	Z80
	PreDef	Math
	MacLib	CPM22

	Entry	0x100

	Include CPM22.ASI

	Globals

	Stack	020h
	Startup

	Print$	<'ULOAD Version 1.0 for CPM 1 and IMDOS\r\n'>

	call	ScanForOpt

	BDOSDE	_SetDMA,_DefDMA
	
	call	CheckDLopen

	call	OpenFile
	
	lda	optBorT
	ora	a
	jnz	Ptext

	Print$	<'\r\n   Uploading as Binary...'>
	jmp	again
Ptext	Print$	<'\r\n   Uploading as Text...'>

again
	call	ReadRecord
	jnz	Finished

	lda	optBorT
	ora	a
	jnz	Wtext

	call	WriteRecordBinary
	jmp	again
Wtext	call	WriteRecordText
	jmp	again
	
Finished
	BDOSDE	_Close,_DefFCB
	Print$	<'Finished\r\n'>
ExitPGM
	Exit

optBorT	db	0

OpenFile
	Call	FixUPFCB
	BDOSDE _Open,_DefFCB
	cpi	4
	rc
NOTexist
	Print$	<'\r\nFile does NOT exist\r\n'>
	jmp	ExitPGM
	
;returns a= 0=OK , not 0=eof

RDRecCnt	dw	0

ReadRecord
	lhld	RdRecCnt
	inx	hl
	shld	RdRecCnt
	BDOSDE _ReadSEQ,_DefFCB
	ora	a	;0=OK , not 0=eof
	ret

WriteRecordText
	mvi	b,0x80
	lxi	hl,_DefDMA
WriteT0
	in	0xa3
	ora	a
	jz	WriteFailed
	mov	a,m
	cpi	26
	rz
	out	0xa2
	inx	hl
	dcr	b
	jnz	WriteT0
	ret

WriteRecordBinary
	mvi	b,0x80
	lxi	hl,_DefDMA
WriteB0
	in	0xa3
	ora	a
	jz	WriteFailed
	mov	a,m
	out	0xa2
	inx	hl
	dcr	b
	jnz	WriteB0
	ret

WriteFailed
	Print$	<'\r\nFailed writing to system\r\n'>	
	jmp	ExitPGM

;exit if dload file not open
CheckDLopen
;	mvi	a,0xff
;	out	0xa3
	in	0xa3
	ora	a
	rnz
	Print$	<'\r\nNO Uload 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

ScanForOpt
	lxi	hl,_DefDMA
	mov	a,m
	cpi	2
	jc	Usage

	lxi	hl,_DefFCB1+1
	mov	a,m
	cpi	' '
	rz

	call	ScanForB
	cz	SetOptB
	rz

	lxi	hl,_DefFCB1+1
	call	ScanForT
	cz	SetOptT
	rz

; neither b nor t was found in aux FCB and aux FCB is NOT blank

	lxi	hl,_DefFCB+1
	call	ScanForB
	cz	SetOptB
	jz	foundOPT

	lxi	hl,_DefFCB+1
	call	ScanForT
	cz	SetOptT
	jz	foundOPT
	
	Print$	<'\r\nInvalid Option\r\n'>
	jmp	Usage
	
	ret
foundOPT
	Move	_DefFCB,_DefFCB1,16
	ret
ScanForT
	mov	a,m
	cpi	'-'
	rnz
	inx	hl
	mov	a,m
	cpi	'T'
	rnz
	inx	hl
	mov	a,m
	cpi	' '
	rz
	cpi	0
	ret
ScanForB
	mov	a,m
	cpi	'-'
	rnz
	inx	hl
	mov	a,m
	cpi	'B'
	rnz
	inx	hl
	mov	a,m
	cpi	' '
	rz
	cpi	0
	ret
SetOptB
	mvi	a,0
	sta	optBorT
	ret
SetOptT
	mvi	a,1
	sta	optBorT
	ret

Usage
	Print$	<'\r\Usage:\r\n'>
	Print$	<'\r\ ULOAD <filename> [-b|-t]\r\n'>
	Print$	<'    -b binary\r\n'>
	Print$	<'    -t text\r\n\r\n'>
	jmp	ExitPGM

	end	~Entry		;set entry point


