' data_filter.pb — Signal/image filtering algorithms
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL signal(200) AS LONG
    LOCAL filtered(200) AS LONG
    LOCAL kernel(20) AS LONG
    LOCAL signalLen AS LONG
    LOCAL kernelLen AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL k AS LONG
    LOCAL sumVal AS LONG
    LOCAL meanVal AS LONG
    LOCAL medianVal AS LONG
    LOCAL minVal AS LONG
    LOCAL maxVal AS LONG
    LOCAL smoothVal AS LONG
    LOCAL edgeVal AS LONG
    LOCAL threshold AS LONG
    LOCAL peakCount AS LONG
    LOCAL window(20) AS LONG
    LOCAL sortedWindow(20) AS LONG
    LOCAL temp AS LONG
    LOCAL sortDone AS LONG
    LOCAL iter AS LONG
    LOCAL idx AS LONG

    signalLen = 30
    kernelLen = 3

    PRINT "=== Signal Filtering ==="

    FOR i = 0 TO signalLen - 1
        signal(i) = 50 + i * 3 + i MOD 7 * 10
    NEXT i

    PRINT "Original signal (" + STR$(signalLen) + " samples):"
    FOR i = 0 TO signalLen - 1
        PRINT "  [" + STR$(i) + "] = " + STR$(signal(i))
    NEXT i

    kernel(0) = 1
    kernel(1) = 2
    kernel(2) = 1

    PRINT "Applying moving average (kernel size=" + STR$(kernelLen) + "):"
    FOR i = 0 TO signalLen - 1
        sumVal = 0
        FOR j = 0 TO kernelLen - 1
            idx = i + j - kernelLen / 2
            IF idx >= 0 AND idx < signalLen THEN
                sumVal = sumVal + signal(idx) * kernel(j)
            END IF
        NEXT j
        filtered(i) = sumVal / 4
    NEXT i

    FOR i = 0 TO signalLen - 1
        IF i < 10 THEN
            PRINT "  [" + STR$(i) + "] " + STR$(signal(i)) + " -> " + STR$(filtered(i))
        END IF
    NEXT i

    PRINT "Threshold detection (threshold=100):"
    threshold = 100
    peakCount = 0
    FOR i = 1 TO signalLen - 2
        IF signal(i) > threshold THEN
            IF signal(i) > signal(i - 1) AND signal(i) > signal(i + 1) THEN
                peakCount = peakCount + 1
                PRINT "  Peak at [" + STR$(i) + "] = " + STR$(signal(i))
            END IF
        END IF
    NEXT i
    PRINT "Peaks found: " + STR$(peakCount)

    PRINT "Median filter (window=3):"
    FOR i = 0 TO signalLen - 1
        j = 0
        FOR k = i - 1 TO i + 1
            IF k >= 0 AND k < signalLen THEN
                window(j) = signal(k)
                sortedWindow(j) = signal(k)
                j = j + 1
            END IF
        NEXT k

        sortDone = 0
        WHILE 1
            sortDone = 1
            FOR k = 0 TO j - 2
                IF sortedWindow(k) > sortedWindow(k + 1) THEN
                    temp = sortedWindow(k)
                    sortedWindow(k) = sortedWindow(k + 1)
                    sortedWindow(k + 1) = temp
                    sortDone = 0
                END IF
            NEXT k
            IF sortDone = 1 THEN EXIT LOOP
        WEND

        medianVal = sortedWindow(j / 2)
        filtered(i) = medianVal
    NEXT i

    PRINT "=== End Filter ==="
    FUNCTION = 0
END FUNCTION
