'
' This program shows how to implement binary downloads over HTTP.
'
' Needs BaCon 1.0 build 18 or higher - September 2010, PvE - GPL.
'----------------------------------------------------------------------------------------

OPTION MEMSTREAM TRUE

' Define HTTP separator
CONST Separator$ = CONCAT$(CHR$(13), CHR$(10), CHR$(13), CHR$(10))

' This is the size of the memory buffer
CONST ChunkSize = 1024

' Website we're downloading from
website$ = "www.basic-converter.org"
port$ = "80"

' The actual file to download
file$ = "documentation.pdf"

' Reserve memory
area = MEMORY(ChunkSize)

' The area should be readable as memory stream because
'   we need to strip off HTTP headers
OPEN area FOR MEMORY AS data$

' The file where the binary data will be written to
OPEN file$ FOR WRITING AS download

' Open network connection
OPEN CONCAT$(website$, ":", port$) FOR NETWORK AS mynet

' Send a HTTP GET
SEND CONCAT$("GET /", file$, " HTTP/1.1\r\nHost: ", website$, Separator$) TO mynet

stripped = FALSE

' Get the binary content
REPEAT
    ' Print progress on sreen
    PRINT ".";

    ' Receive binary data into memory buffer
    RECEIVE area FROM mynet CHUNK ChunkSize SIZE amount

    ' Strip off HTTP header
    IF NOT(stripped) THEN
        x = INSTR(data$, Separator$)-1
        IF x THEN
            PUTBYTE area + x + LEN(Separator$) TO download SIZE amount-x-LEN(Separator$)
            stripped = TRUE
        END IF
    ' If stripped add binary data to file
    ELSE
        PUTBYTE area TO download SIZE amount
    END IF

UNTIL ISFALSE(WAIT(mynet, 1000))

' Close all open handles
CLOSE NETWORK mynet
CLOSE FILE download
CLOSE MEMORY data$

' Finished!
PRINT "Downloading '", file$, "' done!"