' CSV parser: field parsing with quote handling, write, row operations
#COMPILE EXE
#DIM ALL

SUB ParseCSVLine(BYVAL line AS STRING, f1 AS STRING, f2 AS STRING, f3 AS STRING, f4 AS STRING, fc AS LONG)
    LOCAL i  AS LONG
    LOCAL idx  AS LONG
    LOCAL inQuote  AS LONG
    LOCAL c  AS STRING
    LOCAL f  AS STRING
    f1 = ""
    f2 = ""
    f3 = ""
    f4 = ""
    idx = 0
    inQuote = 0
    f = ""
    FOR i = 1 TO LEN(line)
        c = MID$(line, i, 1)
        IF c = CHR$(34) THEN
            inQuote = 1 - inQuote
        ELSEIF c = "," AND inQuote = 0 THEN
            idx = idx + 1
            IF idx = 1 THEN f1 = f
            IF idx = 2 THEN f2 = f
            IF idx = 3 THEN f3 = f
            IF idx = 4 THEN f4 = f
            f = ""
        ELSE
            f = f + c
        END IF
    NEXT i
    idx = idx + 1
    IF idx = 1 THEN f1 = f
    IF idx = 2 THEN f2 = f
    IF idx = 3 THEN f3 = f
    IF idx = 4 THEN f4 = f
    fc = idx
END SUB

FUNCTION MakeCSVLine(a AS STRING, b AS STRING, c AS STRING, d AS STRING) AS STRING
    LOCAL result AS STRING
    IF INSTR(a, ",") > 0 THEN a = CHR$(34) + a + CHR$(34)
    IF INSTR(b, ",") > 0 THEN b = CHR$(34) + b + CHR$(34)
    IF INSTR(c, ",") > 0 THEN c = CHR$(34) + c + CHR$(34)
    IF INSTR(d, ",") > 0 THEN d = CHR$(34) + d + CHR$(34)
    FUNCTION = a + "," + b + "," + c + "," + d
END FUNCTION

FUNCTION PBMAIN() AS LONG
    LOCAL f1  AS STRING
    LOCAL f2  AS STRING
    LOCAL f3  AS STRING
    LOCAL f4  AS STRING
    LOCAL fc AS LONG
    PRINT "=== CSV Reader/Writer ==="
    PRINT
    CALL ParseCSVLine("Name,Age,City,Zip", f1, f2, f3, f4, fc)
    PRINT "Header (" + FORMAT$(fc) + " fields):"
    PRINT "  " + f1 + " | " + f2 + " | " + f3 + " | " + f4
    PRINT
    CALL ParseCSVLine("Alice,32,Portland,97201", f1, f2, f3, f4, fc)
    PRINT "Data row:"
    PRINT "  Name: " + f1
    PRINT "  Age: " + f2
    PRINT "  City: " + f3
    PRINT "  Zip: " + f4
    PRINT
    CALL ParseCSVLine(CHR$(34) + "Smith, John" + CHR$(34) + ",45," + CHR$(34) + "San Francisco, CA" + CHR$(34) + ",94102", f1, f2, f3, f4, fc)
    PRINT "Quoted CSV (" + FORMAT$(fc) + " fields):"
    PRINT "  [1]: " + f1
    PRINT "  [2]: " + f2
    PRINT "  [3]: " + f3
    PRINT "  [4]: " + f4
    PRINT
    PRINT "Make CSV: " + MakeCSVLine("Widget", "100", "$19.99", "In Stock")
    PRINT "Make CSV (quoted): " + MakeCSVLine("Smith, John", "500", "Active", "N/A")
    PRINT
    PRINT "CSV reader tests complete."
    FUNCTION = 0
END FUNCTION
