;; This example shows how to write a file byte-by-byte.
;;
;; This code can be used to write a headerless file,
;; or to write a file with your own header.

.cas_out_open equ &bc8c
.cas_out_close equ &bc8f
.cas_out_char equ &bc95

ld hl,&4000				;; start address of data to write (example)
ld bc,&4000				;; length of data to write (example)
push hl
push bc

;; open output file
ld b,end_filename-filename
ld hl,filename
ld de,two_k_buffer
call cas_out_open

;; at this point the file will be opened for output.
;; A header is *not* created or written to the output
;; file

pop bc
pop hl

;; HL = start address of data to write
;; BC = length of data to write

.next_byte
ld a,(hl)		;; read byte from memory
inc hl		;; increment point

;; write byte to output file
push bc
push hl
call cas_out_char
pop hl
pop bc

;; decrement count (BC = number of bytes remaining to write to
;; output file)
dec bc

;; BC = 0 -> finished writing
;; BC <> 0 -> not finished. write more bytes
ld a,b
or c
jr nz,next_byte

;; close the output file
call cas_out_close
ret

;;----------------------------------------------------------------
;; this is the filename of the output file

.filename
defb "datafile.bin"
.end_filename

;;----------------------------------------------------------------
;; this buffer is filled with data which will be written to the output
;; file

.two_k_buffer defs 2048
