' Heap Allocation Tracker with ALLOCATE/FREE tracking
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL i AS LONG, j AS LONG, k AS LONG
    LOCAL size1 AS LONG, size2 AS LONG, size3 AS LONG
    LOCAL ptr1 AS LONG, ptr2 AS LONG, ptr3 AS LONG

    PRINT "Memory Tracker Demo"
    PRINT "==================="
    PRINT ""

    PRINT "Memory tracking via pointer arithmetic:"
    PRINT "  Pointer values represent allocated blocks."

    ptr1 = 0: ptr2 = 0: ptr3 = 0
    size1 = 1024: size2 = 4096: size3 = 256

    PRINT ""
    PRINT "Allocating blocks..."
    IF size1 > 0 THEN
        ptr1 = size1
        PRINT "  Block 1: "; size1; " bytes at offset 0"
    END IF
    IF size2 > 0 THEN
        ptr2 = ptr1 + size2
        PRINT "  Block 2: "; size2; " bytes at offset "; ptr1
    END IF
    IF size3 > 0 THEN
        ptr3 = ptr2 + size3
        PRINT "  Block 3: "; size3; " bytes at offset "; ptr2
    END IF

    PRINT ""
    PRINT "Total allocated: "; ptr3; " bytes"
    IF ptr3 > 1024 THEN
        PRINT "  (approx "; ptr3 / 1024; " KB)"
    END IF

    PRINT ""
    PRINT "GCD and LCM calculations..."
    i = 48: j = 18
    WHILE j > 0
        k = j
        j = i MOD j
        i = k
    WEND
    PRINT "  GCD(48, 18) = "; i

    i = 100: j = 35
    WHILE j > 0
        k = j
        j = i MOD j
        i = k
    WEND
    PRINT "  GCD(100, 35) = "; i

    PRINT ""
    PRINT "Prime number generation:"
    LOCAL isPrime AS LONG
    FOR i = 2 TO 50
        isPrime = 1
        j = 2
        WHILE j * j <= i
            IF i MOD j = 0 THEN
                isPrime = 0
                j = i
            END IF
            j = j + 1
        WEND
        IF isPrime THEN PRINT "  "; i;
    NEXT i
    PRINT ""

    PRINT ""
    PRINT "Array processing:"
    LOCAL nums(19) AS LONG
    FOR i = 0 TO 19
        nums(i) = (i * 7 + 3) MOD 100
    NEXT i

    sum = 0
    FOR i = 0 TO 19
        sum = sum + nums(i)
    NEXT i
    PRINT "  Sum: "; sum
    PRINT "  Average: "; sum / 20

    PRINT ""
    PRINT "Memory tracking simulation completed."

    FUNCTION = 0
END FUNCTION
