program Con2Case;
{ Converts names of constats to strings assigned by case statement;
  use con2case.tp to compile this (or DEFINE TINY) }
uses StrStrm, FileType, Fileu, MyType, Stru;

procedure Conv(infilename, outfilename, prefix: string);
var
  ss:TStringStream;
  basename,s:string;
  i:integer;
  inf,outf:text;
  doit:boolean;
  isInSection:boolean;
const indent = '  ';
begin
 {$I-}
  assign(inf, infilename);
  reset(inf);
  if ioresult <> 0 then begin
    writeln(infilename, ' not found.');
    exit;
  end;
  assign(outf, outfilename);
  rewrite(outf);
  if ioresult <> 0 then begin
    writeln('Can not create file ' + outfilename);
    exit;
  end;
  basename := GetFileNamePart(fpBaseName, infilename);
  i := pos('TYPE', UsUppcase(basename));
  if i > 0 then
    basename := copy(basename, 1, i - 1);
  isInSection := false;
  writeln(outf, '{Generated by command: "con2case ' + infilename + ' ' +
    outfilename + ' ' + prefix + '"}');
  writeln(outf, 'function ' + BaseName + 'ErrorMessage(i:integer):string;');
  writeln(outf, 'var s:string;');
  writeln(outf, 'begin');
  writeln(outf, indent + 'case i of');
  while not eof(inf) do begin
    readln(inf, s);
    ss.init(s);
    ss.ReadString(s, sizeof(s));

    doit := true;
    if prefix <> '' then begin
      if IsInSection then begin
        if pos('{/'+prefix, s) = 1 then
          break;
        doit := (pos(prefix, s) = 1);
      end else begin
        doit := false;
        if pos('{' + prefix, s) = 1 then
          IsInSection := true;
      end;
    end;

    if doit then
      writeln(outf, indent + '  ' + s + ' : s := '+ chr(39) + s + chr(39) + ';');
    ss.done;
  end;
  writeln(outf, indent + 'else');
  writeln(outf, indent + '  s := IntToStr(i);');
  writeln(outf, indent + 'end;');
  writeln(outf, indent + BaseName + 'ErrorMessage := s;');

  writeln(outf, 'end;');
  writeln(outf, '{/Generated by command: "con2case...}');
  close(outf);
  close(inf);

end;

begin
  if paramcount < 2 then begin
    writeln('Usage: Con2Case infile outfile [prefix]');
    writeln(' infile format:');
    writeln;
    writeln(' [prefix]const1 = 1;');
    writeln(' [prefix]const2 = 2;');
    writeln(' ...');
    writeln;
    writeln(' outfile format:');
    writeln;
    writeln(' case i of ');
    writeln('   const1 : s := '+chr(39) + '[prefix]const1' + chr(39) + ';');
    writeln('  ...');
    writeln(' end;');
    writeln;
    writeln('  If prefix defined, then only section between ');
    writeln('  lines starting "{prefix" and "{/prefix" are taken in account');
    writeln('  and only lines that start with "  prefix" are included in outfile.');
    exit;
  end;
  conv(paramstr(1), paramstr(2), paramstr(3));
end.