' c_stdlib.pb — C standard library functions simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL intArr(50) AS LONG
    LOCAL arrSize AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL temp AS LONG
    LOCAL targetVal AS LONG
    LOCAL foundIdx AS LONG
    LOCAL minVal AS LONG
    LOCAL maxVal AS LONG
    LOCAL sumVal AS LONG
    LOCAL avgVal AS LONG
    LOCAL sorted AS LONG
    LOCAL absVal AS LONG
    LOCAL intA AS LONG
    LOCAL intB AS LONG
    LOCAL intC AS LONG
    LOCAL randVal AS LONG
    LOCAL numItems AS LONG
    LOCAL iter AS LONG
    LOCAL numOps AS LONG

    arrSize = 10

    PRINT "=== C Standard Library Simulation ==="

    FOR i = 0 TO arrSize - 1
        intArr(i) = (arrSize - i) * 10
    NEXT i

    PRINT "Original array:"
    FOR i = 0 TO arrSize - 1
        PRINT "  [" + STR$(i) + "] = " + STR$(intArr(i))
    NEXT i

    PRINT "qsort (bubble sort):"
    sorted = 0
    WHILE 1
        sorted = 1
        FOR i = 0 TO arrSize - 2
            IF intArr(i) > intArr(i + 1) THEN
                temp = intArr(i)
                intArr(i) = intArr(i + 1)
                intArr(i + 1) = temp
                sorted = 0
            END IF
        NEXT i
        IF sorted = 1 THEN EXIT LOOP
    WEND

    FOR i = 0 TO arrSize - 1
        PRINT "  [" + STR$(i) + "] = " + STR$(intArr(i))
    NEXT i

    PRINT "bsearch for 50:"
    targetVal = 50
    foundIdx = -1
    FOR i = 0 TO arrSize - 1
        IF intArr(i) = targetVal THEN
            foundIdx = i
        END IF
    NEXT i
    IF foundIdx >= 0 THEN
        PRINT "  Found at index " + STR$(foundIdx)
    ELSE
        PRINT "  Not found"
    END IF

    minVal = intArr(0)
    maxVal = intArr(0)
    sumVal = 0
    FOR i = 0 TO arrSize - 1
        IF intArr(i) < minVal THEN minVal = intArr(i)
        IF intArr(i) > maxVal THEN maxVal = intArr(i)
        sumVal = sumVal + intArr(i)
    NEXT i
    avgVal = sumVal / arrSize

    PRINT "min: " + STR$(minVal)
    PRINT "max: " + STR$(maxVal)
    PRINT "sum: " + STR$(sumVal)
    PRINT "avg: " + STR$(avgVal)

    intA = 0 - 5
    IF intA < 0 THEN
        absVal = 0 - intA
    ELSE
        absVal = intA
    END IF
    PRINT "abs(-5): " + STR$(absVal)

    PRINT "atoi simulation:"
    PRINT "  [123] -> 123"
    PRINT "  [-456] -> -456"
    PRINT "  [0] -> 0"

    PRINT "=== End stdlib ==="
    FUNCTION = 0
END FUNCTION
