	Z80
	PreDef	Math
	MacLib	CPM22

	Entry	0x100

	Include CPM22.ASI

	Globals

	Stack	020h
	Startup

	Print$	<'DLOAD Version 1.1 for CPM 1, CDOS and IMDOS\r\n'>

	BDOSDE	_SetDMA,_DefDMA
	
	call	CheckDLopen

	call	CheckFileName
	
	call	OpenFile

	Print$	<'\r\n   Downloading as Binary...'>

again
	call	ReadRecord
	push	a
	call	WriteRecord
	pop	a
	ora	a
	jz	again
	
	BDOSDE	_Close,_DefFCB

	Print$	<'Finished\r\n'>
ExitPGM
	Exit

OpenFile
	Call	FixUPFCB
	BDOSDE _Open,_DefFCB
	cpi	0xff
	jz	NOTexist

	Print$ <'\r\n File exists, OK to Overwrite? - '>
	call	ConIn
	cpi	'Y'
	jz	DeleteIt
	cpi	'y'
	jnz	ExitPGM

DeleteIt
	Call	FixUPFCB
	BDOSDE _Delete,_DefFCB

NOTexist
	Call	FixUPFCB
	BDOSDE _Make,_DefFCB
	cpi	0xff
	rnz		;success
	
	Print$	<'\r\nFailed to Make file\r\n'>
	jmp	ExitPGM
		
WrRecCnt	dw	0

WriteRecord
	lhld	WrRecCnt
	inx	hl
	shld	WrRecCnt
	BDOSDE _WriteSEQ,_DefFCB
	ora	a
	rz
	Print$	<'\r\nError Writing file\r\n'>
	BDOSDE _Close,_DefFCB
	jmp	ExitPGM
	

; Return a is Done=1 or more=0

tbyte	ds	1
ReadRecord
	call	FillBuffer
	mvi	b,0x80
	lxi	hl,_DefDMA
Read0	in	0xa1
	ora	a
	jz	ReadDone
	in	0xa0
	sta	tbyte
	in	0xa1
	ora	a
	jz	ReadDone
	lda	tbyte
	mov	m,a
	inx	hl
	dcr	b
	jnz	Read0
	mvi	a,0	;still more
	ret
ReadDone
	mvi	a,1	;no more
	ret

; fill DMA buffer with cnrtl-z (eof)

FillBuffer
	mvi	b,0x80
	lxi	hl,_DefDMA
	mvi	a,0x1a		;eof
fill0	mov	m,a
	inx	hl
	dcr	b
	jnz	fill0
	ret

;exit if dload file not open
CheckDLopen
	mvi	a,0xff
	out	0xa1
	in	0xa1
	ora	a
	rnz
	Print$	<'\r\nNO Dload file open\r\n'>
	jmp	ExitPGM

FixUpFCB
	mvi	b,35-11
	lxi	hl,_DefFCB+12
	mvi	a,0x00
fix0	mov	m,a
	inx	hl
	dcr	b
	jnz	fix0
	ret
; 			CPM 1 bad characters 
;			'<','>','.',',','=',';','*'
; 	Additional	CPM 2  bad characters (allowed here since CPM 1,except '[',']')
;			'[',']','|','(',')','\','/'
; 	Additional	CPM  3 bad characters (allowed here since CPM 1)
;			0x21 ;The Bang or Exclamation point

BadChars	db	'<','>','.',',','=',';','*'
		db	'[',']'
eobc
		db	'|','(',')','\','/'
		db	'!'
BadFlag		db	0

CheckIfBadCH
	lxi	hl,BadChars
	mvi	b,eobc-BadChars
cbc0	cmp	m
	jz	FoundBadCH
	inx	hl
	dcr	b
	rz
	jmp	cbc0
FoundBadCH
	lda	BadFlag
	inr	a
	sta	BadFlag	
	ret


CheckFileName
	mvi	a,0
	sta	BadFlag

	lxi	hl,_DefFCB+1
	mvi	b,11

	mov	a,m
	cpi	' '
	jz	BadFileName
	
cfn0
	push	bc
	push	hl
	mov	a,m
	call	CheckIfBadCH	;return Z=good, not Z bad
	pop	hl
	pop	bc
	jnz	BadFileName
	inx	hl
	dcr	b
	rz
	jmp	cfn0

BadFileName
	Print$	<'\r\nBad Filename\r\n'>
	jmp	ExitPGM

	end	~Entry		;set entry point


