/* macrored.c                                  *
 * redcode macro preprocessor by Nandor Sieben *
 * aznxs@asuacad.bitnet                        */


#include "stdio.h"
#include "stdlib.h"
#define STRSIZ 200
#include "string.h"

FILE             *fin , *fout;
    char         dir[STRSIZ], name[STRSIZ], ext[STRSIZ], outstr[STRSIZ], s[STRSIZ], ss[STRSIZ];
    char         *index;
    char         tomb[100][81];
    int          tpoint, i, j, k;
    char         number[4],number1[4];

main(int   argc,
     char  *argv[])
{
if ( ( argc < 3 ) || ( ! strcmp(argv[1],argv[2] ) )) {
   printf("\nRedcode macroprocessor by Nandor Sieben   4/25/1993\n");
   printf("Usage:\n");
   printf("macrored infile outfile \n");
   printf("\n");
   printf("You can use the following macro :\n");
   printf("         for 3         ;the compile variable \"for\" goes from 1 to 3\n");
   printf("LABELfor dat #for*2-1  ;\"for\" will be substituted by the actual value\n");
   printf("         rof           ;end of for\n");
   exit(1);
}
if ( (fin = fopen(argv[1],"r") ) == NULL) {
   printf("******* Macrored error *******\n");
   printf("\n");
   printf("File does not exist\n");
   exit(2);
};
strcpy(outstr,argv[2]);
if ( (fout = fopen(argv[2],"w") ) == NULL) {
   printf("******* Macrored error *******\n");
   printf("\n");
   printf("Can't create file\n");
   exit(3);
};

while (!feof(fin)) {
      fgets(s,STRSIZ,fin);
      index = strstr(s,"for");
      if (index == NULL)
	 fprintf(fout,"%s",s);
      else {
	   index += 3;
	   sscanf(index,"%d",&k);
	   if (k <= 0) {
              printf("******* Macrored error *******\n");
              printf("\n");
              printf("Bad \"for\" parameter\n");
	      printf("%s",s);
              exit(3);
           }
           tpoint = 0;
           do {
		 fgets(s,STRSIZ,fin);
		 tpoint++;
		 strcpy(tomb[tpoint],s);
	   }  while (!((strstr(s,"rof") != NULL) || feof(fin)));
           for (j = 1; j <= k; j++) {
	       sprintf(number1,"%d",j);
	       switch (strlen(number1)) {

		    case 1:   strcpy(number,"00");
                    break;

		    case 2:   strcpy(number,"0");
		    break;
	       }
	       strcat(number,number1);
	       for (i = 1; i < tpoint ; i++) {
		   strcpy(s,tomb[i]);
                   do {
			 index = strstr(s,"for");
			 if (index != NULL) {
			    index[0] = number[0];
			    index[1] = number[1];
			    index[2] = number[2];
                         }
                   }  while (!(index == 0));
		   fprintf(fout,"%s",s);
               } 
           } 
      } 

} 
fclose(fin); 
fclose(fout); 
exit(0);
}

