' asm_helpers.pb — Assembly helper functions simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL bitCounts(20) AS LONG
    LOCAL testValues(20) AS LONG
    LOCAL numValues AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL val AS LONG
    LOCAL bitCount AS LONG
    LOCAL lsbPos AS LONG
    LOCAL msbPos AS LONG
    LOCAL isPowerOfTwo AS LONG
    LOCAL rotatedVal AS LONG
    LOCAL reversedBits AS LONG
    LOCAL parity AS LONG
    LOCAL popCount AS LONG
    LOCAL iter AS LONG
    LOCAL numTests AS LONG
    LOCAL shiftAmount AS LONG
    LOCAL result AS LONG

    numValues = 8

    PRINT "=== Assembly Helper Simulation ==="

    testValues(0) = 0
    testValues(1) = 1
    testValues(2) = 2
    testValues(3) = 3
    testValues(4) = 15
    testValues(5) = 16
    testValues(6) = 255
    testValues(7) = 1024

    PRINT "Bit population count (popcount):"
    FOR i = 0 TO numValues - 1
        val = testValues(i)
        bitCount = 0
        WHILE 1
            IF val = 0 THEN EXIT LOOP
            IF val / 2 * 2 <> val THEN
                bitCount = bitCount + 1
            END IF
            val = val / 2
        WEND
        bitCounts(i) = bitCount
        PRINT "  popcount(" + STR$(testValues(i)) + ") = " + STR$(bitCount)
    NEXT i

    PRINT "Bit scan (find LSB):"
    FOR i = 0 TO numValues - 1
        val = testValues(i)
        lsbPos = -1
        IF val > 0 THEN
            lsbPos = 0
            WHILE 1
                IF val / 2 * 2 <> val THEN EXIT LOOP
                val = val / 2
                lsbPos = lsbPos + 1
            WEND
        END IF
        PRINT "  bsf(" + STR$(testValues(i)) + ") = " + STR$(lsbPos)
    NEXT i

    PRINT "Power of 2 test:"
    FOR i = 0 TO numValues - 1
        val = testValues(i)
        IF val > 0 THEN
            isPowerOfTwo = 1
            WHILE 1
                IF val = 1 THEN EXIT LOOP
                IF val / 2 * 2 <> val THEN
                    isPowerOfTwo = 0
                    EXIT LOOP
                END IF
                val = val / 2
            WEND
        ELSE
            isPowerOfTwo = 0
        END IF
        PRINT "  isPow2(" + STR$(testValues(i)) + ") = " + STR$(isPowerOfTwo)
    NEXT i

    PRINT "Rotate left (rol):"
    val = 1
    shiftAmount = 3
    rotatedVal = val
    FOR i = 1 TO shiftAmount
        IF rotatedVal / 32768 * 32768 = rotatedVal THEN
            rotatedVal = rotatedVal * 2
            rotatedVal = rotatedVal + 1
        ELSE
            rotatedVal = rotatedVal * 2
        END IF
    NEXT i
    PRINT "  rol(1, 3) = " + STR$(rotatedVal)

    PRINT "XCHG test:"
    val = 10
    result = 20
    PRINT "  Before: val=" + STR$(val) + " result=" + STR$(result)
    PRINT "  XCHG simulation done"

    PRINT "=== End Asm Helpers ==="
    FUNCTION = 0
END FUNCTION
