DEFINT A-Z
'
'Take our data, encrypt it and turn it into the LUNATIX1.DAT module.
'
DECLARE FUNCTION AntiEscape$ (c$)
DECLARE FUNCTION Decode$ (b$)
DECLARE FUNCTION Encode$ (a$)
CONST MAXDATA = 42 '*what's the max # of the data file we're dealing with.
CONST SEEKSIZE = 8 '*What's the space to allow for offsets - 8-digit number.

DIM SHARED AnError
DIM SHARED Offsets!(0 TO MAXDATA)

CLS

OPEN "LUNATIX1.DAT" FOR OUTPUT SHARED AS #2
'*** Create an empty header record!
PRINT #2, STRING$((MAXDATA + 1) * SEEKSIZE, " ")

FOR x = 0 TO MAXDATA
    AnError = 0
    ON ERROR GOTO NOPEN
    OPEN "DATA\ROOM" + LTRIM$(STR$(x)) + ".DAT" FOR INPUT SHARED AS #1
    ON ERROR GOTO 0
    IF AnError > 0 THEN GOTO LOOPER

    Offsets!(x) = SEEK(2) 'Record the STARTING POINT of this data
    WHILE NOT EOF(1)
        LINE INPUT #1, a$
        IF x <> 41 THEN
            IF LEN(LTRIM$(RTRIM$(a$))) > 0 THEN
                b$ = Encode$(AntiEscape$(LTRIM$(a$)))
                PRINT #2, b$
            END IF
        ELSE
            IF LEN(LTRIM$(RTRIM$(a$))) = 0 THEN a$ = "   "
            b$ = Encode$(a$)
            PRINT #2, b$
        END IF
    WEND
LOOPER:
CLOSE #1
NEXT x

'**** Okay now that we've compiled all the data, we should place offsets
'in the header so it's quicker to find later.

a$ = ""
FOR x = 0 TO MAXDATA
    b$ = LTRIM$(STR$(Offsets!(x)))
    IF LEN(b$) < SEEKSIZE THEN
        b$ = b$ + STRING$(8 - LEN(b$), " ")
    END IF
    a$ = a$ + b$
NEXT x

SEEK #2, 1
PRINT #2, a$;

CLOSE #2

END

NOPEN: AnError = 1: RESUME NEXT

FUNCTION AntiEscape$ (c$)

n = INSTR(c$, CHR$(27))
WHILE n > 0
    MID$(c$, n, 1) = CHR$(210)
    n = INSTR(c$, CHR$(27))
WEND
AntiEscape$ = c$

END FUNCTION

FUNCTION Decode$ (b$)

keyval = 193: RotVal = 3: ss$ = ""
FOR x = 1 TO LEN(b$)
    l = ASC(MID$(b$, x, 1))
    IF x > 1 THEN
        l = l - 33
        IF (l - keyval) < 0 THEN l = l + 223
        l = l - keyval
        l = l + 32
    END IF
    ss$ = ss$ + CHR$(l)
    keyval = keyval + RotVal: IF keyval > 242 THEN keyval = RotVal + 14
NEXT x
Decode$ = ss$

END FUNCTION

FUNCTION Encode$ (a$)

keyval = 193: RotVal = 3: ss$ = ""

j$ = a$

FOR x = 1 TO LEN(a$)
    l = ASC(MID$(a$, x, 1))
    IF x > 1 THEN
        l = l - 32
        l = l + keyval
        IF l > 222 THEN l = l - 223
        l = l + 33
    END IF
    ss$ = ss$ + CHR$(l)
    keyval = keyval + RotVal: IF keyval > 242 THEN keyval = RotVal + 14
NEXT x

'IF Decode$(b$) <> j$ THEN
'    PRINT "FOUND UNMATCH"
'END IF

Encode$ = ss$: EXIT FUNCTION

END FUNCTION

