/************************************************************
  Program: RESEQPAT.C
  Written: Michael Johnson
  Created: 10/8/87

  This program was written to resequence a Silos pattern
  file.  The program looks for a digit in the first column
  and replaces it with the current value of the counter.
  In addition if a "$+N", where "N" is a number, the value
  of N is added to the counter.  This is useful when waiting
  for a clock.
  The command line is as follows:

  reseqpat infile [outfile] [#start] [+delta]

  An output file is optional.  If none is given the output
  will be written to default.pat.  An "start" will be the 
  time of the first vector and will increment by "delta"
  thereafter.
************************************************************/

#include	<stdio.h>

#define		MAXLNLEN	132
#define		NSTART		10000
#define		NDELTA		10000
#define		DFLTFN		"default.pat"

index(s,c)
char *s,c;
{
int  i;

   for(i=0; *s != c && *s != '\t' && *s != '\o'; i++,s++);
   return(i);
}
   
main(argc,argv)
int  argc;
char *argv[];
{
FILE *fopen(),*fi,*fo;
char line[MAXLNLEN],
     temp[MAXLNLEN];
int  start = NSTART,
     delta = NDELTA,
     len;

   if (argc == 1)
   {
      fprintf(stderr,"Usage: reseqpat infile [outfile] [#start] [+delta]");
      exit(1);
   }
   
   if ((fi = fopen(*++argv,"r")) == NULL)
   {
      printf("\nError opening input file.");
      exit(1);
   }
   
   fo = NULL;
   argc--;
   while (--argc > 0)
   {
   argv++;
   switch (*argv[0])
      {
      case '#': {
                sscanf(*argv+1,"%d",&start);
                break;
                }
      case '+': {
                sscanf(*argv+1,"%d",&delta);
                break;
                }
      default : 
                if ((fo = fopen(*argv,"w")) == NULL)
                {
                   printf("\nError opening %s as output.",*argv+1);
                   fclose(fi);
                   exit(1);
                 }
      }
   }

   if (fo == NULL)
      if ((fo = fopen(DFLTFN,"w")) == NULL)
      {
         printf("\nError opening %s as output.",DFLTFN);
         fclose(fi);
         exit(1);
      }

   while(fgets(line,MAXLNLEN,fi) != NULL)
   {
      if (line[0] >= '0' && line[0] <= '9')
      {
         len = index(line,' ');
         sprintf(temp,"%08d ",start);
         start += delta;
         strcat(temp,line+len+1);
         fputs(temp,fo);
      }
      else
      {
         fputs(line,fo);
         if (line[1] == '+' && line[0] == '$')
         {
            sscanf(line+2,"%d",&len);
            start += len - delta;
         }
      }
   }
   fclose(fi);
   fclose(fo);
}
