Program A86ErrorFilter;

{ you MUST run A86 with the +E command line option! }

Var
  Source : Text;
  FileName : String;
  Index  : Integer;
  SymbolError : Boolean;
  LastLine : String;
  LineNo : Integer;
  Column : Integer;

Function Trim(Line : String) : String;

Begin
  While (Line[1] = ' ') AND (Length(Line) > 0) Do Delete(Line,1,1);
  While Line[Length(Line)] = ' ' Do Dec(Line[0]);
  Trim := Line;
End;

Procedure FindFileName(Var Source : Text;Var Line : String;Var Symbols : Boolean);

Var
  Index : Integer;

Begin
  Line := '';
  While Not Eof(Source) do
  Begin
    LastLine := Line;
    ReadLn(Source,Line);
    If Pos('Error messages inserted into',Line) > 0 Then
    Begin
      Symbols := False;
      Line := Trim(Line);
      Index := Length(Line);
      While(Line[Index]) <> ' ' Do Dec(Index);
      Delete(Line,1,Index);
      Exit;
    End;
    If Pos('Undefined symbols are listed in',Line) > 0 Then
    Begin
      Symbols := TRUE;
      Line := Trim(Line);
      Index := Length(Line);
      While(Line[Index]) <> ' ' Do Dec(Index);
      Delete(Line,1,Index);
      Exit;
    End;
  End;
End;

Function NextLine(Var Source : Text) : String;

Var
  L : String;

Begin
  If Not Eof(Source) Then
  Begin
    ReadLn(Source,L);
    NextLine := L;
    Inc(LineNo);
  End;
End;

Procedure ParseSymbolErrors(FileName : String);

Var
  Line   : String;
  Message : String;

Begin
  Assign(Source,FileName);
  Reset(Source);
  While Not Eof(Source) Do
  Begin
    ReadLn(Source,Line);
    Line := Trim(Line);
    Index := Pos(' ',Line);
    If Index > 0 Then
    Begin
      Message := 'Undefined symbol: '+Copy(Line,1,Pred(Index));
      Delete(Line,1,Index+3);
      WriteLn(Line,', 0, 0, ',Message);
    End;
  End;
  Close(Source);
  Erase(Source);
End;

Procedure ParseOtherErrors(FileName : String);

Var
  Line   : String;

Begin
  Assign(Source,FileName);
  Reset(Source);
  LineNo := 0;
  Line := NextLine(Source);
  If Pos('~',Line) = 1 Then Dec(LineNo);
  While Not Eof(Source) Do
  Begin
    Line := NextLine(Source);
    If Line[Length(Line)] = '~' Then
    Begin
      Dec(LineNo);  { adjust for inserted error message }
      Index := Pred(Length(Line));
      While Line[Index] <> '~' Do Dec(Index);
      Column := Index;
      Delete(Line,1,Index);
      Dec(Line[0]);
      WriteLn(Trim(LastLine),', ',Succ(LineNo),', ',Column,', ','Error #',Line);
    End;
  End;
  Close(Source);
  Erase(Source);
End;

Begin
  Assign(Source,ParamStr(1));
  Reset(Source);
  FindFileName(Source,FileName,SymbolError);
  Close(Source);
  If FileName = '' Then Exit;
  If SymbolError
    Then ParseSymbolErrors(FileName)
  Else ParseOtherErrors(FileName);
End.
