{ RPX - file transfer for RETRO-PORT, by its serial API (RPAPI 1).
  For the IBM PC, PC/XT and compatibles: 8088, DOS 2 or later.
  Turbo Pascal 6 (or 7):  TPC RPX.PAS

  RPX [options] [command [arguments]]
    DIR [path]          list a folder on RETRO-PORT's SD card
    GET remote [local]  copy a file from the card to the PC
    PUT local [remote]  copy a file from the PC to the card
    FETCH url [path]    have RETRO-PORT download a URL to its card
    DEL path, MD folder, REN old new, CD folder
    TIME                RETRO-PORT's clock;  SETTIME sets the PC's clock from it
    STATUS, FREE
  With no command, RPX asks for commands (QUIT leaves). Anything it doesn't
  know goes to RETRO-PORT as typed, so every API command can be tried.

  Options: /1 /2 /3 /4 serial port (COM1), /B:9600 speed, /K:1024 block
  size, /H hex mode (7-bit lines).

  The spec: http://n9taxretrolab.net/api/   (RPAPI.TXT) }

program RPX;

{$M 8192,0,65536}
{$I-}
{$R-}
{$S-}

uses Dos;

const
  RXSIZE = 4096;
  RXMASK = 4095;
  ESC = #27;
  BASES: array[1..4] of word = ($3F8, $2F8, $3E8, $2E8);
  IRQS: array[1..4] of byte = (4, 3, 4, 3);

type
  TBlock = array[0..1023] of byte;

var
  rxbuf: array[0..RXSIZE - 1] of byte;
  rxhead, rxtail: word;
  base: word;
  irq: byte;
  oldvec: pointer;
  oldexit: pointer;
  portopen: boolean;
  crctab: array[0..255] of word;
  blk: TBlock;
  blocksize: word;
  baud: longint;
  comnum: integer;
  hexmode: boolean;
  lasterr: integer;      { the ER code of the last failed command }
  lasttext: string;      { its text }
  apiblock: word;        { BLOCK= from the sign-on }

{ ---------------------------------------------------------------- the UART }

procedure ComISR; interrupt;
begin
  while (Port[base + 5] and 1) <> 0 do
  begin
    rxbuf[rxhead] := Port[base];
    rxhead := (rxhead + 1) and RXMASK;
  end;
  Port[$20] := $20;
end;

procedure ComClose;
begin
  if portopen then
  begin
    Port[base + 1] := 0;
    Port[$21] := Port[$21] or (1 shl irq);
    SetIntVec($08 + irq, oldvec);
    portopen := false;
  end;
end;

{$F+}
procedure RpxExit;
begin
  ComClose;
  ExitProc := oldexit;
end;
{$F-}

procedure ComOpen;
var
  d: word;
  b: byte;
begin
  base := BASES[comnum];
  irq := IRQS[comnum];
  d := 115200 div baud;
  Port[base + 3] := $80;                  { divisor latch }
  Port[base] := Lo(d);
  Port[base + 1] := Hi(d);
  Port[base + 3] := $03;                  { 8 bits, no parity, 1 stop }
  Port[base + 2] := 0;                    { no FIFO: works on an 8250 too }
  rxhead := 0;
  rxtail := 0;
  GetIntVec($08 + irq, oldvec);
  SetIntVec($08 + irq, @ComISR);
  oldexit := ExitProc;
  ExitProc := @RpxExit;
  portopen := true;
  Port[base + 4] := $0B;                  { DTR, RTS, OUT2 (interrupts to the PIC) }
  Port[base + 1] := 1;                    { interrupt when a byte arrives }
  b := Port[base];
  b := Port[base + 5];
  b := Port[base + 6];
  b := Port[base + 2];
  Port[$21] := Port[$21] and not (1 shl irq);
end;

procedure ComPut(c: byte);
begin
  while (Port[base + 5] and $20) = 0 do ;
  Port[base] := c;
end;

procedure ComPutStr(s: string);
var
  i: integer;
begin
  for i := 1 to Length(s) do ComPut(Ord(s[i]));
end;

{ ---------------------------------------------------------------- time and keys }

function Ticks: longint;                  { 18.2 a second, from the BIOS }
begin
  Ticks := MemL[$0040:$006C];
end;

function Since(t0: longint): longint;
var
  d: longint;
begin
  d := Ticks - t0;
  if d < 0 then d := d + 1573040;         { past midnight }
  Since := d;
end;

function EscPressed: boolean;
var
  r: Registers;
begin
  EscPressed := false;
  r.AH := 1;
  Intr($16, r);
  if (r.Flags and FZero) = 0 then
  begin
    r.AH := 0;
    Intr($16, r);
    if r.AL = 27 then EscPressed := true;
  end;
end;

function RxByte(var b: byte; tmo: longint): boolean;
var
  t0: longint;
begin
  t0 := Ticks;
  while rxhead = rxtail do
    if Since(t0) > tmo then
    begin
      RxByte := false;
      Exit;
    end;
  b := rxbuf[rxtail];
  rxtail := (rxtail + 1) and RXMASK;
  RxByte := true;
end;

{ A line from RETRO-PORT, CR LF taken off; blank lines are skipped. }
function RxLine(var s: string; tmo: longint): boolean;
var
  b: byte;
begin
  s := '';
  RxLine := false;
  repeat
    if not RxByte(b, tmo) then Exit;
    if b = 10 then
    begin
      if s <> '' then
      begin
        RxLine := true;
        Exit;
      end;
    end
    else if (b <> 13) and (Length(s) < 255) then s := s + Chr(b);
  until false;
end;

{ ---------------------------------------------------------------- CRC-16/XMODEM }

procedure CrcInit;
var
  i, j: integer;
  c: word;
begin
  for i := 0 to 255 do
  begin
    c := i shl 8;
    for j := 1 to 8 do
      if (c and $8000) <> 0 then c := (c shl 1) xor $1021 else c := c shl 1;
    crctab[i] := c;
  end;
end;

function Crc16(var d: TBlock; n: word): word;
var
  i: word;
  c: word;
begin
  c := 0;
  if n > 0 then
    for i := 0 to n - 1 do
      c := (c shl 8) xor crctab[(c shr 8) xor d[i]];
  Crc16 := c;
end;

{ ---------------------------------------------------------------- small helpers }

function Upper(s: string): string;
var
  i: integer;
begin
  for i := 1 to Length(s) do s[i] := UpCase(s[i]);
  Upper := s;
end;

function Word1(var s: string): string;    { take the first word off s }
var
  i: integer;
  w: string;
begin
  while (s <> '') and (s[1] = ' ') do Delete(s, 1, 1);
  if (s <> '') and (s[1] = '"') then
  begin
    Delete(s, 1, 1);
    i := Pos('"', s);
    if i = 0 then i := Length(s) + 1;
    w := Copy(s, 1, i - 1);
    Delete(s, 1, i);
  end
  else
  begin
    i := Pos(' ', s);
    if i = 0 then i := Length(s) + 1;
    w := Copy(s, 1, i - 1);
    Delete(s, 1, i);
  end;
  while (s <> '') and (s[1] = ' ') do Delete(s, 1, 1);
  Word1 := w;
end;

function Quote(s: string): string;        { names may have spaces }
begin
  if Pos(' ', s) > 0 then Quote := '"' + s + '"' else Quote := s;
end;

function NumStr(n: longint): string;
var
  s: string;
begin
  Str(n, s);
  NumStr := s;
end;

function StrNum(s: string): longint;
var
  n: longint;
  e: integer;
begin
  Val(s, n, e);
  if e <> 0 then n := -1;
  StrNum := n;
end;

function HexNum(s: string): longint;
var
  n: longint;
  i, v: integer;
begin
  n := 0;
  for i := 1 to Length(s) do
  begin
    v := Pos(UpCase(s[i]), '0123456789ABCDEF') - 1;
    if v < 0 then
    begin
      HexNum := -1;
      Exit;
    end;
    n := n * 16 + v;
  end;
  HexNum := n;
end;

function Hex4(w: word): string;
const
  H: string[16] = '0123456789ABCDEF';
begin
  Hex4 := H[(w shr 12) + 1] + H[((w shr 8) and 15) + 1] + H[((w shr 4) and 15) + 1] + H[(w and 15) + 1];
end;

function BaseName(s: string): string;     { the part after the last / or \ }
var
  i: integer;
begin
  for i := Length(s) downto 1 do
    if (s[i] = '/') or (s[i] = '\') or (s[i] = ':') then
    begin
      BaseName := Copy(s, i + 1, 255);
      Exit;
    end;
  BaseName := s;
end;

{ ---------------------------------------------------------------- the protocol }

{ Send a command and read its reply. Data lines ("= ...") are printed when
  show is true. st gets what follows OK (or the whole GO / DATA line).
  False on ER (lasterr, lasttext) or no answer. }
function Command(c: string; show: boolean; var st: string; tmo: longint): boolean;
var
  ln: string;
begin
  Command := false;
  if c <> '' then ComPutStr(c + #13);     { '' = only wait for the status line }
  repeat
    if not RxLine(ln, tmo) then
    begin
      lasterr := 0;
      lasttext := 'RETRO-PORT did not answer';
      Exit;
    end;
    if Copy(ln, 1, 2) = '= ' then
    begin
      if show then WriteLn(Copy(ln, 3, 255));
    end
    else if (ln = 'OK') or (Copy(ln, 1, 3) = 'OK ') then
    begin
      st := Copy(ln, 4, 255);
      Command := true;
      Exit;
    end
    else if (ln = 'GO') or (Copy(ln, 1, 5) = 'DATA ') then
    begin
      st := ln;
      Command := true;
      Exit;
    end
    else if Copy(ln, 1, 3) = 'ER ' then
    begin
      lasterr := StrNum(Copy(ln, 4, 3));
      lasttext := Copy(ln, 8, 255);
      Exit;
    end;
    { anything else is left over from the menus: skip it }
  until false;
end;

{ Wake RETRO-PORT, then HELLO with a word of our own: the sign-on that ends
  with it is the reply to this HELLO, so an earlier one still on its way
  (a wake answered late, or answered twice) is skipped. }
function Wake: boolean;
var
  tries: integer;
  ln, tag: string;
  t0: longint;
  woke: boolean;
begin
  Wake := false;
  for tries := 1 to 4 do
  begin
    rxtail := rxhead;
    ComPutStr(#22#22'RPAPI'#13);
    t0 := Ticks;
    woke := false;
    while (Since(t0) < 55) and not woke do       { 3 seconds }
      if RxLine(ln, 55 - Since(t0)) then
        woke := Copy(ln, 1, 9) = 'OK RPAPI ';
    if woke then
    begin
      tag := 'RPX' + NumStr(Ticks and 32767);
      ComPutStr('HELLO ' + tag + #13);
      t0 := Ticks;
      while Since(t0) < 182 do                   { 10 seconds }
        if RxLine(ln, 182 - Since(t0)) then
          if (Copy(ln, 1, 9) = 'OK RPAPI ') and (Copy(ln, Length(ln) - Length(tag), 255) = ' ' + tag) then
          begin
            apiblock := 1024;
            if Pos('BLOCK=', ln) > 0 then
              apiblock := StrNum(Copy(ln, Pos('BLOCK=', ln) + 6, 4));
            if blocksize > apiblock then blocksize := apiblock;
            Wake := true;
            Exit;
          end;
    end;
  end;
end;

function Fail(what: string): boolean;
begin
  if lasterr <> 0 then WriteLn(what, ': error ', lasterr, ' ', lasttext)
  else WriteLn(what, ': ', lasttext);
  Fail := false;
end;

{ The data after a DATA line: n bytes raw, or hex lines in hex mode. }
function RxBlock(n: word): boolean;
var
  i, k: word;
  b: byte;
  ln: string;
begin
  RxBlock := false;
  i := 0;
  if not hexmode then
    while i < n do
    begin
      if not RxByte(blk[i], 182) then Exit;
      Inc(i);
    end
  else
    while i < n do
    begin
      if not RxLine(ln, 182) then Exit;
      k := 1;
      while (k < Length(ln)) and (i < n) do
      begin
        blk[i] := HexNum(Copy(ln, k, 2));
        Inc(i);
        Inc(k, 2);
      end;
    end;
  RxBlock := true;
end;

procedure TxBlock(n: word);
const
  H: string[16] = '0123456789ABCDEF';
var
  i: word;
begin
  if not hexmode then
  begin
    if n > 0 then
      for i := 0 to n - 1 do ComPut(blk[i]);
  end
  else if n > 0 then
  begin
    for i := 0 to n - 1 do
    begin
      ComPut(Ord(H[(blk[i] shr 4) + 1]));
      ComPut(Ord(H[(blk[i] and 15) + 1]));
      if ((i mod 32) = 31) or (i = n - 1) then ComPutStr(#13#10);
    end;
  end;
end;

{ ---------------------------------------------------------------- commands }

{ OPEN: the handle and the file's size }
function OpenRemote(name, mode: string; var h: integer; var size: longint): boolean;
var
  st: string;
begin
  OpenRemote := false;
  if not Command('OPEN ' + Quote(name) + ' ' + mode, false, st, 182) then Exit;
  h := StrNum(Word1(st));
  size := StrNum(Word1(st));
  OpenRemote := true;
end;

procedure CloseRemote(h: integer);
var
  st: string;
begin
  if Command('CLOSE ' + NumStr(h), false, st, 182) then ;
end;

procedure Progress(done, total: longint);
begin
  Write(#13, done, ' of ', total, ' bytes');
end;

function DoGet(remote, local: string): boolean;
var
  h, tries: integer;
  size, off, n: longint;
  st, w: string;
  f: file;
  crc: longint;
  ok: boolean;
begin
  DoGet := false;
  if local = '' then
  begin
    { the card's 8.3 name, if the file has one: DOS can use it as it is }
    local := BaseName(remote);
    if Command('STAT ' + Quote(remote), false, st, 182) then
    begin
      w := Word1(st); w := Word1(st); w := Word1(st); w := Word1(st);
      w := Word1(st);
      if w <> '-' then local := w;
    end;
  end;
  if not OpenRemote(remote, 'R', h, size) then
  begin
    DoGet := Fail(remote);
    Exit;
  end;
  Assign(f, local);
  Rewrite(f, 1);
  if IOResult <> 0 then
  begin
    WriteLn('Cannot create ', local);
    CloseRemote(h);
    Exit;
  end;
  WriteLn(remote, ' -> ', local);
  off := 0;
  ok := true;
  repeat
    tries := 0;
    repeat
      Inc(tries);
      n := -1;
      if not Command('READ ' + NumStr(h) + ' ' + NumStr(off) + ' ' + NumStr(blocksize), false, st, 182) then
      begin
        ok := Fail('READ');
        tries := 99;
      end
      else
      begin
        w := Word1(st);                    { DATA }
        n := StrNum(Word1(st));
        crc := HexNum(Word1(st));
        if not RxBlock(n) then
        begin
          WriteLn;
          WriteLn('The data stopped coming.');
          ok := false;
          tries := 99;
        end
        else if Crc16(blk, n) <> crc then
        begin
          if tries >= 3 then
          begin
            WriteLn;
            WriteLn('Block at ', off, ' arrived damaged three times.');
            ok := false;
          end;
          n := -1;
        end;
      end;
    until (n >= 0) or (tries >= 3);
    if ok and (n > 0) then
    begin
      BlockWrite(f, blk, n);
      if IOResult <> 0 then
      begin
        WriteLn;
        WriteLn('Disk full?');
        ok := false;
      end;
      off := off + n;
      Progress(off, size);
      if EscPressed then
      begin
        WriteLn;
        WriteLn('Stopped.');
        ok := false;
      end;
    end;
  until (not ok) or (n <= 0);
  Close(f);
  CloseRemote(h);
  if ok then WriteLn(#13, off, ' bytes received.      ');
  DoGet := ok;
end;

function DoPut(local, remote: string): boolean;
var
  h, tries: integer;
  size, total, off: longint;
  n: word;
  st: string;
  f: file;
  ok, sent: boolean;
begin
  DoPut := false;
  if remote = '' then remote := BaseName(local);
  FileMode := 0;
  Assign(f, local);
  Reset(f, 1);
  FileMode := 2;
  if IOResult <> 0 then
  begin
    WriteLn('Cannot open ', local);
    Exit;
  end;
  total := FileSize(f);
  if not OpenRemote(remote, 'W', h, size) then
  begin
    Close(f);
    DoPut := Fail(remote);
    Exit;
  end;
  WriteLn(local, ' -> ', remote);
  off := 0;
  ok := true;
  while ok and (off < total) do
  begin
    BlockRead(f, blk, blocksize, n);
    if (IOResult <> 0) or (n = 0) then
    begin
      WriteLn('Read error on ', local);
      ok := false;
    end
    else
    begin
      tries := 0;
      sent := false;
      repeat
        Inc(tries);
        if not Command('WRITE ' + NumStr(h) + ' ' + NumStr(off) + ' ' + NumStr(n) + ' ' + Hex4(Crc16(blk, n)),
                       false, st, 182) then
        begin
          ok := Fail('WRITE');
        end
        else
        begin
          TxBlock(n);
          if Command('', false, st, 364) then sent := true    { the status line after the data }
          else if (lasterr <> 412) or (tries >= 3) then ok := Fail('WRITE');
        end;
      until sent or not ok;
      if sent then
      begin
        off := off + n;
        Progress(off, total);
        if EscPressed then
        begin
          WriteLn;
          WriteLn('Stopped.');
          ok := false;
        end;
      end;
    end;
  end;
  Close(f);
  CloseRemote(h);
  if ok then WriteLn(#13, off, ' bytes sent.         ');
  DoPut := ok;
end;

{ DIR, twenty entries a request: RETRO-PORT waits while the PC prints them. }
function DoDir(path: string): boolean;
var
  st, ln, t, size, date, tm, short, long, cmd: string;
  start, files, dirs: longint;
  more: boolean;
begin
  DoDir := false;
  start := 0;
  files := 0;
  dirs := 0;
  if path = '' then path := '.';
  repeat
    cmd := 'DIR ' + Quote(path) + ' ' + NumStr(start) + ' 20';
    ComPutStr(cmd + #13);
    more := false;
    repeat
      if not RxLine(ln, 182) then
      begin
        WriteLn('RETRO-PORT did not answer');
        Exit;
      end;
      if Copy(ln, 1, 2) = '= ' then
      begin
        ln := Copy(ln, 3, 255);
        t := Word1(ln); size := Word1(ln); date := Word1(ln); tm := Word1(ln);
        short := Word1(ln);
        long := ln;
        if short = '-' then short := '';
        while Length(short) < 13 do short := short + ' ';
        if t = 'D' then
        begin
          size := '<DIR>';
          Inc(dirs);
        end
        else Inc(files);
        while Length(size) < 10 do size := ' ' + size;
        WriteLn(short, size, '  ', date, ' ', tm, '  ', long);
        Inc(start);
      end;
    until (Copy(ln, 1, 2) = 'OK') or (Copy(ln, 1, 3) = 'ER ');
    if Copy(ln, 1, 3) = 'ER ' then
    begin
      WriteLn('DIR: error ', Copy(ln, 4, 255));
      Exit;
    end;
    more := Pos('MORE', ln) > 0;
    if EscPressed then more := false;
  until not more;
  WriteLn(files, ' file(s), ', dirs, ' folder(s)');
  DoDir := true;
end;

function DoFetch(url, path: string): boolean;
var
  ln: string;
begin
  DoFetch := false;
  if path <> '' then path := ' ' + Quote(path);
  ComPutStr('FETCH ' + Quote(url) + path + #13);
  WriteLn('Fetching ', url, '   (Esc cancels)');
  repeat
    if EscPressed then ComPut(24);       { CAN: RETRO-PORT stops the download }
    if not RxLine(ln, 18) then ln := '';
    if Copy(ln, 1, 2) = '= ' then Write(#13, Copy(ln, 3, 255), ' bytes   ');
  until (Copy(ln, 1, 2) = 'OK') or (Copy(ln, 1, 3) = 'ER ');
  WriteLn;
  if Copy(ln, 1, 3) = 'ER ' then
    WriteLn('Failed: ', Copy(ln, 8, 255))
  else
  begin
    ln := Copy(ln, 4, 255);
    WriteLn('Saved ', Word1(ln), ' bytes as ', ln);
    DoFetch := true;
  end;
end;

{ TIME: "2026-11-25 14:02:33 3 -0600 CST" }
function DoTime(setpc: boolean): boolean;
var
  st: string;
begin
  DoTime := false;
  if not Command('TIME', false, st, 182) then
  begin
    DoTime := Fail('TIME');
    Exit;
  end;
  WriteLn('RETRO-PORT: ', st);
  if setpc then
  begin
    SetDate(StrNum(Copy(st, 1, 4)), StrNum(Copy(st, 6, 2)), StrNum(Copy(st, 9, 2)));
    SetTime(StrNum(Copy(st, 12, 2)), StrNum(Copy(st, 15, 2)), StrNum(Copy(st, 18, 2)), 0);
    WriteLn('The PC''s clock is set.');
  end;
  DoTime := true;
end;

function Simple(c: string; tmo: longint): boolean;  { print the data lines and the OK text }
var
  st: string;
begin
  if Command(c, true, st, tmo) then
  begin
    if st <> '' then WriteLn(st);
    Simple := true;
  end
  else Simple := Fail(Word1(c));
end;

function Run(line: string): boolean;
var
  verb, a1, a2: string;
begin
  verb := Upper(Word1(line));
  a1 := Word1(line);
  a2 := Word1(line);
  if verb = 'DIR' then Run := DoDir(a1)
  else if verb = 'GET' then Run := DoGet(a1, a2)
  else if verb = 'PUT' then Run := DoPut(a1, a2)
  else if verb = 'FETCH' then Run := DoFetch(a1, a2)
  else if verb = 'TIME' then Run := DoTime(false)
  else if verb = 'SETTIME' then Run := DoTime(true)
  else if verb = 'MD' then Run := Simple('MKDIR ' + Quote(a1), 182)
  else if verb = 'FREE' then Run := Simple('FREE', 10920)
  else
  begin
    { the rest go as typed: DEL, REN, CD, STAT, STATUS, HELP ... }
    if a1 <> '' then verb := verb + ' ' + Quote(a1);
    if a2 <> '' then verb := verb + ' ' + Quote(a2);
    if line <> '' then verb := verb + ' ' + line;
    Run := Simple(verb, 546);
  end;
end;

procedure Usage;
begin
  WriteLn('RPX - files to and from RETRO-PORT (RPAPI 1)');
  WriteLn;
  WriteLn('RPX [/1../4] [/B:9600] [/K:1024] [/H] [command]');
  WriteLn('  DIR [path]   GET remote [local]   PUT local [remote]');
  WriteLn('  FETCH url [path]   DEL   MD   REN   CD   STAT');
  WriteLn('  TIME   SETTIME   STATUS   FREE');
  WriteLn('No command: type them, QUIT to leave.');
  WriteLn('/1-/4 COM port, /B speed, /K block size, /H hex mode');
  Halt(1);
end;

var
  i: integer;
  arg, cmdline, ln, st: string;
  ok: boolean;

begin
  comnum := 1;
  baud := 9600;
  blocksize := 1024;
  hexmode := false;
  cmdline := '';
  for i := 1 to ParamCount do
  begin
    arg := ParamStr(i);
    if (arg[1] = '/') and (cmdline = '') then
    begin
      arg := Upper(arg);
      if (arg[2] >= '1') and (arg[2] <= '4') then comnum := Ord(arg[2]) - 48
      else if Copy(arg, 1, 3) = '/B:' then baud := StrNum(Copy(arg, 4, 6))
      else if Copy(arg, 1, 3) = '/K:' then blocksize := StrNum(Copy(arg, 4, 5))
      else if arg = '/H' then hexmode := true
      else Usage;
    end
    else
    begin
      if cmdline <> '' then cmdline := cmdline + ' ';
      cmdline := cmdline + Quote(arg);
    end;
  end;
  if (baud < 50) or (baud > 115200) or (blocksize < 16) or (blocksize > 1024) then Usage;
  CrcInit;
  ComOpen;
  if not Wake then
  begin
    WriteLn('No answer from RETRO-PORT on COM', comnum, ' at ', baud, ' baud.');
    WriteLn('It must show one of its own screens (a menu, the screen');
    WriteLn('saver or the power-on question), not a telnet session.');
    Halt(2);
  end;
  if hexmode then
    if not Command('MODE HEX', false, st, 182) then hexmode := false;
  if cmdline <> '' then
    ok := Run(cmdline)
  else
  begin
    WriteLn('RETRO-PORT is listening. Commands: DIR GET PUT FETCH DEL');
    WriteLn('MD REN CD TIME SETTIME STATUS FREE HELP, QUIT to leave.');
    ok := true;
    repeat
      Write('RPX> ');
      ReadLn(ln);
      if EOF then ln := 'QUIT';
      if (Upper(ln) <> 'QUIT') and (Upper(ln) <> 'BYE') and (ln <> '') then ok := Run(ln);
    until (Upper(ln) = 'QUIT') or (Upper(ln) = 'BYE');
  end;
  if Command('BYE', false, st, 91) then ;
  ComClose;
  if not ok then Halt(1);
end.
