;*****************************************************************************
;
;  Flop2PC - Transfer floppy image to PC over a serial port
;		(for Vector Graphic 8 inch controller)
;
;	This program transmits an image of an 8 inch floppy to a PC,
;	The image is transmitted through a Bitstreamer II or ZCB serial
;	port using the XMODEM protocol. Since the DSDD disks are 1 mb
;	in size, the program gives the option to end the transmission
;	when multiple tracks of E5's are detected indicating the 
;	probable end of file data on a CP/M disk.
;
;	The program talks directly to the Vector Graphic 8 inch FDC
;	and does not require CP/M or an OS to function. The program 
;	runs standalone at 0x100 or under CP/M.
;
;	This program works best if console port and the transfer port
;	are not the same device. Otherwise, most error messages won't
;	be seen as the file transfer dialog box prevents their display.
;
;	Written by Mike Douglas
;
;	Rev	 Date	    Desc
;	1.0	04/23/16    Original
;
;	1.1	05/08/16    Add support for VG SSSD and IBM SSSD disks.
;			    Implement software fix for race condition
;			    in Rev 0 of the controller. See comments
;			    in dRdSec and dWrSec.
;
;*****************************************************************************

	maclib	z80		;bring in Z80 opcodes

; VG Monitor Locations

VGMON	equ	0E000h		;base address of VG monitor

; Disk information equates

NUMCYL	equ	77
NUMTRK	equ	154		;number of tracks (double density)
NUMSEC	equ	26		;number of sectors per track
SECLEN	equ	256		;sector length (as double density)
MINDRV	equ	0		;first drive number
MAXDRV	equ	3		;max drive number 

DDTRKL	equ	(NUMSEC*SECLEN)	;length of track (double density)
SDTRKL	equ	DDTRKL/2	;length of track (single density)
RDTRIES	equ	3		;disk retries per retry step

IBMSSSD	equ	0		;disk type code saved in dskType
VGSSSD	equ	1
VGDSDD	equ	2

; Specify head settle delay (in addition to the 10ms step delay provided
;    by the 1793), and the amount of time to delay between reversing
;    track steps (e.g., step in/out or step out/in sequence). 
;
; Set ONEMS to give a 1ms delay for a 19 cycle loop cycle loop

HDSETL	equ	10		;10ms additional head settle after step
STPREV	equ	10		;10ms delay when reversing step direction
;ONEMS	equ	105		;105*19 cycles = 1ms at 2Mhz (8080)
ONEMS	equ	211		;211*19 cycles = 1ms at 4Mhz (Z80)

; Monitor, CP/M boot entry points

MONITOR	set	VGMON		;Vector Graphic monitor entry point
CPMBOOT	set	0		;CP/M warm boot jump vector

; XMODEM equates

PKTLEN	equ	128		;128 byte xmodem packet length
SOH	equ	001h
EOT	equ	004h
ACK	equ	006h
NAK	equ	015h
EOF	equ	01Ah		;ctrl-z character
XMTRIES	equ	10		;number of xmodem retries

; CP/M Equates

WBOOT	equ	0		;warm boot jump vector

; Misc equates

CR	equ	13		;ascii for carriage return
LF	equ	10		;ascii for line feed
DEL	equ	7Fh		;ascii DEL
BS	equ	08h		;ascii backspace
CTRLC	equ	03		;ascii for control-c
JMPINST	equ	0C3h		;jump instruction opcode
NMIVECT	equ	066h		;location of NMI interrupt vector

	org	0100h		;load address
;-----------------------------------------------------------------------------
;   Initialize for transfer
;-----------------------------------------------------------------------------
init	lxi	sp,ourStk	;initialize stack pointer
	call	chkCpm		;set flag for CP/M or not
	call	sizeRam		;determine amount of RAM available

	lxi	h,0C9F1h	;NMI routine: POP PSW then RET
	shld	NMIVECT		;install NMI interrupt routine

	mvi	a,MINDRV	;a=default drive
	sta	drvNum		;need for pgmExit

;  Display welcome message, then get the drive number and port number
;    to use for the transfer from the operator.

	lxi	h,mWelcom	;display welcome message
	call	dispMsg

; getDrv - get drive number or letter from the user.

getDrv	lxi	h,mDrive	;display drive number prompt
	call	dispMsg
	call	rcvCon		;get byte from the console
	ori	20h		;upper case letters to lower case
	cpi	'x'		;exit requested?
	jz	pgmExit		;yes

	lxi	h,baseDrv	;ascii 1st drive - baseDrv = 0
	sub	m
	cpi	MAXDRV-MINDRV+1	;validate >=min drive and <= max drive
	jnc	getDrv		;invalid, prompt again

	adi	MINDRV		;restore offset of 1st drive (if any)
	sta	drvNum		;save the drive number to use

	call	dRestor		;restore to track 0 (selects drive)

; getType - get disk type from the user. Save in dskType. Save tracks
;    to process based on disk type in trkCnt.

getType	lxi	h,mType		;display disk type prompt
	call	dispMsg
	call	rcvCon		;get byte from the console
	ori	20h		;upper to lower case, nums not affected
	cpi	'x'		;exit requested?
	jz	pgmExit		;yes

	sui	'1'		;'1' - '3' to binary 0-2
	cpi	3		;validate ascii 1-3
	jnc	getType		;invalid, prompt again

	sta	dskType		;save the disk type

	cpi	VGDSDD		;double sided?
	mvi	a,NUMTRK	;A=154 tracks for double sided
	jz	savTrks		;yes, save track count of 154

	rrc			;else, A=77 tracks for single sided	

savTrks	sta	trkCnt

; getPort - get serial port number from the user.

getPort	lxi	h,mPort		;display transfer port prompt
	call	dispMsg
	call	rcvCon		;get byte from the console
	ori	20h		;upper to lower case, nums not affected
	cpi	'x'		;exit requested?
	jz	pgmExit		;yes

	sui	'1'		;'1' - '2' to binary 0-1
	cpi	2		;validate ascii 1-2
	jnc	getPort		;invalid, prompt again

	sta	xfrPort		;save the port to use

; See if user wants to end tranmission when multiple tracks of E5
;    are detected. If yes, fillDat is set to E5, otherwise to 'n'

	lxi	h,mEndDat	;display end on E5 prompt
	call	dispMsg
	call	rcvCon		;get response
	ori	20h		;upper case to lower case
	cpi	'n'		;no?
	jz	saveEod		;save "no" status"

	mvi	a,0E5h

saveEod	sta	fillDat		;tracks searched for all (fillDat)

; Prompt the user to start the XMODEM receive operation on the PC. 
;    Wait for a clear receive line for a least one second, then start
;    looking for NAK or 'C' (crc protocol) from the PC

	lxi	h,mStart	;display start file transfer prompt
	call	dispMsg

clrRcv1	call	rcvByte		;loop until input clear for 1 second
	jnz	clrRcv1

	xra	a		;set CRC flag to false (checksum mode)
	sta	crcFlag

waitNak	call	chkQuit		;give user chance to abort
	call	rcvByte		;wait for a character
	cpi	NAK
	jz	haveNak		;have a NAK, use checksum protocol

	cpi	'C'		;CRC protocol requested?
	jnz	waitNak		;no

	sta	crcFlag		;set crc flag non-zero = CRC mode

;  NAK or 'C' received meaning the XMODEM receive has started. Initialize
;     for the transfer.

haveNak	xra	a		;init track we want to zero
	sta	trkNum
	sta	lastSec		;last sector accessed

	inr	a		;init xmodem block number to one
	sta	blkNum

	lxi	h,trkBuf	;trkBuf is initial starting point for
	shld	sndPtr		;   XMODEM send

;-----------------------------------------------------------------------------
;  mainLp - Loop through all tracks on the disk buffering as many tracks
;    as will fit in RAM before sending via xmodem, then repeat.
;-----------------------------------------------------------------------------
mainLp	lxi	h,trkBuf	;disk buffering always start at trkBuf
	shld	trkPtr

; Read and buffer bufTrks tracks unless all tracks on drive reached first

bufLoop	call	readTrk		;read into trkBuf

	lda	trkCnt		;put tracks to process in B (preserve HL)
	mov	b,a		;B=tracks to process (77 or 154)

	lda	trkNum		;increment track number (preserve HL)
	inr	a
	sta	trkNum	

	cmp	b		;done all tracks on the disk?
	jz	sendBuf		;yes, go send the buffered tracks

	lda	trkErr		;read failure on the track?
	ora	a		;if so, send buffered tracks now
	jnz	sendBuf		;so XMODEM won't time out

	xchg			;de=current track pointer
	lhld	bufEnd		;hl=end of buffering space
	call	cmpDeHl		;compare current-end
	jc	bufLoop		;still room, keep going	

; Track buffer is full or all tracks have been read. Send the buffered
;    tracks via xmodem.

sendBuf	call	chkE5s		;see if all E5's (probably end of data)
	call	sndTrks		;send the buffered tracks via xmodem

	lda	trkCnt		;put tracks to process in B (preserve HL)
	mov	b,a		;B=tracks to process (77 or 154)
	lda	trkNum		;A=track we're on
	cmp	b		;done all tracks?
	jnz	mainLp		;no, not done yet

; The entire disk has been read and (mostly) transmitted. See if there are
;    left over bytes to send. If so, send them.

	mov	a,l		;hl->next packet to send, a=lsb of ptr
	cpi	trkBuf AND 0ffh	;pointing to lsb of address of trkBuf?
	jz	noExtra		;same, no extra bytes to send

	call	sndPkt		;otherwise, send one last packet

; Send EOT and wait for response. Then display the success message and
;    start the program over.

noExtra	call	sndEot		;send and get response for EOT
	lxi	h,mDone		;print the all done message
	call	dispMsg
	jmp	getDrv		;start over asking for a drive
	
;-----------------------------------------------------------------------------
; readTrk - read NUMSEC sectors from the current track into a trkBuf as
;   pointed to by trkPtr. After the track is read, trkPtr is updated
;   by the length of a track to point to the next track buffer. This
;   saved value is also returned in HL.
;-----------------------------------------------------------------------------
readTrk	lxi	h,trkNum	;get desired track from trkNum	
	mov	l,m		;and put into l
	call	dSeek		;seek to the track

	xra	a
	sta	trkErr		;no error on this track yet

	mvi	a,2		;init retry step
	sta	rtStep

; To make sure the head is settled following the track step, yet still
;    minimize latency, add 6 to the last sector number accessed (and
;    wrap as needed). When this sector number is used in the call to
;    dNxtSec, a total delay of about 38ms has transpired since the step
;    was issued.

	lda	lastSec		;last sector accessed
	adi	6		;bump by six sector times
	cpi	NUMSEC+1	;past 26?
	jc	noWrap

	sui	NUMSEC		;wrap to sector 1-n

noWrap	mov	e,a		;e=new "last" sector number

; Read an entire track. Start after the sector in e. 

	mvi	d,NUMSEC	;d=sector counter

secLoop	call	dNxtSec		;e=next sector, bc=offset within track

stpLoop	lhld	trkPtr		;hl->start of current track buffer
	dad	b		;hl->sector buffer

	call	chkQuit		;check for ctrl-c from operator

	call	dRead		;read the sector
	jnz	secRtry		;error, run retry logic	

; Decrement sector count. If full track is done, increment trkPtr
;   to point to the next track buffer in trkBuf and exit.

nxtSec	dcr	d		;decrement sector count
	jnz	secLoop
	
	lhld	trkPtr		;hl=current track pointer
	lxi	d,DDTRKL	;de=bytes in a double density track
	lda	secSize		;current track single or double density?
	ora	a
	jz	addLen		;0=256 bytes in sector (double density)

	lxi	d,SDTRKL	;de=bytes in a single density track	

addLen	dad	d		;hl=start of next track in trkBuf
	shld	trkPtr
	ret

;--------------------------------------------------------------------------
; secRtry - Read error retry logic. Three retry steps are tried in
;   the order shown below:
;
;   Step    Action
;    2	Re-read RDTRIES times
;    1	Seek out one track and back, then re-read RDTRIES times
;    0	Seek in one track and back, then re-read RDTRIES times
;
;    Upon entry, if the error is "sector not found," then retries are
;    not performed since the controller has already tried to read the
;    address mark across three revolutions.
;--------------------------------------------------------------------------	
secRtry	ani	sSECERR		;sector not found error?
	jnz	nxtStep		;yes, skip retries, go to next step

	mvi	a,RDTRIES	;init retry counter
	sta	rdRtry

retryLp	call	dWtSec		;get bc=offset of sector e in track
	lhld	trkPtr		;hl->start of current track buffer
	dad	b		;hl->sector buffer

	call	chkQuit		;check for ctrl-c
	
	call	dRead		;read the sector
	jz	rtDone		;success, retry is done

	lxi	h,rdRtry	;decrement retry counter
	dcr	m
	jnz	retryLp		;try again

; nxtStep - move to the next retry step

nxtStep	lxi	h,rtStep	;decrement to next retry step
	dcr	m
		
	jz	skPast		;step 0, step in one track and come back	
	jp	skBack		;step 1, step out one track and come back

; All retry steps failed. Display the error, then jump back into the main
;    read loop which will resume at the next sector.

	call	dspErr		;give up, display the error

; rtDone - retry logic is done. Reset the retry step counter and
;    jump to end of sector processing above

rtDone	mvi	a,2		;restart retry step counter
	sta	rtStep
	jmp	nxtSec

;-----------------------------------------------------------------------------
; skBack - step out then back in, retry read
; skPast - step in then back out, retry read
;-----------------------------------------------------------------------------
skBack	lda	trkNum		;a=current track
	dcr	a		;move out one track
	jp	doBump		;not before track zero, do the step out

skPast	lda	trkNum		;a=current track
	inr	a		;move in one track
	cpi	NUMTRK		;past end?
	jnc	skBack		;yes, do seek back instead
	
doBump	mov	l,a
	call	dSeek		;issue step out or in

	mvi	a,STPREV	;delay for step direction reversal
	call	delayMs

	lxi	h,trkNum	;get desired track from trkNum
	mov	l,m		;and put into l
	call	dSeek		;seek back to the track

	mvi	a,HDSETL	;delay head settle time after step
	call	delayMs

	call	dWtSec		;get bc=offset of sector within track
	jmp	stpLoop		;start reads for new step

;-----------------------------------------------------------------------------
; chkE5s - see if the entire buffer of multiple tracks is all E5. For
;    a CP/M disk, this indicates there are probably no more files on the
;    disk. If so, jump to the exit point in the main loop (noExtra).
;-----------------------------------------------------------------------------
chkE5s	lhld	trkPtr
	xchg			;de->end of buffered data + 1
	lxi	h,trkBuf	;hl->start of buffered data
	call	subDeHl		;hl=length of buffered data
	xchg			;de=length of bufferd data
	lxi	h,trkBuf	;hl->start of buffered data

	lda	fillDat		;E5 (or 'n')
	mov	b,a		;save in B

e5Loop	mov	a,b		;A=E5 (or 'n')
	cmp	m
	rnz			;byte other than E5 found

	inx	h		;move to next byte
	dcx	d		;decrement byte count
	mov	a,d
	ora	e
	jnz	e5Loop	

	lxi	sp,ourStk	;restore stack pointer
	jmp	noExtra		;jump to exit steps of main loop

;-----------------------------------------------------------------------------
; sndTrks - send the tracks buffered in trkBuf via xmodem. trkPtr points
;    to the end+1 of the data to send
;-----------------------------------------------------------------------------
sndTrks	lhld	trkPtr		;hl=end of buffered data + 1
	xchg			;de=end of buffered data + 1
	lhld	sndPtr		;hl=start tranmission address

sndLoop	push	d		;save end pointer
	call	sndPkt		;send a packet
	pop	d		;de=end pointer

; At this point, hl->start of next packet and de->last byte read from disk+1.
;    If the next XMODEM packet will go past the end of the disk data,
;    we don't want to send it yet.

	lxi	b,PKTLEN	;bc=length of XMODEM packet
	dad	b		;hl=address at end of NEXT packet + 1
	call	cmpDeHl		;compare disk end - end of next packet
	jc	sndDone		;next packet will pass the end, stop

	lxi	b,-PKTLEN	;restore hl
	dad	b
	jmp	sndLoop

; sndDone - all the packets we can send have been sent. Move any bytes
;    left over to just before the start of trkBuf. The next group of
;    xmodem packets will be transmitted starting there.

sndDone	call	subDeHl		;hl=de-hl = left over byte count - PKTLEN
	mov	a,l		;a=left over count - PKTLEN
	adi	PKTLEN		;a=left over byte count
	mov	b,a		;b=count of bytes to move
	lxi	h,trkBuf	;hl->start of trkBuf
	jz	mvDone		;no bytes to move, we're done

; Copy the leftover data backwards to just before the track buffer. The
;   next XMODEM send sequence will start at the beginning of this copied
;   data instead of at the start of trkBuf.

moveLp	dcx	h		;hl->memory just before trkBuf
	dcx	d		;de->unsent bytes from end of trkBuf
	ldax	d		;move from end of trkBuf to before trkBuf
	mov	m,a	
	dcr	b
	jnz	moveLp

mvDone	shld	sndPtr		;save address from which to send next time
	ret

;-----------------------------------------------------------------------------
; sndPkt - send an xmodem format 128 byte packet. HL points to the 128 byte
;    buffer to send. On exit, HL points to the next 128 byte boundary.
;-----------------------------------------------------------------------------
sndPkt	mvi	a,XMTRIES	;init retry counter
	sta	xmRetry

; First, send header bytes

reSend	call	chkQuit		;check for ctrl-c
	push	h		;save hl for possible re-send
	mvi	a,SOH		;1st byte is SOH
	call	sndByte
	lda	blkNum		;2nd byte is the block number
	call	sndByte
	cma			;2nd complement of block number
	call	sndByte

; Init checksum and CRC and packet length for transmission of data portion

	xra	a		;init crc
	sta	crc16
	sta	crc16+1
	lxi	d,PKTLEN*256	;d=byte counter, e=0 (checksum)

; Loop sending the data bytes and updating checksum and CRC

pktLoop	mov	a,m
	call	sndByte		;send and update checksum in e
	call	calCrc		;update the CRC
	inx	h		;point to next byte
	dcr	d		;decrement bytes remaining
	jnz	pktLoop

; Send checksum or CRC based on crcFlag

	lda	crcFlag		;crc or checksum?
	ora	a
	jz	sndCsum		;flag clear = checksum

	lda	crc16+1		;a=high byte of CRC
	call	sndByte		;send it
	lda	crc16		;a=low byte of crc
	jmp	sndSkip		;skip next instruction	

sndCsum	mov	a,e		;send the checksum byte

sndSkip	call	sndByte

;  All bytes sent. Wait for the response.

	call	rcvByte		;get the response character
	jz	sndFail		;timeout on response

	cpi	ACK		;ack received?
	jnz	sndFail		;no, send failed

	lda	blkNum		;increment block number
	inr	a
	sta	blkNum

	pop	b		;remove pushed hl, but don't clobber hl
	ret

; sndFail - ACK not received, decrement retry and try again.

sndFail	lxi	h,xmRetry	;point to retry counter
	dcr	m
	jz	xmFail		;retries used up, failed xmodem transfer

; If we've had 3 NAKs on the 1st packet and CRC is selected, assume
;   we took so long to send the 1st packet due to disk retries that
;   the receiver has since timed out and switched to checksum

	lda	crcFlag		;are we in CRC mode
	jz	clrRcv2		;no, ignore the rest of this

	lda	blkNum		;on block 1?
	dcr	a
	jnz	clrRcv2		;no, go on

	lda	xmRetry		;failed three times in a row on block 1?
	sui	XMTRIES-3
	jnz	clrRcv2		;no

	sta	crcFlag		;clear crcFlag to force checksum

;  clrRcv2 - wait for one second of line clear time and send packet again.

clrRcv2	call	rcvByte		;wait for 1 second of clear line
	jnz	clrRcv2

	pop	h		;restore pointer to the packet
	jmp	reSend		;re-send the packet

;  xmFail - Display failure message then restart program

xmFail	lxi	h,mXmdm		;xmodem failure message
	call	dispMsg

	lxi	sp,ourStk	;initialize stack pointer
	jmp	getDrv		;start over asking for drive

;-----------------------------------------------------------------------------
; calCrc - update the 16-bit CRC with one more byte. 
;    (Copied from M. Eberhard)
; On Entry:
;   a has the new byte
;   crc16 is current except this byte
; On Exit:
;   crc16 has been updated
;   Trashes a,bc
;-----------------------------------------------------------------------------
calCrc	push	d
	push	h
	lhld	crc16		;get CRC so far
	xra	h		;XOR into CRC top byte
	mov	h,a
	lxi	b,1021h		;bc=CRC16 polynomial
	mvi	d,8		;prepare to rotate 8 bits

; do 8 bit shift/divide by CRC polynomial

cRotLp	dad	h		;16-bit shift
	jnc	cClr		;skip if bit 15 was 0
	mov	a,h		;CRC=CRC xor 1021H
	xra	b
	mov	h,a
	mov	a,l
	xra	c
	mov	l,a
cClr	dcr	d
	jnz	cRotLp		;rotate 8 times

; save the updated CRC and exit

	shld	crc16		;save updated CRC
	pop	h
	pop	d
	ret

;-----------------------------------------------------------------------------
;  sndEot - send EOT character and wait for ACK response
;-----------------------------------------------------------------------------
sndEot	mvi	a,XMTRIES	;init retry counter
	sta	xmRetry

reEot	mvi	a,EOT		;send the EOT
	call	sndByte
	call	rcvByte		;wait for response
	jz	eotFail		;timeout

	cpi	ACK		;ack received?
	jnz	eotFail		;no, eot send failed

	ret			;otherwise, we're done.

; timeout waiting for ACK to EOT. Decrement retry counter and try again

eotFail	lxi	h,xmRetry	;point to retry counter
	dcr	m
	rz			;just give up - xfer was probably good

clrRcv3	call	rcvByte		;wait for 1 second of clear line
	jnz	clrRcv3
	jmp	reEot		;try again

;-----------------------------------------------------------------------------
; dispMsg - display the null-terminated message passed in hl on the
;    console device. Clobbers b, hl
;-----------------------------------------------------------------------------
dispMsg	mov	a,m		;get the next message byte
	ora	a		;null terminates
	rz

	mov	b,a		;conOut wants character in b
	call	conOut
	inx	h		;move to next byte
	jmp	dispMsg

;-----------------------------------------------------------------------------
; rcvCon - Receive a character from the console device, echo it, then
;   wait for a CR. Exits program if Ctrl-c typed. Returns with invalid
;   character (null) if BS or DEL pressed after 1st character
;   Returns character in a, clobbers b.
;-----------------------------------------------------------------------------
rcvCon	call	conIn		;check for input
	jz	rcvCon		;nothing

	ani	7fh
	cpi	CTRLC		;abort requested?
	jz	pgmExit		;yes

	cpi	CR		;return pressed?
	rz			;yes, don't echo it

	mov	b,a		;conOut needs character in b
	call	conOut		;echo it

; Wait for CR, then return 1st character typed

rcvCr	call	conIn		;check for input
	jz	rcvCr		;nothing

	ani	7fh
	cpi	CTRLC		;abort requested?
	jz	pgmExit		;yes

	cpi	DEL		;delete
	rz			;yes, return DEL character

	cpi	BS		;backspace?
	rz			;yes, return BS character

	cpi	CR		;return pressed?
	jnz	rcvCr		;no, keep waiting

	mov	a,b		;return 1st character typed
	ret

;-----------------------------------------------------------------------------
; sndByte - send the byte in a through the specified transfer port. 
;     Adds the byte to register e for checksum. Clobbers b.
;     XMODEM send routine assumes serOut returns with a containing
;     the character sent.
;-----------------------------------------------------------------------------
sndByte	mov	b,a		;b=byte to transmit
	add	e		;update checksum
	mov	e,a		;e=updated checksum
	lda	xfrPort		;a=port to use for transfer
	jmp	serOut		;send the character

;-----------------------------------------------------------------------------
; rcvByte - Receive a byte from specified transfer port with a one second
;     timeout. If a timeout occurs, zero is returned in A and the zero 
;     flag is true. Otherwise, the character is returned in A (could be
;     zero) and zero flag is false. ONESEC must be set based on processor
;     speed and the number of cycles in the serIn call + 64. 
;     Clobbers a, b and c.
;-----------------------------------------------------------------------------
rcvByte	lxi	b,ONESEC	;bc=cycles through this loop for 1s

rcvWait	lda	xfrPort		;(14) a=port to use for transfer
	call	serIn		;(18+cycles in serIn)look for a byte
	rnz			;(6) byte received

	dcx	b		;(5) otherwise, decrement timer
	mov	a,b		;(5) one second expire?
	ora	c		;(5)
	jnz	rcvWait		;(11) no, keep waiting

	ret			;return with timeout (zero true and in a)

;-----------------------------------------------------------------------------
; dspErr - display the current track and sector number which just had
;     a read error. If this is the first error on a track, the track
;     number is displayed first.
;
;  on entry:
;     e = sector number
;-----------------------------------------------------------------------------
dspErr	lda	trkErr		;test track error flag
	ora	a
	jnz	dspSec		;track already displayed, go display sector

	inr	a		;set track flag non-zero
	sta	trkErr

; First error on this track. Display "Track xx errors: "

	lxi	h,errTrk	;hl->where to put ascii decimal
	lda	trkNum		;a=track with error on it
	call	bin2dec		;track to ascii
	lxi	h,mTrkErr	;display the track error message
	call	dispMsg

; dspSec - display the sector number with an error

dspSec	lxi	h,errSec	;hl->where to put ascii sector
	mov	a,e		;a=sector where error occured
	call	bin2dec
	call	dispMsg		;display the error
	ret

;--------------------------------------------------------------
; bin2dec - Binary byte in A to 2 ASCII digits at (HL)
;   HL is preserved
;--------------------------------------------------------------
bin2dec	mvi	m,' '		;assume zero supression
	sui	10		;value less than 10?
	jc	do1s		;yes, leading blank
	mvi	m,'1'		;have one ten already

loop10	sui	10		;count 10s
	jc	do1s		;done with 10s, do 1s
	inr	m
	jmp	loop10

do1s	adi	'0'+10		;form ASCII 1s digit
	inx	h		;move to 1s position
	mov	m,a
	dcx	h		;restore hl
	ret

;--------------------------------------------------------------
; chkQuit - check for the user to request abort (ctrl-c). If
;    a character is present on the console port, read it and
;    see if ctrl-c. Clobbers A
;--------------------------------------------------------------
chkQuit	call	conIn		;check for console input
	rz

	ani	7fh
	cpi	CTRLC		;abort requested?
	rnz			;no

; Ctrl-C typed while program is running. Return to drive prompt.

	lxi	sp,ourStk	;initialize stack pointer
	jmp	getDrv		;start over asking for drive num

;--------------------------------------------------------------
; pgmExit - Exit to CP/M or to the monitor ROM based on the
;    CP/M flag
;--------------------------------------------------------------
pgmExit	lda	cpmFlag		;running under CP/M?
	ora	a
	jnz	cpmExit		;yes

; Exit to ROM monitor

	lxi	h,mExit		;display "exiting" message
	call	dispMsg
	jmp	MONITOR		;jump to ROM monitor entry point

; CP/M exit. If boot drive was used, prompt user to insert CP/M disk

cpmExit	lda	drvNum		;boot drive used?
	sui	MINDRV
	jnz	noDisk		;not 1, disk prompt not needed

	lxi	h,mCpm		;display "insert cp/m disk"	
	call	dispMsg
	call	rcvCon		;wait for a character

noDisk	mvi	a,MINDRV	;re-select drive A for CP/M 1.4
	sta	drvNum
	call	dSelDrv

	lxi	h,mExit		;display "exiting" message
	call	dispMsg
	jmp	CPMBOOT		;reboot CP/M

;--------------------------------------------------------------
; chkCpm - check if running under CP/M. CP/M flag is set true
;   (non-zero) if yes, cleared otherwise.
;--------------------------------------------------------------
; First, initialize entries for stand-alone

chkCpm	xra	a
	sta	cpmFlag		;clear CP/M flag
	mvi	a,MINDRV+'0'	;ascii for minimum drive number
	sta	mDrvMin		;store in the drive prompt message
	sta	baseDrv		;ascii 1st drive - baseDrv = 0
	mvi	a,MAXDRV+'0'	;ascii for max drive number
	sta	mDrvMax

; Determine if we're under CP/M or standalone. CP/M is assumed if
;   a jump instruction is present at the CP/M warm start location (0)
;   and five more jumps (e.g., a jump table) is present at the
;   jump-to destination.
		
	lda	WBOOT		;see if jump instruction present for CP/M
	cpi	JMPINST
	rnz			;no, not CP/M

; A jump instruction is present at the CP/M warm boot location (0),
;   now see if that jump points to five more jumps. If so, assume CP/M

	lxi	h,WBOOT+1	;point to lsb of jump address
	mov	e,m		;e=low byte of jump
	inx	h
	mov	d,m		;de=destination of jump
	mvi	b,5		;look for 5 more jumps (a jump table)

jmpTest	ldax	d		;a=opcode at jump destination
	sui	JMPINST		;another jump present?
	rnz			;no, not CP/M
	inx	d		;move to next jump
	inx	d
	inx	d
	dcr	b
	jnz	jmpTest

	dcr	a		;a=0ffh
	sta	cpmFlag		;CP/M flag to non-zero = true

; We're running under CP/M. Change drive prompt message to show drive
;    letters instead of drive numbers and change baseDrv to convert
;    an 'A' to the base drive number (MINDRV).

	mvi	a,'A'		;'A' in drive message instead of number
	sta	mDrvMin
	adi	MAXDRV-MINDRV	;max drive letter
	sta	mDrvMax
	mvi	a,'a'		;ascii 1st drive - baseDrv = 0
	sta	baseDrv
	ret

;------------------------------------------------------------------
; sizeRam - determine how much RAM we have for buffering tracks.
;   Sets the bufEnd variable which points to end address of 
;   the last possible track buffer + 1
;------------------------------------------------------------------
; If running under CP/M, use the BIOS pointer to determine the top
;    of available RAM. Otherwise, size RAM manually.

sizeRam	lhld	WBOOT+1		;get address of BIOS jump table+3
	dcx	h		
	dcx	h
	dcx	h		;hl->top of usable ram+1
	lda	cpmFlag		;running under CP/M?
	ora	a
	jnz	ramEnd		;yes, we have the end of RAM

;  Not under CP/M. Find the end of RAM manually.

	lxi	h,(trkBuf+0ffh) AND 0ff00h   ;next 256 byte boundary

ramLoop	mov	a,m		;a=current RAM content
	inr	m		;change RAM
	cmp	m		;did RAM change?
	mov	m,a		;restore RAM
	jz	ramEnd		;end of RAM found

	inr	h		;next page
	jnz	ramLoop

; ramEnd - end of RAM found. Now determine the end address + 1 of the
;   last track buffer that will fit in RAM. Store in bufEnd

ramEnd	xchg			;de=end of RAM + 1
	mvi	a,-((DDTRKL SHR 8) + 1) AND 0ffh
	cmp	d		;force de < (10000h - DDTRKL)
	jnc	topOk

	mov	d,a		;limit max address

topOk	lxi	h,trkBuf	;hl=start of track buffer
	lxi	b,DDTRKL	;bc=length of track in bytes

; Loop increasing hl by DDTRKL until hl > end of RAM.

bfEndLp	dad	b		;hl=hl+track length
	call	cmpHlDe		;compare hl-de
	jc	bfEndLp		;still more room, keep going

; Subtract one track length from hl, this will be the end address + 1 of
;   the the last track buffer that will fit in RAM

	lxi	b,-DDTRKL	;subtract one track length
	dad	b		;hl = end address of last track + 1
	shld	bufEnd		;save as bufEnd
	ret

;--------------------------------------------------------------------
; cmHlDe - compare HL-DE. Carry set if HL<DE, carry clear if HL>=DE
;--------------------------------------------------------------------
cmpHlDe	mov	a,l		;compare HL-DE, do lsbs first
	sub	e
	mov	a,h		;do msbs
	sbb	d
	ret			;carry set HL<DE, clear HL>=DE

;--------------------------------------------------------------------
; cmDeHl - compare DE-HL. Carry set if DE<HL, carry clear if DE>=HL
;--------------------------------------------------------------------
cmpDeHl	mov	a,e		;compare DE-HL, do lsbs first
	sub	l
	mov	a,d		;do msbs
	sbb	h
	ret			;carry set DE<HL, clear DE>=HL

;--------------------------------------------------------------------
; subDeHl - HL=DE-HL
;--------------------------------------------------------------------
subDeHl	mov	a,e		;subtract DE-HL, do lsbs first
	sub	l
	mov	l,a		;lsb result in l
	mov	a,d		;do msbs
	sbb	h
	mov	h,a		;msb result in h	
	ret

;--------------------------------------------------------------------
; delayMs - delay number of MS specified in A. Clobbers B.
;    Be sure to set the ONEMS equate as required for the
;    target CPU.
;--------------------------------------------------------------------
delayMs	mvi	b,ONEMS		;loops for 1ms
	
dlyLoop	nop			;(4)
	dcr	b		;(5)
	jnz	dlyLoop		;(10)

	dcr	a		;decrement ms counter
	jnz	delayMs

	ret

;---------------------------------------------------------------------
; Message constants
;---------------------------------------------------------------------
mWelcom	db	cr,lf,lf
	db	'===== Floppy to PC Disk Image Transfer =====',cr,lf
	db	'     (Vector Graphic 8 in FDC, ver 1.1)',cr,lf,lf
	db	'Sends an image of an 8 inch floppy to a PC through a'
	db	cr,lf
	db	'serial port using the XMODEM protocol.',0

mDrive	db	cr,lf,lf,'Insert and specify source drive ('
mDrvMin	db	'x-'
mDrvMax	db	'x) or X to exit: ',0

mType	db	cr,lf,lf
	db	'Specify the disk type',cr,lf
	db	'  1) SSSD (IBM Format)',cr,lf
	db	'  2) SSSD (VG Format, track 1 is DD)',cr,lf
	db	'  3) DSDD (VG Format)',cr,lf
	db	'Enter disk type or X to exit: ',0

mPort	db	cr,lf,lf
	db	'Specify the serial port to use for file transfer',cr,lf
	db	'  1) Bitstreamer II port A (2/3)',cr,lf
	db	'  2) Bitstreamer II port B or ZCB port A (4/5)',cr,lf
	db	'Enter port or X to exit: ',0

mEndDat	db	cr,lf,lf
	db	'Stop transfer when multiple tracks of E5 detected (Y/N)? ',0

mStart	db	cr,lf,lf,'Start XMODEM receive operation on the PC now...',0

mDone	db	cr,lf,lf,'Transfer complete!',cr,lf,0

mXmdm	db	cr,lf,lf,'XMODEM communication failure',cr,lf,0

mNoTrk0	db	cr,lf,lf,'Seek to track 0 failed',cr,lf,0

mTrkErr	db	cr,lf,'Track '
errTrk	db	'xx failed sectors: ',0
errSec	db	'xx ',0

mExit	db	cr,lf,lf,'Exiting...',cr,lf,0

mCpm	db	cr,lf,lf
	db	'Insert CP/M disk into drive A, then press Return...',0


;****************************************************************************
;
;  Hardware specific console and serial I/O routines. 
;     The following four routines must be written to provide a common
;     interface to the hardware on which this program is running. The
;     port number specified for serIn and serOut matches the port number
;     input from the operator via the port menu.
;
;****************************************************************************

; The rcvByte subroutine above times a one second timeout with a code
;    loop that calls the hardware specific serIn routine below. ONESEC
;    must be set based on processor speed and the number of cycles in 
;    the serIn call + 64 cycles for the rcvByte code. 

ONESEC	equ	35714		;rcvByte loop count for 1 second (4MHz)

; VG Monitor I/O equates

KEYTST	equ	VGMON+3		;test keyboard in VG ROM monitor
KEYDATA	equ	VGMON+6		;input from keyboard in VG ROM monitor
CRT	equ	VGMON+9		;output to screen in VG ROM monitor

; Serial port equates for 8251 on Bitstreamer II and ZCB

PORTADR	equ	2		;port a is at 2/3
PORTASR	equ	3
PORTBDR	equ	4		;port b is at 4/5
PORTBSR	equ	5
XMTMASK	equ	1		;mask to isolate transmit ready bit
RCVMASK	equ	2		;mask to isolate receive ready bit

;----------------------------------------------------------------------------
; conIn - input character from console
;    inputs:
;    outputs: z true if no character present
;	      z false if character returned in a
;    clobbers none
;----------------------------------------------------------------------------
conIn	call	KEYTST		;call ROM monitor to test for console input
	rz			;return zero true if none
	jmp	KEYDATA		;get character typed from ROM monitor

;----------------------------------------------------------------------------
; conOut - output character to console
;    inputs: b = character to send
;    clobbers none
;----------------------------------------------------------------------------
conOut	mov	a,b		;monitor expects character in a
	jmp	CRT		;send/display it

;----------------------------------------------------------------------------
; serIn - input character from port specified in a
;    inputs: a = port to read from
;    outputs: z true if no character present
;	      z false if character returned in a
;    clobbers none
;    48 cycles when not returning a character
;-----------------------------------------------------------------------------
serIn	ora	a		;(5) port b?
	jnz	serInB		;(11) yes

; input from port A

	in	PORTASR		;(12) a=port status register
	ani	RCVMASK		;(8) isolate receive ready bit
	rz			;(12) nothing present
	in	PORTADR		;a=character from serial port
	ret			

; input from port B

serInB	in	PORTBSR		;a=status register
	ani	RCVMASK		;isolate receive ready bit
	rz			;nothing present
	in	PORTBDR		;a=character from serial port
	ret			

;-----------------------------------------------------------------------------
; Hardware specific I/O
; serOut - output character to port specified in a
;    inputs: a = port to transmit through
;	     b = character to send
;    clobbers none
;-----------------------------------------------------------------------------
serOut	ora	a		;port b?
	jnz	serOutB		;yes

; output through port A

serOutA	in	PORTASR		;a=port status register
	ani	XMTMASK		;isolate transmit ready bit
	jz	serOutA		;not ready

	mov	a,b		;a=character to transmit
	out	PORTADR		;transmit the character
	ret	

; output through port B

serOutB	in	PORTBSR		;a=port status register
	ani	XMTMASK		;isolate transmit ready bit
	jz	serOutB		;not ready

	mov	a,b		;a=character to transmit
	out	PORTBDR		;transmit the character
	ret		

;****************************************************************************
;
; Vector Graphic 8" FDC disk I/O routines
;
;****************************************************************************

; Controller Equates

FDCBASE	equ	0E0H		;controller base address
FDCCMD	equ	FDCBASE		;1793 command register
FDCSTAT	equ	FDCBASE		;1793 status register
FDCTRK	equ	FDCBASE+1	;1793 track register
FDCSEC	equ	FDCBASE+2	;1793 sector register
FDCDATA	equ	FDCBASE+3	;1793 data in/out register
FDCSEL	equ	FDCBASE+4	;FDC drive select/status port
FDCWAIT	equ	FDCBASE+5	;FDC stall/wait port

FDMSIDE	equ	04h		;selects top side when set in FDCSEL
FDMDEN	equ	08h		;selects double density when set in FDCSEL

; Commands for 1793.

STPRATE	equ	0		;3ms step rate

cRESTOR	equ	008h+STPRATE	;restore, head load, no verify
cSEEK	equ	018h+STPRATE	;seek, head load, no verify
cSTPIN	equ	058h+STPRATE	;step in, update track reg, head loaded
cSTPOUT	equ	078h+STPRATE	;step out, update track reg, head loaded
cREAD	equ	088h		;read, head assumed settled
cWRITE	equ	0A8h		;write, head assumed settled
cRDADDR	equ	0C4h		;read address marker, wait head settle
cRESET	equ	0D0h		;reset 1793 to idle
cWRTRK	equ	0F4h		;write track command

cWAITHD	equ	004h		;bit for read/write to wait for head settle


; Status bits from 1793

sNOTRDY	equ	80h		;1=not ready
sWRPROT	equ	40h		;1=write protected
sHDLOAD	equ	20h		;1=head is loaded
sSKERR	equ	10h		;1=seek error
sCRCERR	equ	08h		;1=CRC error
sTRACK0	equ	04h		;1=on track zero
sINDEX	equ	02h		;1=index detected
sBUSY	equ	01h		;1=1793 busy

sSECERR	equ	10h		;1=sector not found
sWRTFLT	equ	20h		;1=write fault
sDLOST	equ	04h		;1=lost data 

; Combined status flag masks for status of a seek, read, and write

smSEEK	equ	sSKERR+sCRCERR+sNOTRDY+sBUSY
smREAD	equ	sSECERR+sCRCERR+sDLOST+sNOTRDY+sBUSY
smWRITE	equ	smREAD+sWRPROT+sWRTFLT

;--------------------------------------------------------------
; dSelDrv - Select and wait for drive specified in drvNum 
;    to be ready. 
; On Entry:
;    drvNum = drive to be selected
; On Exit:
;    drive selected and ready, 1793 not busy
; Clobbers none
;--------------------------------------------------------------
dSelDrv	lda	drvNum		;A=drive number
	out	FDCSEL		;select the drive

; reset the 1793 and wait for not busy

	mvi	a,cRESET	;ensure 1793 is idle
	out	FDCCMD
	xthl			;waste some time
	xthl

; drive selected, 1793 idle, wait for drive ready

dWtRdy	in	FDCSTAT
	rlc			;not ready bit in carry
	jc	dWtRdy		;wait for ready
	ret

;--------------------------------------------------------------
; dSeek - Seek track specified in L. Selects drive and loads
;    head. If the head was not already loaded, then the E bit
;    (wait for head settle one-shot) is set in fWaitHd for
;    OR'ing into the subsequent read/write command.
; On Entry:
;    L=track to seek
;    drvNum = drive to use
; On Exit:
;    Z flag set = seek worked and verified
;    Z flag clear = error
;    curCyl = resulting cylinder of the track seek
;    curSide = resulting side (0 or 1) of the track seek
;    secSize = sector size (128 or 256) of current track
; Clobbers C,H,L
;--------------------------------------------------------------
dSeek	equ	$

; See if head is currently loaded. Use the reset (interrupt)
;    command to ensure the status register is type I so it
;    includes the head status bit. If not loaded, set the E
;    bit (wait for head-settle one-shot) in fWaitHd which is
;    OR'd into the subsequent read/write command.

	in	FDCSTAT		;see if head is currently loaded
	ani	sHDLOAD
	mvi	a,cWAITHD	;E flag set for R/W commands
	jnz	doSeek1	;head already loaded

	sta	fWaitHd		;otherwise, set E flag

; Determine the track density, cylinder, and side based on the disk
;    type at the requested track number

doSeek1	mov	a,l		;A=requested track number
	lxi	h,dskType	;C=disk type
	mov	c,m

	mvi	h,0		;H=single density mask
	ora	a		;track zero?
	jz	doSeek2		;yes

	dcr	c		;IBM SSSD?
	jm	doSeek2		;yes, always single density

	mvi	h,FDMDEN	;H=double density, bottom side mask
	cpi	1		;track 1 always DD for VG disks
	jz	doSeek2

	mvi	h,0		;H=single density mask
	dcr	c		;VG SD disk?
	jm	doSeek2		;yes, single density if not track 1

	mvi	h,FDMDEN	;H=double density, bottom side mask
	cpi	NUMCYL		;top or bottom?
	jc	doSeek2		;bottom

	mvi	h,FDMSIDE+FDMDEN   ;H=double density, top side mask
	sui	NUMCYL		;A=proper cylinder

doSeek2	out	FDCDATA		;give 1793 the desired cylinder number
	sta	curCyl		;save the cylinder we're on

	mov	a,h		;save the side selected...
	ani	FDMSIDE		;bit 2 (4's) is side flag 
	rrc	
	rrc
	sta	curSide		;curside = 0 (bot) or 1 (top)	
		
	mov	a,h		;set 128 or 256 bytes (SD or DD)
	ani	FDMDEN		;A=density bit alone
	xri	FDMDEN		;A=0 if DDEN
	jz	savSlen		;save the sector length (0=256)

	mvi	a,128		;otherwise, length is 128

savSlen	sta	secSize

	lda	drvNum		;set density and side on FDC board
	ora	h		;include density and side bits
	out	FDCSEL		;this also selects drive

	mvi	a,cSEEK		;issue seek command
	out	FDCCMD
	call	dWtComp		;wait for seek to complete

	in	FDCSTAT		;test status of the seek
	ani	smSEEK		;any of these bits is an error
	ret

;--------------------------------------------------------------
; dRestor - Restore the currently selected drive to track 0.
; On Entry:    
; On Exit:
;    Z flag set = restore operation worked
;    Z flag clear = restore failed
; Clobbers none
;--------------------------------------------------------------
dRestor	call	dSelDrv		;make sure drive is selected

	mvi	a,cRESTOR	;issue restore to track zero
	out	FDCCMD
	call	dWtComp		;wait for restore to complete

	in	FDCSTAT		;verify restore worked
	ani	smSEEK		;isolate seek bits
	rz			;restore worked

; restore failed

	lxi	h,mNoTrk0

errMsg	call	dispMsg
	lxi	sp,ourStk	;initialize stack pointer
	jmp	getDrv		;start over asking for drive num

;--------------------------------------------------------------
; dWtComp - Wait here for NMI to return to caller. The NMI
;    routine aborts the loop and does the return.
; On Entry:
;    A command has been issued to the 1793
; On Exit:
;    1793 has completed the command
; Clobbers none
;--------------------------------------------------------------
dWtComp	in	FDCSEL		;allows NMI to occur
	nop
	jmp	dWtComp

;--------------------------------------------------------------
; dNxtSec - wait for next (any) sector. For the 1793, this
;    routine simply increments and wraps the sector number
;    passed in E, then falls into dWtSec to return BC with
;    the offset of the sector within the track buffer.
; On Entry:
;    Drive is selected, motor is running
;    E = most recent sector number
; On Exit:
;    E = next sector sector number
;    BC = byte offset of this sector in a track
;--------------------------------------------------------------
dNxtSec	inr	e		;move to next sector
	jz	dSec1		;in case uninitialized rolled to 0

	mov	a,e		;see if past end
	cpi	NUMSEC+1	;verify between 1 and 26
	jc	dWtSec		;good sector, compute bc

dSec1	mvi	e,1		;restart at sector 1
				;fall into dWtSec

;--------------------------------------------------------------
; dWtSec - wait for sector specified in e. For the 1793
;    controller, this routine simply returns the offset
;    of the sector within this track in bc.
; On Entry:
;    e = desired sector number (must be 1-26 for 1793)
;    secSize = sector length on current track
; On Exit:
;    E = sector number
;    BC = byte offset of this sector in a track
;--------------------------------------------------------------
dWtSec	mov	a,e		;save the computed sector
	sta	lastSec

; compute bc=256*(sector-1)

	dcr	a		;zero index sector number
	mov	b,a		;B=MSB of offset
	mvi	c,0		;BC=256*(E-1)

; if single density, then shift offset in BC to the right
;    by one bit for 128 byte sectors vs 256 byte

	lda	secSize		;single or double density track?
	ora	a		;test for zero and clear carry
	rz			;0(256) bytes = double density

	mov	a,b		;shift BC right once (divide by 2)
	rar
	mov	b,a

	mov	a,c
	rar
	mov	c,a

	ret

;--------------------------------------------------------------
; dRead - Read sector on current track
; On Entry:
;    Drive is selected, on proper track, head loaded
;    HL->sector buffer
;    E = sector number to read
; On Exit:
;    Z flag set = success
;    Z flag clear = error
; Clobbers H,L
;--------------------------------------------------------------
dRead	di			
	mov	a,e		;give sector number to FDC
	out	FDCSEC

	lda	fWaitHd		;load head settle (E) flag
	ori	cREAD		;combine with read command

	push	b		;preserve BC, DE
	push	d
	call	dRdSec		;do the data transfer
	pop	d		;restore
	pop	b

	xra	a		;no head settle wait after 1st read
	sta	fWaitHd

	in	FDCSTAT		;get status of the read
	ani	smREAD		;any of these bits is an error
	ei			;re-enable interrupts
	ret		

;--------------------------------------------------------------
; dRdSec - Do the physical transfer of data from the disk
;    into memory. When the disk controller completes the
;    command, it generates an NMI interrupt that returns
;    control to the caller of this subroutine.
; 
;    The FDCWAIT register can't be used for data sync until
;    after the 1793 presents the 1st byte. Therefore, a poll
;    for DRQ must be used for the 1st byte. In order to meet
;    1793 timing requirements for DD data (13.5us worst case)
;    the poll loop uses a computed jump based on reading
;    the board status (select) register. When DRQ is asserted,
;    0FFh is returned, otherwise 0FCh is returned. This loop
;    must be located at xxFCh within a page.
;
;    To handle a race condition that can occur with the Rev 0
;    controller, B' is loaded with FFh (the LSB of the jump
;    address when DRQ is asserted) because the race condition
;    can cause the DRQ poll loop to jump into the middle of
;    the INP L instruction. The 2nd byte evaluates to a MOV L,B
;    instruction, and therefore, moves the LSB of the proper
;    jump address into L for subsequent PCHL jump.
;
; On Entry:
;    Read sector or read address command issued to controller
;    HL->sector (or address mark) buffer
; On Exit:
; Clobbers All (may exit while in alternate registers)
;
; One cycle has been added to all instruction times to account
; for the wait state added by the VG ZCB during M1.
;--------------------------------------------------------------

RDSIZE	set	drWt1st-dRdSec

;	org	(($+RDSIZE+100h-0FCh) AND 0FF00h) + (0FCh - RDSIZE)
	org	(($+0Ch+100h-0FCh) AND 0FF00h) + (0FCh - 12h)

dRdSec	out	FDCCMD		;issue command from A

	lda	secSize		;put sector size-1 in B
	dcr	a
	mov	b,a

	mvi	c,FDCDATA	;C=port to read for data byte

	push	h		;putting HL into DE'
	inx	h		;HL->2nd byte location
	exx
	pop	d		;DE'=original HL

	mvi	h,(drWt1st SHR 8) AND 0FFh   ;H'=msb of jump address
	lxi	b,((dRd1st AND 0FFh) SHL 8) + FDCSEL

drWt1st	inp	l		;(13) L=FCh (no DRQ) or FFh (DRQ)
	pchl			;(5) jump to drWt1st or dRd1st

dRd1st	in	FDCDATA		;(12) read 1st byte
	stax	d		;(8) store in buffer
	exx			;(5) back to regular registers

dRdLoop	in	FDCWAIT		;(12) wait for next byte
	ini			;(17) retrieve and store byte
	jnz	dRdLoop		;(11)

	jmp	dWtComp		;all bytes read, go wait for interrupt

	if	0		;write not used in Flop2PC
;--------------------------------------------------------------
; dWrite - Write a sector on current track
; On Entry:
;    Drive is selected, on proper track, head loaded
;    HL->buffer address
;    E = sector number to write
; On Exit:
;    Z flag set = success
;    Z flag clear = error
; Clobbers H,L
;--------------------------------------------------------------
dWrite	di
	mov	a,e		;give sector number to FDC
	out	FDCSEC

	lda	fWaitHd		;load head settle (E) flag
	ori	cWrite		;combine with write command

	push	b		;save BC
	push	d		;save DE
	call	dWrSec		;do the data transfer
	pop	d		;restore
	pop	b

	xra	a		;no head settle wait after 1st write
	sta	fWaitHd

	in	FDCSTAT		;get status of the write
	ani	smWRITE		;any of these bits is an error
	ei			;re-enable interrupts
	ret

;--------------------------------------------------------------
; dWrtTrk - Write a track for formatting
; On Entry:
;    Drive is selected, on proper track
;    HL->track buffer
; On Exit:
;    Z flag set = success
;    Z flag clear = error
; Clobbers H,L
;--------------------------------------------------------------
dWrtTrk	di

	lda	fWaitHd		;load head settle (E) flag
	ori	cWRTRK		;combine with write track command

	push	b		;save BC
	push	d		;save DE
	call	dWrSec		;do the data transfer
	pop	d		;restore
	pop	b

	xra	a		;no head settle wait after 1st write
	sta	fWaitHd

	in	FDCSTAT		;get status of the write
	ani	smWRITE		;any of these bits is an error
	ei			;re-enable interrupts
	ret

;--------------------------------------------------------------
; dWrSec - Do the physical transfer of data from memory to
;    the disk. When the disk controller completes the
;    command, it generates an NMI interrupt that returns
;    control to the caller of this subroutine.
;
;    The FDCWAIT register can't be used for data sync until
;    after the 1793 requests the 2nd byte. Therefore, a poll
;    for DRQ must be used for the 1st and 2nd byte. The 1st
;    byte is not timing critical. The 2nd byte is. In order to
;    meet 1793 timing requirements for DD data (11.5us worst
;    case) the poll loop uses a computed jump based on reading
;    the board status (select) register. When DRQ is asserted,
;    0FFh is returned, otherwise 0FCh is returned. This loop
;    must be located at xxFCh within a page.
;
;    To handle a race condition that can occur with the Rev 0
;    controller, B' is loaded with FFh (the LSB of the jump
;    address when DRQ is asserted) because the race condition
;    can cause the DRQ poll loop to jump into the middle of
;    the INP L instruction. The 2nd byte evaluates to a MOV L,B
;    instruction, and therefore, moves the LSB of the proper
;    jump address into L for subsequent PCHL jump.
;
; On Entry:
;    Write sector command issued to controller
;    HL->sector (or address mark) buffer
; On Exit:
; Clobbers All (may exit while in alternate registers)
;--------------------------------------------------------------

WRSIZE	set	dwWt2nd-dWrSec

;	org	(($+WRSIZE+100h-0FCh) AND 0FF00h) + (0FCh - RDSIZE)
	org	(($+15h+100h-0FCh) AND 0FF00h) + (0FCh - 16h)

dWrSec	out	FDCCMD		;issue passed write command
	
	mvi	c,FDCDATA	;C=port to write with data byte

dwWt1st	in	FDCSEL		;wait for 1st DRQ
	rrc
	jnc	dwWt1st

	outi			;give 1793 1st byte from HL

	mov	a,m		;A=2nd byte from buffer
	inx	h		;HL->3rd byte location
	push	psw		;push to move to A'
	exx
	pop	psw		;A'=2nd byte to send

	mvi	h,(dwWt2nd SHR 8) AND 0FFh   ;H'=msb of jump address
	lxi	b,((dWr2nd AND 0FFh) SHL 8) + FDCSEL

dwWt2nd	inp	l		;(13) L=FCh (no DRQ) or FFh (DRQ)
	pchl			;(5) jump to dwWt1st or dRd1st

dWr2nd	out	FDCDATA		;(12) give 2nd byte to 1793
	exx			;(5) back to regular registers

dWrLoop	in	FDCWAIT		;(12) wait for next byte
	outi			;(17) give next byte to 1793
	jmp	dWrLoop		;(11)

;--------------------------------------------------------------
; dChkWP - check if disk is write protected. 
; On Entry:
;    disk already selected
; On Exit:
;    returns if disk is not protected. Otherwise, an error
;    message is displayed and the program started over.
; Clobbers none
;--------------------------------------------------------------
dChkWp	in	FDCSTAT		;read 1793 status
	ani	sWRPROT		;get write protect bit alone
	rz			;return if not protected

; Disk write protected. Display error and restart program.

	lxi	h,mWrtPrt	;otherwise, display error message
	jmp	errMsg		;display error and restart

	endif

;**************************************************************************
; 
;  Data area
;
;**************************************************************************
; disk variables

drvNum	ds	1		;drive number to use
dskType	ds	1		;disk type (IBM, VG, and density)

trkNum	ds	1		;track number to read
lastSec	ds	1		;last sector accessed on track
fWaitHd	ds	1		;E bit (wait head settle) flag
curCyl	ds	1		;current cylinder
curSide	ds	1		;current side (0=bot, 1=top)
secSize	ds	1		;sector size (128 or 256)
trkCnt	ds	1		;count of tracks to send (77 or 154)

trkPtr	ds	2		;pointer into trkBuf at track boundaries
bufEnd	ds	2		;end address + 1 of last track spot in RAM

; retry logic variables

rdRtry	ds	1		;disk read retry counter
rtStep	ds	1		;current retry step
trkErr	ds	1		;non zero if error occured on track

; xmodem variables

xfrPort	ds	1		;pseudo port for file transfer
xmRetry	ds	1		;xmodem retry counter
blkNum	ds	1		;current xmodem block number
crcFlag	ds	1		;non zero if using CRC instead of checksum
crc16	ds	2		;crc-16 result
sndPtr	ds	2		;pointer for start of XMODEM send

; misc variables

cpmFlag	ds	1		;non-zero if running under CP/M
baseDrv	ds	1		;ascii 1st drive - baseDrv = 0
fillDat	ds	1		;E5 or 'n'
	ds	64		;stack space
ourStk	equ	$

; track buffer runs from here to the end of memory

	ds	PKTLEN		;space for pre-pended unsent data
trkBuf	equ	$

	end
