unit uImport;

{
This code is part of the TiCodEd Application, designed to develop for the
TI-99/4a Homecomputer in a modern, structured way.

BSD License
Copyright (c) 2026, Stefan Bauch, TiCodEd <at> lizardware <dot> de


Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

}

{$mode ObjFPC}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ValEdit,
  Buttons, Grids;

type

  { TFormImport }

  TFormImport = class(TForm)
    BitBtnOK: TBitBtn;
    BitBtnCancel: TBitBtn;
    BitBtnApply: TBitBtn;
    GroupBoxImport: TGroupBox;
    xbtext: TMemo;
    OpenDialogImport: TOpenDialog;
    ValueListEditor1: TValueListEditor;
    procedure BitBtnOKClick(Sender: TObject);
    procedure BitBtnApplyClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure ValueListEditor1SelectCell(Sender: TObject; aCol, aRow: Integer;
      var CanSelect: Boolean);
  private

  public

  end;

  TLogProc = Procedure(l:Integer; txt:ShortString);

var
  FormImport: TFormImport;
  xbfile,sxbfile : String;

Procedure RegisterDbg(aDbg:TLogProc);


implementation

{$R *.lfm}

{ TFormImport }

USES uSXB2XB,LCLProc,strutils,LazUTF8;

VAR Dbg : TLogProc;

Procedure RegisterDbg(aDbg:TLogProc);
begin
  Dbg := aDbg;
end;

function FindInMemo(AMemo: TMemo; AString: String; StartPos: Integer): Integer;
begin
  Result := PosEx(AString, AMemo.Text, StartPos);
  if Result > 0 then
  begin
    AMemo.SelStart := UTF8Length(PChar(AMemo.Text), Result - 1);
    AMemo.SelLength := Length(AString);
    AMemo.SetFocus;
  end;
end;

function FormatLabel(s:string):String;
var v,r : Integer;
begin
  val(trim(s),v,r);
  if r=0 then begin
                Result := 'LABEL' + format('%.5d',[v]) ;
                if not FormImport.ValueListEditor1.FindRow(Result,r) then FormImport.ValueListEditor1.InsertRow(Result,'',true);
              end else begin
                Result := s;
                dbg(3,'Info : Label Error '+s);
              end;
end;

Function SubstLabel(l:String):String;
var b : Integer;
    s : string;                   // 100,200,300   -> LABEL100, LABEL200, LABEL300
begin
  b := PosUnquoted(',',l);
  s := '';
  if b=0 then s := FormatLabel(l)
  else begin
    while b>0 do begin
      s := s + FormatLabel(copy(l,1,b-1)) + ', ';
      l := trim(copy(l,b+1,255));
      b := PosUnquoted(',',l);
    end;
    s := s + FormatLabel(l);
  end;
  Result := s;
end;

function ReplaceLineNumbers(s,stmt:String):String;
var t : String;
    i,j :  Integer;
begin
  i:=PosUnquoted(stmt,s);
  t:='';
  while i>0 do begin
     if t='' then t := copy(s,1,i+length(stmt))
             else t := t + ' ' + copy(s,1,i+length(stmt));
     s := copy(s,i+length(stmt)+1,255);
     j:=0;
     while (j<length(s)) and (s[j+1] IN ['0'..'9',' ',',']) do inc(j);
     if (j<length(s)) and (s[j+1] IN ['0'..'9',' ',',']) then dec(j);
     if j>0 then begin
       t:=t+SubstLabel(copy(s,1,j));
       s := copy(s,j+1,255);
     end;
     i:=PosUnquoted(stmt,s);
  end;
  Result := trim(t)+' '+trim(s);
end;

procedure TFormImport.FormShow(Sender: TObject);
VAR xb :  TextFile;
    i,v,r :  Integer;
    s,t :  String;
begin
  if OpenDialogImport.Execute then begin
    xbfile := OpenDialogImport.FileName;
    // if true then begin  // uncomment for direct testing
    // xbfile := 'S:\classic99\Delphi\TICodEd\test.org';
    AssignFile(xb,xbfile);
    reset(xb);
    xbtext.Clear;
    ValueListEditor1.Clear;
    while not eof(xb) do begin
      readln(xb,s);
      dbg(4,'Import: '+s);

      s := ReplaceLineNumbers(s, 'THEN');
      s := ReplaceLineNumbers(s, 'ELSE');
      s := ReplaceLineNumbers(s, 'GOTO');
      s := ReplaceLineNumbers(s, 'GO TO');
      s := ReplaceLineNumbers(s, 'RESTORE');
      s := ReplaceLineNumbers(s, 'GOSUB');
      s := ReplaceLineNumbers(s, 'GO SUB');
      s := ReplaceLineNumbers(s, 'USING');
      s := ReplaceLineNumbers(s, 'ON ERROR');
      s := ReplaceLineNumbers(s, 'RETURN');

      dbg(4,'    --> '+s);
      xbtext.Append(s);
    end;
    CloseFile(xb);
    ValueListEditor1.Sort(ColKey);
    i:=0;
    while i<xbtext.Lines.Count do begin
      t := xbtext.Lines.Strings[i];
      val(t,v,r);
      val(copy(t,1,r-1),v,r);
      t := 'LABEL' + format('%.5d',[v]);
      if ValueListEditor1.FindRow(t,r) then begin
         xbtext.Lines.Insert(i,t+':');
         xbtext.Lines.Insert(i,'');
         inc(i,2);
      end;
      inc(i);
    end;

  end else FormImport.Close;
end;

procedure TFormImport.BitBtnApplyClick(Sender: TObject);
VAR i : Integer;
begin
  for i:=1 to ValueListEditor1.Strings.Count do begin
    if ValueListEditor1.Cells[1,i]<>'' then begin
      xbtext.Text:=WideStringReplace(PChar(xbtext.Text),trim(ValueListEditor1.Cells[0,i]),trim(ValueListEditor1.Cells[1,i]),[rfReplaceAll,rfIgnoreCase]);
      Dbg(3,'Label : '+ValueListEditor1.Cells[0,i]+' -> '+ ValueListEditor1.Cells[1,i]);
      ValueListEditor1.Cells[0,i] := ValueListEditor1.Cells[1,i];
      ValueListEditor1.Cells[1,i] := '';
    end;
  end;
end;

procedure TFormImport.BitBtnOKClick(Sender: TObject);
begin
  BitBtnApplyClick(Sender);
  Hide;
end;

procedure TFormImport.ValueListEditor1SelectCell(Sender: TObject; aCol,
  aRow: Integer; var CanSelect: Boolean);
begin
  FindInMemo(xbtext,ValueListEditor1.Keys[aRow]+':',1);
end;

end.

