' Centralized Error Handler with error codes
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL i AS LONG, j AS LONG, k AS LONG
    LOCAL result AS LONG, good AS LONG
    LOCAL vals(9) AS LONG
    LOCAL s AS STRING, c AS STRING
    LOCAL sum AS LONG

    PRINT "Error Handler Demo"
    PRINT "================="
    PRINT ""

    PRINT "1. Successful division:"
    i = 100: j = 5
    IF j <> 0 THEN
        result = i / j
        PRINT "  "; i; " / "; j; " = "; result
        good = 1
    ELSE
        PRINT "  ERROR: Division by zero"
        good = 0
    END IF
    IF good THEN PRINT "  (success)"

    PRINT ""
    PRINT "2. Division by zero:"
    i = 100: j = 0
    IF j <> 0 THEN
        result = i / j
        PRINT "  "; i; " / "; j; " = "; result
    ELSE
        PRINT "  ERROR #1: Division by zero"
    END IF

    PRINT ""
    PRINT "3. String to int:"
    s = "12345"
    result = 0: good = 1
    FOR i = 1 TO LEN(s)
        c = MID$(s, i, 1)
        IF c < "0" OR c > "9" THEN
            PRINT "  ERROR #2: Invalid digit '"; c; "'"
            good = 0
        END IF
        IF good THEN result = result * 10 + (ASC(c) - 48)
    NEXT i
    IF good THEN PRINT "  Parsed: "; result

    PRINT ""
    PRINT "4. Invalid string:"
    s = "12x45"
    result = 0: good = 1
    FOR i = 1 TO LEN(s)
        c = MID$(s, i, 1)
        IF c < "0" OR c > "9" THEN
            PRINT "  ERROR #3: Invalid character at position "; i
            good = 0
            i = LEN(s) + 1
        END IF
        IF good THEN result = result * 10 + (ASC(c) - 48)
    NEXT i
    IF good THEN PRINT "  Parsed: "; result

    PRINT ""
    PRINT "5. Array sum:"
    FOR i = 0 TO 9
        vals(i) = i * 10
    NEXT i
    sum = 0
    FOR i = 0 TO 9
        sum = sum + vals(i)
    NEXT i
    PRINT "  Sum = "; sum
    PRINT "  Average = "; sum / 10

    PRINT ""
    PRINT "6. IndexOf (found):"
    j = -1
    FOR i = 0 TO 9
        IF vals(i) = 50 THEN j = i
    NEXT i
    IF j >= 0 THEN
        PRINT "  50 found at index "; j
    ELSE
        PRINT "  50 not found"
    END IF

    PRINT ""
    PRINT "7. IndexOf (not found):"
    j = -1
    FOR i = 0 TO 9
        IF vals(i) = 999 THEN j = i
    NEXT i
    IF j >= 0 THEN
        PRINT "  999 found at index "; j
    ELSE
        PRINT "  ERROR #4: Value 999 not found"
    END IF

    PRINT ""
    PRINT "All error handling tests completed."

    FUNCTION = 0
END FUNCTION
