' Memo2tinyBas.ibas
{CREATORID "LDmt"}
{VERSION "1.0"}
{RESOURCEFILE "Memo2tinyBas.rsrc"}
{PARSER ON}
{SECUREFILES OFF}

DIM A$(126) ' [27-126] = up to 100 (!)
            ' tinyBas source codes can
            ' be read from MemoDB
DIM A(126)  ' tinyBas file number
           
BEGIN
 E$=CHR$(10)
 LABEL #3,"Scanning MemoDB...",40,70
 K=27 : GOSUB _ScanMemoDB
 IF K=27 THEN
  Z$="[Empty]"
 ELSE
  Z$=A$(27) : S=27
 ENDIF
 B=0
 FOR I=26 TO K 
  B$=A$(I) : C=FONTWIDTH(B$,0)
  B=MAX(B,C)
 NEXT
 B=MIN(B,125)+15 : C=(160-B)\2
 POPUPCHOICE #1,Z$,"A$(27)",8,C,30,B,15
 BUTTON #2,"-> tinyBasic",50,50,60,12
 UPDATELABEL #3,"" : UPDATEPOS #3,60,70
 BUTTON #4,"Launch tinyBasic",30,100,100,12
 BUTTON #5,"Launch Memo Pad",30,120,100,12
 REPEAT
  E=DOEVENTS
  IF E=1 IF S>0 LET S=26+SELECTEDCHOICE
  IF E=2 IF S>0 GOSUB _ConvertDB
  IF E=4 RUN "tinyBasic"
  IF E=5 RUN "Memo Pad"
 UNTIL E=-1
END

_ConvertDB:
 UPDATELABEL #3,"Working..."
 HIDE #4 : HIDE #5
 GOSUB _ScanMemoDB
 D$="tinyBas"+STR$(D,0)
 B=FILEEXISTS(D$)
 IF B=TRUE THEN
  B=MESSAGEBOX("File "+D$+" already exists. Overwrite?",3)
  B=B=2
 ENDIF
 IF B=FALSE THEN
  F=0 : L=1
  OPEN "M2tBas" FOR OUTPUT AS #1
  REPEAT
   GOSUB _ReadOneString
   B$=TRIM$(B$)     
   IF B$<>"" THEN
    B=VAL(B$)
    IF B=0 THEN 
     C=4
    ELSE
     IF F>=B THEN
      C=5
     ELSE
      F=B : PRINT #1,B$ : INC L
     ENDIF
    ENDIF
   ENDIF
  UNTIL C<>1
  CLOSE #1
  KILL D$
  COPY "M2tBas",D$,"LDtB"
  KILL "M2tBas"
  SELECT CASE C
  CASE 2
   B=MESSAGEBOX("File "+D$+" created",1)
  CASE 3 
   A$="["+STR$(L,0)+"] Line too long"+E$
   B=MESSAGEBOX(A$+B$,1)
   KILL D$
  CASE 4
   A$="["+STR$(L,0)+"] Non valid line"+E$  
   B=MESSAGEBOX(A$+B$,1)
   KILL D$
  CASE 5
   A$="["+STR$(L,0)+"] Non valid line number"+E$  
   B=MESSAGEBOX(A$+E$+B$,1)
   KILL D$
  END SELECT
 ENDIF
 UPDATELABEL #3,""
 SHOW #4 : SHOW #5
RETURN

_ScanMemoDB:
 OPEN "MemoDB" FOR INPUT AS #1
 L=LOF(#1) : I=1
 WHILE I<=L
  INPUT$$ #1 : M=LEN$$
  N=1 : GOSUB _ReadOneString
  C$=LEFT$(B$,7) : C$=LCASE$(C$)
  IF C$="tinybas" THEN
   C$=MID$(B$,8,56) : C=VAL(C$)
   IF S=0 THEN
    IF K<=126 THEN
     A$(K)=B$ : A(K)=C : INC K
    ENDIF
   ELSE
    D=A(S) : IF D=C LET I=L
   ENDIF
  ENDIF
  INC I
 WEND
 CLOSE #1
RETURN

_ReadOneString:
 B$="" : C=0
 REPEAT
  IF N>M THEN
   C=2
  ELSE
   B=LEN(B$)
   IF B>62 THEN
    C=3
   ELSE
    C$=GETCHAR$$(N)
    IF C$=E$ THEN
     C=1
    ELSE
     B$=B$+C$ 
    ENDIF
   ENDIF
  ENDIF
  INC N 
 UNTIL C<>0
RETURN
