{ 11_pgn_reading.pas -- reading a game from a PGN file.
  Pascal translation of ../examples/11_pgn_reading.c.

  Function demonstrated:
    SANRGSingle(filename, &game_count) -- read and replay exactly
        one game from a PGN file, leaving the SAN Kit's global game
        state (board, tags, history) exactly as it was at the end
        of that game.

  Usage: 11_pgn_reading <file.pgn>

  This is the one example that reads a tag's tag_value field
  directly (via TTag/PTag, sankit.pas) rather than just handing the
  tag pointer on to another SAN Kit call the way 09_pgn_tags.pas
  does. }

{$H+}
program pgn_reading;

uses
  SanKit;

function PadRight(const s: string; Width: Integer): string;
begin
  PadRight := s;
  while Length(PadRight) < Width do
    PadRight := PadRight + ' ';
end;

procedure PrintTag(const name: string);
var
  tagptr: PTag;
begin
  tagptr := SANTagLocate(PChar(name));
  if (tagptr <> nil) and (tagptr^.tag_value <> nil) then
    WriteLn('  ', PadRight(name, 8), tagptr^.tag_value);
end;

var
  flag, gn: LongInt;

begin
  if ParamCount <> 1 then
    begin
      WriteLn(ErrOutput, 'usage: ', ParamStr(0), ' <file.pgn>');
      Halt(1);
    end;

  SANInit;
  optnv[optn_nabd] := 1;
  optnv[optn_namd] := 1;

  flag := SANRGSingle(PChar(AnsiString(ParamStr(1))), @gn);
  if flag = 0 then
    begin
      WriteLn(ErrOutput, ParamStr(0), ': could not read a game from ',
              ParamStr(1));
      Halt(1);
    end;

  WriteLn('Read ', gn, ' game(s) from ', ParamStr(1),
          '. Tags of the last one read:');
  PrintTag('Event');
  PrintTag('White');
  PrintTag('Black');
  PrintTag('Result');

  WriteLn;
  WriteLn('Final position: ', SANFENGen);
end.
