{ macrored.pas   use Turbo Pascal to compile  }
{ redcode macro preprocessor by Nandor Sieben }
{ aznxs@asuacad.bitnet                        }

uses dos;
var fin,fout:text;
    dir,name,ext,outstr,s,ss:string;
    index:integer;
    tomb:array[1..100] of string[80];
    tpoint,i,j,k:integer;
    szam:string[3];
begin
if paramcount=0 then begin
   writeln('Redcode macroprocessor by Nandor Sieben   4/18/1993');
   writeln('Usage:');
   writeln('macrored infile.ext [ outfile.ext ] ');
   writeln;
   writeln('You can use the following macro :');
   writeln('         for 3         ;the compile variable "for" goes from 1 to 3');
   writeln('LABELfor dat #for*2-1  ;"for" will be substituted by the actual value');
   writeln('         rof           ;end of for');
   halt(1);
end;
assign(fin,paramstr(1));
{$i-}
reset(fin);
{$i+}
if ioresult<>0 then begin
   writeln('******* Macrored error *******');
   writeln;
   writeln('File does not exist');
   halt(2);
end;
outstr:=paramstr(2);
if outstr='' then begin
   fsplit(paramstr(1),dir,name,ext);
   if ext<>'.red' then
      outstr:=dir+name+'.red'
   else outstr:=dir+name+'.sed';
end;
assign(fout,outstr);
rewrite(fout);
while not eof(fin) do begin
      readln(fin,s);
      index:=pos('for',s);
      if index=0 then
         writeln(fout,s)
      else begin
           inc(index,3);
           while s[index]=' ' do inc(index);
           ss:=copy(s,index,length(s)-index+1)+'  ';
           while ss[length(ss)]=' ' do dec(ss[0]);
           val(ss,k,i);
           if i<>0 then begin
              writeln('******* Macrored error *******');
              writeln;
              writeln('Bad "for" parameter');
              writeln('"',s,'"');
              halt(3);
           end;
           tpoint:=0;
           repeat
                 readln(fin,s);
                 inc(tpoint);
                 tomb[tpoint]:=s;
           until (pos('rof',s)<>0) or eof(fin);
           for j:=1 to k do begin
               str(j,szam);
               case length(szam) of
                    1 : szam:='00'+szam;
                    2 : szam:='0'+szam;
               end;
               for i:=1 to tpoint-1 do begin
                   s:=tomb[i];
                   repeat
                         index:=pos('for',s);
                         if index<>0 then begin
                            s[index]:=szam[1];
                            s[index+1]:=szam[2];
                            s[index+2]:=szam[3];
                         end;
                   until index=0;
                   writeln(fout,s);
               end;
           end;
      end;

end;
close(fin);
close(fout);
halt(0);
end.
