; a program to make a file from the contents of memory
;
;      to be used with cptomem
;
cpm	equ	0
prtmsg	equ	9
open	equ	15
close	equ	16
write	equ	21
create	equ	22
setdma	equ	26
sys	equ	0005h
fcb	equ	005ch
buffer	equ	0800h
;
	org	100h
;
; set up stack and open file
;
start	lxi	sp,stack
	lxi	d,fcb
	mvi	c,open
	call	sys
	cpi	4
	jnc	make
	lxi	d,exists         ; file already exists
	mvi	c,prtmsg
	call	sys
	jmp	cpm
;
; create the new file
;
make	lxi	d,fcb
	mvi	c,create
	call	sys
	cpi	4
	jc	writef
	lxi	d,cannot         ; disk is full
	mvi	c,prtmsg
	call	sys
	jmp	cpm
;
; get initial buffer address in h and record count in b
;
writef	lxi	h,buffer
	mvi	b,0
	push	b                ; save record count and
	push	h                ; and buffer address on stack
;
loop	pop	d                ; get address in buffer
	push	d
	mvi	c,setdma         ; and set DMA
	call	sys
	lxi	d,fcb
	mvi	c,write          ; write record
	call	sys
	cpi	0
	jz	incrmt           ; increment if write is OK 
;
; disk is full
;
	lxi	d,eom
	mvi	c,prtmsg
	call	sys
	lxi	d,fcb
	mvi	c,close
	call	sys
	jmp	cpm
;
; increment address in buffer and record number
;
incrmt	pop	h
	lxi	b,128
	dad	b
	pop	b
	mov	a,b
	cpi	255
	jnz	step
	lda	buffer-4
	dcr	a
	sta	buffer-4
	mvi	b,0
	jmp	next
step	inr	b
next	push	b                ; stack record count
	push	h                ; and address
	lda	buffer-4         ; check if last record 
	cpi	0                ;   is read
	jnz	loop
	lda	buffer-3
	cmp	b
	jnz	loop
;
; last record has been read
;
	lxi	d,endp
	mvi	c,prtmsg
	call	sys
	lxi	d,fcb
	mvi	c,close
	call	sys
	jmp	cpm
;
cannot	db	'cannot create file$'
exists	db	'file already exists$'
eom	db	'disk out of free space$'
endp	db	'copy completed$'
	ds	64
stack	nop
;
	end	start
