;*****************************************************************************
;
;  Flop2PC - Transfer floppy image to PC over a serial port
;	     for North Star Horizon Computer
;
;	This program transmits an image of a North Star double density floppy
;       to a PC over a serial port using the XMODEM protocol. The disk is
;	copied in raw format (512 bytes per sector, 10 sectors per track, 
;	35-SS or 70-DS tracks). The disk image is the linear sequence of the
;	512 byte sectors from track 0, sector 0 through track 34 (69)
;	sector 9. The leading zeros before the data payload and the checksum
;	are not transferred.
;
;	This program runs standalone at 0x100 or under CP/M.
;
;	Written by Mike Douglas
;
;	Rev	 Date	    Desc
;	1.0	10/17/15    Original
;
;*****************************************************************************

; Disk information equates

NUMTRK	equ	70		;number of tracks
NUMCYL	equ	35		;number of cylinders
NUMSEC	equ	10		;number of sectors per track
SECLEN	equ	512		;sector length (as transmitted)
MINDRV	equ	1		;first drive number
MAXDRV	equ	4		;max drive number 

TRKLEN	equ	(NUMSEC*SECLEN)	;length of track in bytes
DKTRIES	equ	5		;number of disk read retries

; North Star Disk Type Byte at offset 5C in sector zero
;    bit	80H	;0 = single density, 1 = double density
;    bit	40H	;0 = single sided,   1 = double sided
;    bit	20H	;0 = format 1,	     1 = format 2
;    bit	10H	;always set to 1
;    bit	 8H	;not assigned
;    bit	 4H	;not assigned
;    bit	 2H	;0 = 48 track/in.,   1 = 96 track/in.
;    bit	 1H	;always set to 0

DSKTYPE	equ	5ch		;disk type is at offset 5c on sector zero
DSKSIDE	equ	40h		;isolate single/double sided bit
DSKCHK	equ	10h		;isolate the always 1 bit

; Monitor, CP/M boot entry points

MONITOR	equ	0100h		;no default ROM, just restart program
CPMBOOT	set	0e800h		;cold boot ROM entry point

; 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 location

; 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

	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
	mvi	a,MINDRV	;a=default drive
	sta	drvNum		;need for pgmExit
	mvi	a,NDBLDEN	;init order register to double density
	sta	ctlOrd

;  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
	jm	getDrv		;error, entry was < first drive
	cpi	MAXDRV-MINDRV+1	;validate <= max drive
	jnc	getDrv		;invalid, prompt again
	adi	MINDRV		;restore offset of 1st drive (if any)
	sta	drvNum		;save the drive number to use

; Detect and display disk type, then display menu to ask the user
;   how he wants the disk treated

	call	dspType		;detect and display disk type
getType	lxi	h,mType		;display disk type menu
	call	dispMsg
	call	rcvCon		;get byte from the console
	ori	20h		;upper case letters to lower case
	cpi	'x'		;exit requested?
	jz	pgmExit		;yes
	mvi	b,NUMCYL	;b=single sided tracks
	sui	'1'		;0 index options
	jz	saveAct		;single sided chosen, save actual tracks
	mvi	b,NUMTRK	;b=double sided tracks
	dcr	a		;option '2' decrements to zero
	jnz	getType		;neither 1 or 2 chosen, try again

saveAct	mov	a,b		;a=actual track ount
	sta	actTrks		;actTrks=actual track count

; getPort - get serial port number 1-2 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' to 0
	cpi	2		;validate input was '1' or '2'
	jnc	getPort		;invalid, prompt again
	sta	xfrPort		;save the port to use

; 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	mvi	a,0ffh		;track position on drive not known
	sta	curCyl
	xra	a		;init track we want to zero
	sta	trkNum
	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	trkNum		;increment track number (preserve HL)
	inr	a
	sta	trkNum
	mov	b,a		;b=current track
	lda	actTrks		;a=actual number of tracks to process
	cmp	b		;done all tracks?
	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	sndTrks		;send the buffered tracks via xmodem
	lda	trkNum		;a=current track
	mov	b,a		;b=current track
	lda	actTrks		;a=number of tracks to process
	cmp	b		;all done? (had to preserve HL)
	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
	sta	rtStep		;current retry step 
	mvi	d,NUMSEC	;d=sector counter

; secLoop - Read an entire track. Start at whatever sector comes up next

secLoop	call	chkQuit		;check for ctrl-c
	call	dNxtSec		;wait for next (any) sector sync
	lhld	trkPtr		;hl->start of current track buffer
	dad	b		;bc has offset of sector within track
	call	dRead		;read the sector
	jnz	secRtry		;error, go to retry logic

; Decrement sector count. If full track is done, increment trkPtr
;   to point to the next track buffer in trkBuf

nxtSec	dcr	d		;decrement sector count
	jnz	secLoop
	lhld	trkPtr		;hl=current track pointer
	lxi	d,TRKLEN	;de=bytes in a track
	dad	d		;hl=start of next track in trkBuf
	shld	trkPtr
	ret

;--------------------------------------------------------------------------
; secRtry - read error retry logic. Six retry steps are tried in
;   the following order:
;
;   Step    Action
;    0	Re-read DKTRIES times
;    1	Seek in one track and back, then re-read DKTRIES times
;    2	Seek out to track 0 and back, then re-read DKTRIES times
;    3	Seek in one track and back, then re-read DKTRIES times
;    4	Seek out to track 0 and back, then re-read DKTRIES times
;--------------------------------------------------------------------------	
secRtry	mvi	a,DKTRIES	;init disk retry counter
	sta	dskRtry

retryLp	call	chkQuit		;check for ctrl-c
	call	dWtSec		;wait for sector specified in e
	lhld	trkPtr		;hl->start of current track buffer
	dad	b		;bc has offset of sector within track
	call	dRead		;read the sector
	jz	rtDone		;success, retries done

; read failed. Decrement retry count and try again if not zero. Once
;   retry counter expires, increment the step counter to try the
;   next retry stage.

	lxi	h,dskRtry	;decrement retry counter
	dcr	m
	jnz	retryLp		;try again

; read re-tries expired, try next retry step

	lxi	h,rtStep	;move to next retry step
	inr	m
	mov	a,m		;a=new retry step
	dcr	a		;step 1, seek past track and come back
	jz	skPast
	dcr	a		;step 2 restore to track zero
	jz	restor0
	dcr	a		;step 3, seek past track and come back
	jz	skPast
	dcr	a		;step 4 restore to track zero
	jz	restor0

; retries failed. Display the error, wait for the failed sector number
;    to come under the head again, then jump back into the main
;    read loop which will resume at the next sector.

	call	dspErr		;give up, display the error
	call	dWtSec		;wait for the failed sector number

; rtDone - retry logic is done. Reset the retry step counter and
;    jump to end of sector processing above

rtDone	xra	a		;restart retry step counter
	sta	rtStep
	jmp	nxtSec

;-----------------------------------------------------------------------------
; restor0 - retry step to restore to track zero, then seek back to
;    the current track.
;
; skPast - retry step to seek past the current track, then back to
;    the current track.
;-----------------------------------------------------------------------------
restor0	push	d		;save sector count and number
	call	dRestor		;restore to track zero
reseek	lxi	h,trkNum	;get desired track from trkNum
	mov	l,m		;and put into l
	call	dSeek		;seek back to the track
	pop	d		;restore sector in e
	jmp	secRtry		;try again

skPast	lda	trkNum		;a=current track
	cpi	NUMTRK-1	;at max track?
	jz	restor0		;yes, just try restore again
	push	d		;save sector count and number
	inr	a		;otherwise step in a track
	mov	l,a
	call	dSeek
	jmp	reseek		;then back out

;-----------------------------------------------------------------------------
; 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

;--------------------------------------------------------------------
; dspType - read sector zero of track 0 and look at the disk type
;    byte at offset 5c to see if this is a single or double sided
;    disk. Display a message to the user if type is determined.
; On Entry: drvNum must be set
;-------------------------------------------------------------------- 
dspType	call	dRestor		;restore to track zero
	mvi	d,3		;try three times
	mvi	e,0		;e=sector to read
dtSec	call	dWtSec		;wait for sector zero
	lxi	h,trkBuf	;hl->where to put sector
	call	dRead		;read the sector
	jz	dtChk		;have sector, check what type
	dcr	d
	jnz	dtSec

; dtNone - disk type couldn't be determined. 

dtNone	lxi	h,mNoType	;display "no type" message
dtDisp	call	dispMsg
	ret			

; dtChk - sector zero read, check the disk type byte
	
dtChk	lda	trkBuf+DSKTYPE	;get disk type byte from sector zero
	mov	b,a		;and save it in b
	ani	DSKCHK		;verify this bit is one
	jz	dtNone		;invalid byte, display "no type" message
	lxi	h,mSgl		;assume single sided
	mov	a,b		;a=disk type byte
	ani	DSKSIDE		;isolate disk sides bit
	jz	dispMsg		;display "single sided" message
	lxi	h,mDbl		;double sided message
;	jmp	dispMsg		;display "double sided" message (fall through)

;-----------------------------------------------------------------------------
; 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 + 59.
;     Clobbers a, b and c.
;-----------------------------------------------------------------------------
rcvByte	lxi	b,ONESEC	;bc=cycles through this loop for 1s
rcvWait	lda	xfrPort		;(13) a=port to use for transfer
	call	serIn		;(17+cycles in serIn)look for a byte
	rnz			;(5)byte received
	dcx	b		;(5)otherwise, decrement timer
	mov	a,b		;(5)one second expire?
	ora	c		;(4)
	jnz	rcvWait		;(10)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	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
;------------------------------------------------------------------
sizeRam	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,-((TRKLEN SHR 8) + 1) AND 0ffh
	cmp	d		;force de < (10000h - TRKLEN)
	jnc	topOk
	mov	d,a		;limit max address
topOk	lxi	h,trkBuf	;hl=start of track buffer
	lxi	b,TRKLEN	;bc=length of track in bytes

; Loop increasing hl by TRKLEN 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,-TRKLEN	;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

;---------------------------------------------------------------------
; Message constants
;---------------------------------------------------------------------
mWelcom	db	cr,lf,lf
	db	'===== Floppy to PC Image Transfer (Horizon), Version 1.0 ====='
	db	cr,lf,lf
	db	'This program transfers an image of a North Star double'
	db	cr,lf
	db	'density disk to a PC through a user-specified port'
	db	cr,lf
	db	'using the XMODEM protocol (checksum or CRC).',0

mDrive	db	cr,lf,lf,'Insert and specify source drive ('
mDrvMin	db	'x-'
mDrvMax	db	'x) or X to exit: ',0

mNoType	db	cr,lf,lf,'** Disk type could not be determined **',0
mSgl	db	cr,lf,lf,'** Single sided disk detected **',0
mDbl	db	cr,lf,lf,'** Double sided disk detected **',0

mType	db	cr,lf,lf
	db	'Transfer a single or double sided disk?',cr,lf
	db	'  1) Single Sided',cr,lf
	db	'  2) Double Sided',cr,lf
	db	'Choose 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) Console serial port',cr,lf
	db	'  2) Second serial port',cr,lf
	db	'Enter port or X to exit: ',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

mStkTk0	db	cr,lf,lf,'Drive stuck on track 0',cr,lf,0

mNotRdy	db	cr,lf,lf,'Drive not ready',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.
;
;****************************************************************************

; 8251 UART Equates

SIOACR	equ	03h		;console port - control register
SIOADR	equ	02h		;console port - data register
SIOBCR	equ	05h		;2nd port - control register
SIOBDR	equ	04h		;2nd port - data register
SIORDA	equ	02h		;read data available flag
SIOTRE	equ	01h		;transmit register empty flag

; 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 + 59 cycles for the rcvByte code. 

ONESEC	equ	39604		;rcvByte loop count for 1 second (4mhz)

;----------------------------------------------------------------------------
; conIn - input character from console
;    inputs:
;    outputs: z true if no character present
;	      z false if character returned in a
;    clobbers none
;----------------------------------------------------------------------------
conIn	in	SIOACR		;see if a new character is present
	ani	SIORDA
	rz			;no character, return zero status
	in	SIOADR		;return character and non-zero status
	ret	

;----------------------------------------------------------------------------
; conOut - output character to console
;    inputs: b = character to send
;    clobbers a
;----------------------------------------------------------------------------
conOut	in	SIOACR		;wait for OK to transmit
	ani	SIOTRE
	jz	conOut
	mov	a,b		;a=character to transmit
	out	SIOADR		;send it
	ret

;----------------------------------------------------------------------------
; Hardware specific I/O
; serIn - input character from port specified in a
;       0 = console serial port
;       1 = second serial port
;    inputs: a = port to read from
;    outputs: z true if no character present
;	      z false if character returned in a
;    clobbers none
; 42 cycles including return when no character present
;-----------------------------------------------------------------------------
serIn	ora	a		;(4) port 0 or 1?
	jnz	s2InB		;(10) port 1, 2nd serial port

; Input from console serial port

s2InA	in	SIOACR		;(10+1) see if a new character is present
	ani	SIORDA		;(7)
	rz			;(10) no character, return zero status
	in	SIOADR		;return character and non-zero status
	ret	
	
; Input from 2nd serial port

s2InB	in	SIOBCR		;(10+1) see if a new character is present
	ani	SIORDA		;(7)
	rz			;(10) no character, return zero status
	in	SIOBDR		;return character and non-zero status
	ret		

;-----------------------------------------------------------------------------
; Hardware specific I/O
; serOut - output character to port specified in a
;       0 = console serial port
;       1 = second serial port
;    inputs: a = port to transmit through
;	     b = character to send
;    clobbers a
;-----------------------------------------------------------------------------
serOut	ora	a		;port 0 or 1 ?
	jnz	s2OutB		;second serial port

; Send character through console serial port

S2OutA	in	SIOACR		;wait for OK to transmit
	ani	SIOTRE
	jz	S2OutA
	mov	a,b		;a=character to transmit
	out	SIOADR		;send it
	ret

; Send character through second serial port

s2OutB	in	SIOBCR		;wait for OK to transmit
	ani	SIOTRE
	jz	s2OutB
	mov	a,b		;a=character to transmit
	out	SIOBDR		;send it
	ret


;****************************************************************************
;
; North Star disk I/O routines.
;   Based on code for the single density controller written by 
;   M Eberhard. Modified for this program and for the DD controller
;   by M Douglas.
;
; Commands are issued to the North Star controller by reading memory
; locations. Data and Control bits to the controller are embedded
; in the read addresses. What you get back depends on what you
; read - either one of 3 status bytes, or disk data. The commands
; constructed below take care of this.
;
; 3 RAM locations are needed:
;    curCyl is used to remember the current cylinder
;           and should be initialized to 0FFh
;    drvNum remembers the current unit. On the N* controller,
;           disks are 1 to 4. 0 means none selected.
;    ctlOrd is a saved copy of the controller order byte

;************************************************
; North Star disk Controller Addresses & Commands
; (Read or write from address to execute command)
;************************************************
NSCTRL	equ	0E800h		;North Star disk controller
NSBOOT	equ	NSCTRL		;disk boot PROM entry point
NWRITE	equ	NSCTRL+100h	;write prefix (data in low byte)
NORDER	equ	NSCTRL+200h	;controller order base address
NCOMND	equ	NSCTRL+300h	;commands base address

NASTAT	equ	NCOMND+10h	;read A status
NBSTAT	equ	NCOMND+20h	;read B status
NCSTAT	equ	NCOMND+30h	;read C status
NMOTRA	equ	NCOMND+15h	;motor on, read A status
NRBYTE	equ	NCOMND+40h	;read a byte of disk data
NWRCRD	equ	NCOMND+16h	;start write-sector sequence
NRSEFL	equ	NCOMND+11h	;reset sector flag, read A status


;****************************
; Controller Order Register Bits
;****************************
NDBLDEN	equ	080h		;select double density mode

NTOPSID	equ	040h		;select top side of DS disk

NSTPIN	equ	020h		;step in

NPREON	equ	020h		;write pre-comp on
NPREOFF	equ	0dfh		;write pre-comp off
NPRETRK	equ	21		;precomp on starting with this track

NSTEPH	equ	010h		;assert step line
NSTEPL	equ	0efh		;de-assert step line


;****************************
; Status Register Bits
;****************************
; Status Register A

NSBDY	equ	1		;body (sync chr found)
NSRE	equ	4		;read enable (PLL locked)
NSWIND	equ	8		;in 96us pre-sector window

; Status Register B

NSTR0	equ	1		;track 0
NSWP	equ	2		;write protect

; Status Register C (sector position

NSSP	equ	0Fh		;sector position

; All status registers

NSMO	equ	10h		;motor on flag
NSDD	equ	20h		;double density flag
NSWN	equ	40h		;window flag
NSSF	equ	80h		;Nsector flag

;**************************
; Disk Controller constants
;**************************
SYNC	equ	0FBh		;header sync charactor
WRMUP	equ	32h		;warm up time in sectors
SETL	equ	0Dh		;head settling time in sectors
SWAIT	equ	08Ch		;max wait for body before error
MAXUNT	equ	3		;max disk drive unit (0 not allowed)
MAXTRK	equ	39		;max track
MAXSEC	equ	9		;max sector (SA400 and SA400L)

;**************************
;Disk Subsystem Subroutines
;**************************

;***Subroutine**************************************
; dRead - Read sector on current track.
; On Entry:
;    Drive is selected, motor is running and sector
;        sync was just previously detected
;    hl->sector buffer
; On Exit:
;    clobbers b,c,h,l
;***************************************************
dRead:	mvi	b,SWAIT		;max time until body

;wait for RE bit (PLL lock) 

NSRD1:	dcr	b
	jz	NOSYNC		;timeout, sync not found
	lda	NASTAT		;look for RE, PLL lock flag
	ani	NSRE
	jz	NSRD1		

;wait for body bit (sync character found)

NSRD2:	dcr	b
	jz	NOSYNC		;timeout, sync not found
	lda	NASTAT		;look for "body" flag in stat A
	rrc			;test for NSBDY bit
	jnc	NSRD2

	lxi	b,0		;init CRC (b), byte count (c)

;read sector data two bytes at a time (512 bytes total)

NSRD3:	lda	NRBYTE		;read a byte
	mov	m,a		;save it
	xra	b		;compute checksum
	rlc
	mov	b,a
	inx	h		;bump pointer

	lda	NRBYTE		;read a byte
	mov	m,a		;save it
	xra	b		;compute checksum
	rlc
	mov	b,a
	inx	h		;bump pointer

	dcr	c		;256*2 byteS
	jnz	NSRD3

;check CRC

	lda	NRBYTE		;get disk CRC
	xra	b		;compare to computed CRC
	ret			;Z flag set if OK, else error

NOSYNC:	dcr	b		;b=0ffh
	ret			;return with zero false

	if	0		;not used in FLOP2PC
;***Subroutine**************************************
; dVerify - Verify sector on current track
; On Entry:
;    Drive is selected, motor is running and sector
;        sync was just previously detected
;    hl->buffer to compare against
; On Exit:
;    clobbers b,c,h,l
;***************************************************
dVerify: mvi	b,SWAIT		;max time until body

;wait for RE bit (PLL lock) 

NSVF1:	dcr	b
	jz	NOSYNC		;timeout, sync not found
	lda	NASTAT		;look for RE, PLL lock flag
	ani	NSRE
	jz	NSVF1

;wait for body bit (sync character found)

NSVF2:	dcr	b
	jz	NOSYNC		;timeout, sync not found
	lda	NASTAT		;look for "body" flag in stat A
	rrc			;test for NSBDY bit
	jnc	NSVF2

	lxi	b,0		;init CRC (b), byte count (c)

;read and verify sector data two bytes at a time (512 bytes)

NSVF3:	lda	NRBYTE		;read a byte
	cmp	m		;compare to validate data
	rnz			;match fail
	xra	b		;compute checksum
	rlc
	mov	b,a
	inx	h		;bump pointer

	lda	NRBYTE		;read a byte
	cmp	m		;compare to validate data
	rnz			;match fail
	xra	b		;compute checksum
	rlc
	mov	b,a
	inx	h		;bump pointer

	dcr	c		;256*2 bytes
	jnz	NSVF3

;check CRC

	lda	NRBYTE		;get disk CRC
	xra	b		;compare to computed CRC
	ret			;Z flag set if OK, else error

;***Subroutine**************************************
; dWrite - Write a sector on current track
; On Entry:
;    Drive is selected, motor is running and sector
;        sync was just previously detected
;    hl->buffer address
; On Exit:
;   clobbers b,c,h,l
;***************************************************
dWrite:	push	d		;save de 
	lda	NWRCRD		;issue write command to controller

NSWR1:	lda	NASTAT		;wait for pre-sector window to pass
	ani	NSWIND
	jnz	NSWR1

;write sector header

	lxi	b,NWRITE	;bc = write command, data zero
	lxi	d,001FH		;number of header zeros (31)
				;init CRC calculation (d)

NSWR2:	ldax	b		;write a zero
	mov	a,a		;kill some time
	mov	a,a		;kill some time
	dcr	e		;count header zeros
	jnz	NSWR2

;write two sector sync characters

	mvi	c,SYNC		;write sync chr
	ldax	b
	mov	a,a		;kill some time
	mov	a,a		;kill some time
	mvi	c,SYNC		;kill some time
	ldax	b

;write  sector data 2 bytes at a time (512 bytes)

NSWR3:	mov	c,m		;get chr from RAM
	mov	a,c		;Calculate CRC
	xra	d		;keep it in d
	rlc
	mov	d,a
	ldax	b		;write chr to disk
	inx	h		;bump pointer

	mov	c,m		;get chr from RAM
	mov	a,c		;Calculate CRC
	xra	d		;keep it in d
	rlc
	mov	d,a
	ldax	b		;write chr to disk
	inx	h		;bump pointer

	dcr	e		;write 256*2 bytes
	jnz	NSWR3

;write sector CRC

	mov	c,d		;Write CRC
	ldax	b
	
	pop	d		;restore de
	ret			;don't wait for end of sector

;***Subroutine**************************************
; 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 h,l
;***************************************************
dChkWP	lda	NBSTAT		;check for write protect
	ani	NSWP
	rz			;return if not protected

; Disk write protected. Display error and restart program.

	lxi	h,mWrtPrt	;otherwise, display error message
	call	dispMsg		;display the error
	lxi	sp,ourStk	;re-init stack point
	jmp	getDrv
	endif

;***Subroutine**************************************
; dSeek - Seek Track. The motor timeout is restarted 
;    as a result of this call. After the seek, a controller
;    order is issued to turn on/off write precomp and
;    to select the bottom/top head.
; On Entry:
;    curCyl = current cylinder FFh means we don't know
;    l = desired track
; On Exit:
;    curCyl = current cylinder
; trashes all registers
;***************************************************
dSeek:	call	NSELCT		;select drive, spin up
	
;determine cylinder number from the track number and set the
;  side bit properly in a copy of the controller order register.

	lda	ctlOrd		;put the order register with bottom
	mov	c,a		;   selected into c
	mvi	a,NUMCYL-1	;a=maximum cylinder number
	sub	l		;a=max cylinder - requested track
	jp	NSSEEK		;tracks 0-34 are on bottom, go do seek

;track is on the top side. Tracks 35 to 69 correspond to
;  cylinders 34 down to 0.

	adi	NUMCYL		;a=(2*NUMCYL-1)-track
	mov	l,a		;update l with actual cylinder number
	mov	a,c		;set top side bit in order register
	ori	NTOPSID
	mov	c,a		;c=order register with top side set

;compute the required number of steps and the direction

NSSEEK:	push	b		;save c with the controller order

	lda	curCyl		;where are we?
	cpi	0ffh
	cz	dRestor		;lost: restore

	sub	l		;a= +/- steps required
	jz	NSSKPC		;already there, go do precomp

	mvi	b,0		;b=step direction, assume out for now
	jp	NSSKO		;current>desired, seek out

	mvi	b,NSTPIN	;desired<current, seek in
	cma			;compute a=-a
	inr	a

;put number of steps in h, set step direction in e, save target cylinder
;   in curCyl, then do the steps.

NSSKO:	mov	h,a		;h=number of steps
	mov	a,l		;save what will be the new cylinder
	sta	curCyl
	lda	ctlOrd		;form order register with step direction
	ora	b		;  in e
	mov	e,a		;
	call	NSSTEP		;step h tracks in or out

;update the order register with the precomp bit and the side select
;  bit and issue the order to the controller. This is the last
;  order issued before reads and writes take place.

NSSKPC:	pop	b		;c=order register with side select
	lda	curCyl		;a=current cylinder number
	cpi	NPRETRK		;at or above precomp track #?
	jm	NSSKNP		;no precomp needed
	mov	a,c		;a=current controller order
	ori	NPREON		;turn on precomp bit
	mov	c,a		;c=final order register value
NSSKNP:	mvi	b,NORDER/256	;b=msb of order command address
	ldax	b		;set side and precomp
	ret


;***Subroutine*************************
; dRestor - Restore to track 0
; On Exit:
;   Z set and curCyl=0 if track 0 found
; trashes psw,bc,e,h
;**************************************
dRestor: call	NSELCT		;select drive, spin up

;step in once, in case the head is lost

	lda	ctlOrd		;a=current order register
	ori	NSTPIN		;assert step in
	mov	e,a		;e=step in order
	mvi	h,1
	call	NSSTEP		;step in now
	jz	STUCK0		;z: Stuck on track 0

;step out enough times that we should find track 0 even
;if the SA400's actuator is out of its spiral groove

	mvi	h,MAXTRK+16	;more than enough
	lda	ctlOrd		;a=saved order register
	mov	e,a		;e=step out (always saved that way)
	call	NSSTEP		;steppin' out to track 0
	rz			;z set: found track 0

;Error: track 0 not detected despite many steps outward

	lxi	h,mNoTrk0
	call	dispMsg
	lxi	sp,ourStk	;initialize stack pointer
	jmp	getDrv		;start over asking for drive num

;Error: stuck on track zero

STUCK0:	lxi	h,mStkTk0	;stuck on track zero message
	call	dispMsg
	lxi	sp,ourStk	;initialize stack pointer
	jmp	getDrv		;start over asking for drive num

;***Subroutine*************************
; Step head
; On Entry:
;   h = number of steps, >0
;   e = step order (in or out)
; On Exit:
;   Z set and curCyl=0 if track 0 found
; trashes psw,bc,d,h
;**************************************
NSSTEP:	mvi	d,NORDER/256	;d=msb of order command address
	ldax	d		;set step direction

NSSTP1:	mov	a,e		;a=order command
	ori	NSTEPH		;set step line high
	mov	e,a
	ldax	d		;issue step

	mov	a,e		;a=order command
	ani	NSTEPL		;set step line back low
	mov	e,a
	ldax	d		;finish step

	mvi	b,2		;step timer
	call	NSWAIT		;wait 2 sector times

	lda	NBSTAT		;at track 0?
	ani	NSTR0
	jnz	NSSTP2		;yes, stop stepping

	dcr	h		;no, step again
	jnz	NSSTP1		;stepped enough?

	inr	a		;clear Z: not track 0
	ret

;on track 0. clear curCyl, and return with Z set

NSSTP2:	xra	a		;set Z: track 0
	sta	curCyl
	ret

;***Subroutine********************************
; NSELCT - Select drive. Turn on the motor if necessary,
;    wait for head settle time.
; On Entry:
;   drvNum = desired drive (1-4)
; trashes psw,bc
;*********************************************
NSELCT: mvi	b,WRMUP-SETL	;warmup motor time

;long delay if motors are off

	lda	NASTAT		;get current motor status
	ani	NSMO		;already on?
	lda	NMOTRA		;turn on drive motors
	cz	NSWAIT		;no, spin up

;encode drive  number as a bit position and store in the
;  memory image of the controller order register

	lda	drvNum
	cpi	3
	jc	drvSet		;1->1, 2->2
	rlc			;3->6, 4->8
	ani	0ch		;3->4, 8->8

;form and save controller order register with drive bit

drvSet:	mov	b,a		;b=encoded drive value
	lda	ctlOrd		;a=current order register
	ani	0f0h		;clear out drive bits
	ora	b		;a=order register with drive bits
	sta	ctlOrd		;save in ctlOrd
	mvi	b,NORDER/256	;b=msb of order command address
	mov	c,a		;c=order register to write
	ldax	b		;select drive

;wait for settling time after head load

	mvi	b,SETL		;head settling time

;fall into NSWAIT to stall

;***Subroutine***********************
; Wait for b sectors
; On Entry:
;   b = number of sectors to wait for
; trashes psw,b
;************************************
NSWAIT:	lda	NRSEFL		;reset sector flag
	lda	NMOTRA		;restart motor timeout	

NSWAT1:	lda	NASTAT		;get status a
	rlc			;test NSSF, sector flag set?
	jnc	NSWAT1		;no

	dcr	b		;wait for b sectors to pass
	rz

	jmp	NSWAIT

;***Subroutine******************************
; dWtSec - Wait for specified sector.
; On Entry:
;    Drive is selected, motor is running
;    e = desired sector number
; On Exit:
;    drive is at proper sector
;    e = sector number
;    bc = byte offset of this sector in a track
;*******************************************
dWtSec: lda	NRSEFL		;reset sector flag
NSWTS1:	lda	NMOTRA		;restart motor timeout	
NSWTS2:	lda	NCSTAT		;a=sector flag and sector number
	rlc			;test NSSF, sector flag set?
	jnc	NSWTS2

; Sector flag set, get sector number alone and see if this
;   is the right sector

	lda	NRSEFL		;reset sector flag (required)
	lda	NCSTAT		;get sector again to be safe
	ani	NSSP		;get sector bits alone
	cmp	e		;the sector we want?
	jnz	NSWTS1		;no, keep looking

; Compute the offset of this sector within the track and return in bc

	rlc			;512 bytes per sector
	mov	b,a
	mvi	c,0
	ret 

;***Subroutine******************************
; dNxtSec - Wait for next (any) sector
; On Entry:
;    Drive is selected, motor is running
; On Exit:
;    drive is at proper sector
;    e = sector number
;    bc = byte offset of this sector in a track
;*******************************************
dNxtSec: lda	NRSEFL		;reset sector flag
	lda	NMOTRA		;restart motor timeout	
NSWTS3:	lda	NCSTAT		;a=sector flag and sector number
	rlc			;test NSSF, sector flag set?
	jnc	NSWTS3

; Sector flag set, return the sector number in e and compute the offset
;    of this sector within the track.
	
	lda	NRSEFL		;reset sector flag (required)
	lda	NCSTAT		;get sector again to be safe
	ani	NSSP		;get sector bits alone
	mov	e,a		;return sector in e
	rlc			;512 bytes per sector
	mov	b,a
	mvi	c,0
	ret 			

;**************************************************************************
; 
;  Data area
;
;**************************************************************************
; disk variables

drvNum	ds	1		;drive number to use
curCyl	ds	1		;current track number drive is on
ctlOrd	ds	1		;current "controller orders" byte
actTrks	ds	1		;actual number of tracks on disk
trkNum	ds	1		;track number to read
trkPtr	ds	2		;pointer into trkBuf at track boundaries
bufEnd	ds	2		;end address + 1 of last track spot in RAM

; retry logic variables

dskRtry	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
	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
