/******************************************
* remtabs V1.0                            *
* (c) John Donoghue, 1997                 *
*                                         *
* portable ansi c version                 *
*
* Licence: GPL - Use and modify as 
*          per the GPL licence,
*******************************************/
#include <stdio.h>
#include <stdlib.h>

#define DEF_TABS  8

void PrintUsage(const char *progname)
{
      printf("usage: %s fromfile tofile [tabnum]\n",progname);
      printf(" * Converts tabs in a text file to spaces.\n");
      printf(" fromfile=source file.\n");
      printf(" tofile=file to save as.\n");
      printf(" tabnum= number of spaces to convert each tab to.\n");
      printf(" * If it is not included then a default of 8 is used.\n");
}
void RemTabs(FILE *from, FILE * to, int tabs)
{
   int read=1;
   int charcount=0;
   int i;
   char c;

   read=fscanf(from,"%c",&c);
   printf("converting tabs....\n");
   while(read>0) {
      switch(c) {
         case 10:
         case 11:
         case 12:
         case 13: /* new line stuff */
            charcount=0;
            break;
         case '\t': /* tab */
            i=charcount%tabs;
            i=tabs-i;
            charcount+=i;
            c=' ';
            while(i>1) {
               i--;
               fprintf(to,"%c",c);
            }
            break;
         case 0:  /* dont count null byte */
            break;
         default:
            charcount++;
      }
      read=fprintf(to,"%c",c);
      if(read<1) {
         printf("Error writing dest file!\n");
         break;
      }
      read=fscanf(from,"%c",&c);
   }

}
int main(int argc,char **argv)
{
   FILE *to=0;
   FILE *from=0;
   int tabs = 0;


   printf("remtabs V1.0\n(c) John Donoghue, 1997\n");

   if(argc<=2) {
   	PrintUsage(argv[0]);
    exit(0);
   }

   // no real parsing done here ... I will do one day.
   // at the moment it assumes that the user knows what they are 
   // doing.
   if(argc>3) {
      tabs=atoi(argv[3]);
   }
   if(tabs==0) {
      printf("Using default tab-space ratio.\n");
      tabs=DEF_TABS;
   }
   else if(tabs>20) {
      printf("specified tab size is too big - using max size of 20.\n");
      tabs = 20;
   }
   else printf("tabs to space ratio=%d\n",tabs);

   from=fopen(argv[1],"r");
   if(from==0) {
      printf("Error: Cant open source file '%s'.\n",argv[1]);
   }
   to=fopen(argv[2],"w");
   if(to==0) {
      printf("Error: Cant open dest file '%s'.\n",argv[2]);
   }

   if(from && to)
   {
     RemTabs(from, to, tabs);

     printf("finished.\n");
   }

   if(from!=0)   fclose(from);
   if(to!=0)     fclose(to);

   return(0);
}
