{ 09_pgn_tags.pas -- PGN header tags and writing a game score.
  Pascal translation of ../examples/09_pgn_tags.c.

  Functions demonstrated:
    SANTagLocate() -- find a tag by name (e.g. "White", "Event")
    SANTagUpdate() -- change a tag's value
    SANPGNEventReport() -- write the current game (tags + move text)
                           as PGN to a FILE*

  SANPGNEventReport() writes to a C stdio FILE*, a type this unit
  has no Pascal representation for at all -- StdOutAsCFile()
  (sankit.pas, a thin wrapper over fdopen(1, "w")) is what gets one
  for this process's own stdout; see its own header comment there
  for why it's obtained that way rather than more directly. }

{$H+}
program pgn_tags;

uses
  SanKit;

procedure PascalToSanBuf(const s: string; var buf: TSanBuf);
var
  i, n: Integer;
begin
  FillChar(buf, SizeOf(buf), 0);
  n := Length(s);
  if n > sanL - 1 then
    n := sanL - 1;
  for i := 1 to n do
    buf[i - 1] := s[i];
end;

procedure Play(const text: string);
var
  buf: TSanBuf;
  mptr: PMove;
begin
  PascalToSanBuf(text, buf);
  mptr := SANDecodeAux(SanBufPtr(buf));
  SANPlayMove(mptr);
end;

procedure SetTag(const name, value: string);
var
  tagptr: PTag;
begin
  tagptr := SANTagLocate(PChar(name));
  if tagptr <> nil then
    SANTagUpdate(tagptr, PChar(value));
end;

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

  Play('e4'); Play('c5'); Play('Nf3'); Play('d6');
  Play('d4'); Play('cxd4'); Play('Nxd4'); Play('Nf6');
  Play('Nc3');

  SetTag('Event', 'SAN Kit examples');
  SetTag('Site', '?');
  SetTag('Date', '????.??.??');
  SetTag('Round', '9');
  SetTag('White', 'Example Program');
  SetTag('Black', 'Example Program');
  SetTag('Result', '*');

  Flush(Output);
  SANPGNEventReport(StdOutAsCFile);
  FlushCOutput(nil);
end.
