// untab.c                    1523                        7/25/98 

// A quick program to replace "tabs" with a number of spaces. 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *infile;
FILE *linecount;
FILE *outfile;

char infilename[50], otext[300], outfilename[60], text[201];
char command[80], in_line[50];
int count, m, n, p, q, length, linum, lines;

int main(int argc, char *argv[])
	{
	if(argc < 3)
		{
		if((argc == 2) && (strstr(argv[1], "h")))
			{
			printf("\n\n\tUSAGE: untab <filename> n\n");
			printf("\tReplace each tab in file with \"n\" spaces.\n\n");
			return 0;
			}
		printf("\n\n\tUSAGE: untab filename n\n\n");
		return 0;			
		}
	
	count = atoi(argv[2]);
	
	if((count < 1) || (count > 10))
		{
		printf("\n\n\tn must be from 1 to 10!\n\n");
		return 1;
		}	

	strcpy(infilename, argv[1]);
	
	infile = fopen(infilename, "rt");
	
	if(!infile)
		{
		printf("\n\n\tCan't open %s!\n\n", infilename);
		getchar();
		return 1;
		}
		
	outfile = fopen("untab.asc", "wt");
		
	if(!outfile)
		{
		printf("\n\n\tCan't open output file!\n\n");
		getchar();
		return 1;
		}	
		
	while(!feof(infile))
		{
		fgets(text, 200, infile);
		if(!strchr(text, 9)) 
               {
               fputs(text, outfile); // no tabs 
               fflush(outfile);      // TEST FUNCTION!!! 
               }
		else
			{
			for(m=0, n=0; m < strlen(text); m++, n++)
				{
				if(text[m] != 9) otext[n] = text[m];
				else 
                         {
                         for(p=0; p < count; n++, p++) otext[n] = 32;
                         n--; // excess increment 
                         }
				}
			fputs(otext, outfile); // write converted string 
               for(q=0; q < 300; q++) otext[q] = 0; // clear otext 
               fflush(outfile);      // TEST FUNCTION!!! */               
			}	
		}			
		
	fclose(infile);
	fclose(outfile);
     
     sprintf(command, "mv -f untab.asc %s\n", infilename);
     system(command);
	
	return 0;
	}
