# include "align.h"
# include <stdio.h>

/* externals */
 /* from slurp.c */
extern void fetchline();
extern char nextchar();
extern char peekchar();
extern int eoln();
extern FILE *outstream;

 /* from words.c */
extern void readword_col();
extern void init_store();

/* externals from errors.c */
extern goof(); /* error-writing routine
  void goof(char *s); */
extern int sinned, error; /* error-flags */


/* local word-ending function */
static int endword(c)
char c;
{
 char d;
 if (eoln() || ((c == ' ' && ((d = squizchar()) == ' ' || d == '\n')))
   || c == '|')
   return(TRUE);
 else
  return(FALSE);
}

/* skips over `|''s and blanks, getting width */
static int chewspace()
{
  int count;
  char c;

  count = 0;
  if (!eoln()) {
    while ((c = squizchar()) == ' ' || c == '|') {
      count++;
      nextchar();
    }
  }
  return(count);
}


do_word()
{
  word holder;
  int space;
  int stop;

  if (!eoln()) {
    init_store();
    readword_col(&holder,&stop,endword,nextchar);
/* printf("word = %s;  eol = %d\n",holder.loc,eoln()); */
    space = chewspace();
/*    printf("chewed space %d:: eol = %d\n",space,eoln());  */
    if (!error) {
      if (eoln()) {
        fprintf(outstream,"%s",holder.loc);
      }
      else {
	space = space+holder.size+1;
        fprintf(outstream,"\\cbx{%d}{%s}",space,holder.loc);
      }
    }
  }
}

do_line()
{
  int initspace;

  initspace = chewspace();
  if (!eoln() && initspace > 0)
     fprintf(outstream,"\\cbx{%d}{}",initspace);
  while (!eoln())
    do_word();
  fprintf(outstream, "\\\\\n");
}


/* top-level routine,  that reads in lines until it encounters
  end-of-example or eof */

void columns()
{
  int go;

  error = FALSE;
  go = TRUE;
  while (go) {
    fetchline();

    if (matchstr(".>"))
      go = FALSE;
    if (eof()) {
      goof("file ends in example");
      go = FALSE;
    }
    if (go) do_line();
  }
}

/*
char delmark = '\\';
int  wordmax = 60;

main()
{
word sample;
int stop;
int s;

get_com_widths("widths.dat");
open_source("text.dat");
init_store();

advance();
readword_col(&sample,&stop,endword,nextchar);
printf("%s, size = %d, bracket= %d\n",sample.loc,sample.size,sample.bracket);
if (stop) printf("stop!\n");
}
*/