
uses
  SysUtils, Classes;

const
  CMaxMoves = 3;
  
var
  LMoves: array[1..CMaxMoves] of string;

procedure PrintLine(const AMoveCount: integer);
var
  LList: TStringList;
  i: integer;
begin
  Write(Format('PrintLine(%d): ', [AMoveCount]));
  LList := TStringList.Create;
  LList.Delimiter := ' ';
  for i := 1 to AMoveCount do
     LList.Append(LMoves[i]);
  WriteLn(LList.DelimitedText);
  LList.Free;
end;

var
  LIndex: integer;
  LDone: boolean;
  
procedure Store(const AIndex: integer; const AStr: string);
begin
  WriteLn(Format('Store(%d,%s)', [AIndex, AStr]));
  
  if AIndex > LIndex then
  begin
    LMoves[AIndex] := AStr;
    LDone := FALSE;
  end else
    WriteLn('REM Skip step 1');
  
  if AIndex < LIndex then
    if LDone then
      WriteLn('REM Skip step 2')
    else
    begin
      PrintLine(Succ(AIndex));
      LDone := TRUE;
    end;
  
  LIndex := AIndex;
end;

procedure Demo(const ATree: string);
var
  LLen, LLevel, LPos: integer;
  LData: string;
  c: char;
begin
  LLevel := 0;
  LPos := 1;
  LData := '';
  LLen := Length(ATree);
  while LPos <= LLen do
  begin
    c := ATree[LPos];
    case c of
      '(': begin Write('"(" '); Store(LLevel, LData); Inc(LLevel); LData := ''; end;
      ')': begin Write('")" '); Store(LLevel, LData); Dec(LLevel); LData := ''; end;
      else LData := LData + c;
    end;
    Inc(LPos);
  end;
  Store(0, '');
end;

const
  //CSample = '(e2e4(e7e5(d2d4))(c7c5))(d2d4(d7d5))';
  CSample = '(e2e4(e7e5(d2d4))(c7c5))(d2d4(d7d5))(e2e3)';
  
begin
  LIndex := 0;
  LDone := FALSE;
  Demo(CSample);
end.
