' File header: BMP-like header TYPE with field access, validation
#COMPILE EXE
#DIM ALL

TYPE BMPHeader
    signature AS STRING
    fileSize AS LONG
    reserved1 AS INTEGER
    reserved2 AS INTEGER
    dataOffset AS LONG
    headerSize AS LONG
    width AS LONG
    height AS LONG
    planes AS INTEGER
    bitCount AS INTEGER
    compression AS LONG
    imageSize AS LONG
END TYPE

FUNCTION IsValidBMP(BYREF h AS BMPHeader) AS LONG
    IF h.signature <> "BM" THEN
        FUNCTION = 0
        EXIT FUNCTION
    END IF
    IF h.headerSize < 40 THEN
        FUNCTION = 0
        EXIT FUNCTION
    END IF
    IF h.width <= 0 OR h.width > 65536 THEN
        FUNCTION = 0
        EXIT FUNCTION
    END IF
    IF h.bitCount <> 1 AND h.bitCount <> 4 AND h.bitCount <> 8 AND h.bitCount <> 24 AND h.bitCount <> 32 THEN
        FUNCTION = 0
        EXIT FUNCTION
    END IF
    FUNCTION = 1
END FUNCTION

SUB InitBMP(BYREF h AS BMPHeader, BYVAL w AS LONG, BYVAL hgt AS LONG, BYVAL bpp AS INTEGER)
    h.signature = "BM"
    h.headerSize = 40
    h.width = w
    h.height = hgt
    h.planes = 1
    h.bitCount = bpp
    h.compression = 0
    h.imageSize = ((w * bpp + 31) / 32) * 4 * hgt
    h.dataOffset = 54
    h.fileSize = h.dataOffset + h.imageSize
END SUB

FUNCTION CalcStride(BYVAL w AS LONG, BYVAL bpp AS INTEGER) AS LONG
    FUNCTION = ((w * bpp + 31) / 32) * 4
END FUNCTION

FUNCTION PBMAIN() AS LONG
    LOCAL bmp AS BMPHeader
    PRINT "=== File Header Structures ==="
    PRINT
    CALL InitBMP(bmp, 640, 480, 24)
    PRINT "BMP 640x480x24:"
    PRINT "  Signature: " & bmp.signature
    PRINT "  Width: " & FORMAT$(bmp.width)
    PRINT "  Height: " & FORMAT$(bmp.height)
    PRINT "  BitCount: " & FORMAT$(bmp.bitCount)
    PRINT "  FileSize: " & FORMAT$(bmp.fileSize)
    PRINT "  ImageSize: " & FORMAT$(bmp.imageSize)
    PRINT "  Stride: " & FORMAT$(CalcStride(640, 24)) & " bytes/row"
    IF IsValidBMP(bmp) THEN PRINT "  Valid: Yes" ELSE PRINT "  Valid: No"
    PRINT
    CALL InitBMP(bmp, 1920, 1080, 32)
    PRINT "BMP 1920x1080x32:"
    PRINT "  FileSize: " & FORMAT$(bmp.fileSize) & " bytes"
    PRINT "  Stride: " & FORMAT$(CalcStride(1920, 32)) & " bytes/row"
    IF IsValidBMP(bmp) THEN PRINT "  Valid: Yes" ELSE PRINT "  Valid: No"
    PRINT
    bmp.signature = "XX"
    PRINT "Invalid BMP: "
    IF IsValidBMP(bmp) THEN PRINT "Valid=Yes" ELSE PRINT "Valid=No"
    PRINT
    PRINT "File header tests complete."
    FUNCTION = 0
END FUNCTION
