/* entab.c - a program to change runs of spaces in a file to a TAB character.

	Usage:  entab from_file to_file

By  Ron Charlton   20-FEB-88  (taken from a program ENTAB.BAS by uSOFT)
    9002 Balcor Circle
    Knoxville, TN 37923

   CIS 71450,3216
*/

#include "stdio.h"

#define TABSIZE 8
#define MAXLINE 255
#define TRUE 1
int tabstops[MAXLINE+1];

void _wb_parse(){} /* null routine to reduce size of executable */

main(argc,argv)
int argc;
char *argv[];
{
register int c, in_column, out_column;
FILE *in, *out, *fopen();

if (argc != 3)
  quit();

if ( (in = fopen(argv[1], "r")) == NULL )
  {
  printf("Can't open input file.\n");
  quit();
  }

if ( (out = fopen(argv[2], "w")) == NULL )
  {
  printf("Can't open output file.\n");
  quit();
  }

SetTabPos();			/* set tab columns */

out_column = 1;

for (;;)			/* exit on end-of-file */
  {
  in_column = out_column;
  /* replace a run of spaces with a TAB when you reach a tab column */
  for (;;)
    {
    if ( ( c = getc(in) ) == EOF ) exit(0);
    if ( c != ' ' && c != '\t' ) break;
    ++in_column;
    if ( c == '\t' || ThisIsATab(in_column))
      {
      if ( (in_column - out_column > 1) || c == '\t' )	/* no tab if 1 space */
        {
        if ( putc('\t', out)  == EOF )	/* output a TAB */
          cantwrite();
        }
      else
        if ( putc(' ', out) == EOF )	/* output a SPACE */
          cantwrite();
      /* go to a tab column if we have a tab and this is not a tab column */
      while ( !ThisIsATab(in_column) )
        ++in_column;
      out_column = in_column;
      }
    }
  /* output spaces left over */
  while ( out_column < in_column )
    {
    if ( putc(' ', out) == EOF )
          cantwrite();
    ++out_column;
    }
  /* output the non-space character */
  if ( putc(c, out) == EOF )
    cantwrite();
  /* reset column position if this is the end of the line */
  if ( c == '\n' )
    out_column = 1;
  else
    ++out_column;
  }
}


SetTabPos()
{
/* set tab positions in array tabstops */
int i;
for (i=1; i <= 255; i++)
  tabstops[i] = ( ( i % TABSIZE ) == 1 );
}


ThisIsATab(column)
int column;
{
/* is this a tab column? */
if ( column > MAXLINE )
  return(TRUE);
else
  return(tabstops[column]);
}
 

cantwrite()
{
/* some error has occurred on output file */
printf("Can't complete output file.\n");
exit(20);
}


quit()
{
printf("Usage:  entab in_file out_file\n");
exit(20);
}
