;******************************************************************************
;
;  PC2Flop - Transfer disk image from PC to floppy over serial port.
;		(Altair FDC+ with IMSAI SIO-2 serial port)
;
;	This program writes an Altair 330K floppy disk with a disk image
;	transmitted from a PC. The image is transmitted through an IMSAI
;	SIO-2 serial port using the XMODEM protocol. The image is written
;	directly to the floppy in raw format (137 bytes per sector, 32
;	sectors per track, 77 tracks).
;
;	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.
;
;	This program runs standalone at 0x100 or under CP/M. The program
;	is exited with a CTRL-C and either warm boots CP/M or just starts
;       over when running stand alone.
;
;	Written by Mike Douglas
;
;	Rev	 Date	    Desc
;	1.0	 03/29/21   Original
;
;  	1.1	 04/05/21   Move SIO-2 port base to 10h instead of 00h to
;			    avoid conflict with the Altair FDC.
;
;*****************************************************************************

; Disk information equates

NUMTRK	equ	77		;number of tracks
NUMSEC	equ	32		;number of sectors per track
SECLEN	equ	137		;sector length (as transmitted)
MINDRV	equ	0		;first drive number
MAXDRV	equ	3		;max drive number 
CPUSPED	equ	2000		;CPU speed in khz for delayMs

TRKLEN	equ	(NUMSEC*SECLEN)	;length of track in bytes
RDTRIES	equ	5		;number of read (verify) attempts
WRTRIES	equ	4		;number of write attempts

; Monitor, CP/M boot entry points

MONITOR	set	init		;no monitor, just start over
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

; CP/M Equates

WBOOT	equ	0		;warm boot jump location
BDOS	equ	5		;BDOS 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	
;-----------------------------------------------------------------------------
;  Initialize for transfer
;-----------------------------------------------------------------------------
init	di			;disable interrupts
	lxi	sp,ourStk	;initialize stack pointer
	call	chkCpm		;set flag for CP/M or not
	call	sizeRam		;determine amount of RAM available
	call	serInit		;initialize the SIO-2 ports
	mvi	a,MINDRV	;a=default drive
	sta	drvNum		;need for pgmExit
	mvi	a,0ffh		;init disk driver selected disk
	sta	curDrv		;  to "none"

;  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	call	dDeslct		;deselect a possibly active drive
	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

; Verify drive is not write protected

	call	dRestor		;restore to track 0 (selects drive)
	call	dChkWP		;check write protect (aborts to getDrv)

; getPort - get pseudo port number 0-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'		;un-ascii
	cpi	2		;validate ascii 1-2
	jnc	getPort		;invalid, prompt again
	sta	xfrPort		;save the pseudo port to use

; Prompt the user to insert the disk to write, initialize, then start
;   sending NAK to start the XMODEM reception.

	lxi	h,mStart	;display start file transfer prompt
	call	dispMsg
	mvi	a,0ffh		;init disk driver track number
	sta	curTrk		;to "invalid"
	xra	a		;init track we're reading to zero
	sta	trkNum
	inr	a		;init xmodem block number to one
	sta	blkNum
	lxi	h,trkBuf	;trkBuf is initial starting point for
	shld	rcvPtr		;   XMODEM receive
	mvi	a,NAK		;send starting nak after purging input data
	call	purgSio

;-----------------------------------------------------------------------------
;  mainLp - Receive as many packets as will fit into RAM and then write
;      tracks to disk. Repeat until entire disk is written. 
;-----------------------------------------------------------------------------
mainLp	call	bufPkts		;buffer as many packets as possible
	xchg			;de=start of last packet received
	lxi	h,trkBuf	;hl=start of track buffer
	shld	trkPtr		;writing will start from here
	call	cmpDeHl		;compare last packet start - trkBuf
	jc	allDone		;nothing received but an EOT

; trkLoop - write tracks until all disk tracks have been written or all
;    the tracks in the buffer have been written.
	
	call	dLoad		;load drive head
trkLoop	call	wrtTrk		;write a track (hl returns->next track)
	lda	trkNum		;increment track number (preserve HL)
	inr	a
	sta	trkNum	
	cpi	NUMTRK		;done all tracks?
	jz	allDone		;yes
	xchg			;de=next track pointer
	lhld	rcvPtr		;hl=start of last packet received
	call	cmpHlDe		;compare rcvPtr-start of next track
	jnc	trkLoop		;another track is present
	call	dUnload		;unload the head

; All the buffered tracks have been written. Move any bytes left over
;    from the xmodem receive to the start of trkbuf. Adjust rcvPtr
;    to the end of that data which is where reception of the next
;    packet will begin.

	call	subHlDe		;hl=hl-de = left over byte count - PKTLEN
	mov	a,l		;a=left over count - PKTLEN
	adi	PKTLEN		;a=left over byte count
	mov	b,a		;b=left over byte count (bytes to move)
	lxi	h,trkBuf	;hl->start of trkBuf
	jz	mvDone		;no bytes to move, we're done
	
; Copy the leftover data to the start of trkBuf. The next XMODEM receive
;   sequence will start at the end of this copied data instead of at the
;   start of trkBuf.

moveLp	ldax	d		;move from end of trkBuf to start of trkBuf
	mov	m,a
	inx	h		;hl->starting bytes of trackbuf
	inx	d		;de->unwritten bytes from end of trkBuf		
	dcr	b
	jnz	moveLp

mvDone	shld	rcvPtr		;save address where to receive next packet
	mvi	a,ACK		;ACK the last packet or EOT
	call	sndByte
	jmp	mainLp		;go receive more packets

; allDone - The disk is completely written. ACK the final packet (or EOT),
;     display the "transfer complete" message and start the program over.

allDone	call	dUnload		;unload the head
	mvi	a,ACK		;ACK the final packet or EOT
	call	sndByte

	mvi	l,0		;seek to track 0 (don't use dRestor)
	call	dSeek

	lxi	h,mDone		;hl->done message
	call	dispMsg
	jmp	getDrv		;start over asking for drive num

;-----------------------------------------------------------------------------
; bufPkts - Receive XMODEM packets until we fill all the track buffer
;   space available. Reception starts at the address pointed to by
;   rcvPtr. Reception is stopped when the last packet exactly
;   fills or "crosses" the end of the last track spot in RAM. rcvPtr is
;   updated on exit to point to the start of the last packet received.
;   The disk write routines use this pointer to know where data ends and
;   then update rcvPtr to start to where to begin receiving new packets.
;-----------------------------------------------------------------------------
bufPkts	call	rcvPkt		;receive a packet
	xchg			;de=current xmodem receive pointer
	cpi	EOT		;EOT received?
	jz	bufDone		;yes, buffering is done
	lhld	bufEnd		;hl=end of buffering space
	call	cmpDeHl		;compare current-end	
	jnc	bufDone		;past or at end, buffering is done
	mvi	a,ACK		;otherwise, ACK the packet
	call	sndByte
	xchg			;put xmodem rcv pointer back in HL
	jmp	bufPkts		;buffer some more

; bufDone - no more room for packets. Update rcvPtr to point to the 
;   start of the last packet received so the disk write routines know
;   where data ends.

bufDone	xchg			;hl=current xmodem receive pointer
	lxi	d,-PKTLEN
	dad	d		;hl=hl-PKTLEN = start of last rcv'd packet
	shld	rcvPtr		;save use by write tracks
	ret

;-----------------------------------------------------------------------------
; rcvPkt - receive an xmodem format 128 byte packet. HL points to the 128 byte
;    buffer to receive. HL is updated by 128 bytes after each succuessful
;    reception of a new 128 byte packet.
;-----------------------------------------------------------------------------
nakPkt	pop	h		;get HL back
	mvi	a,NAK
	call	purgSio		;purge receive for 1s then transmit NAK

;wait for SOH or EOT

rcvPkt	push	h		;save HL for retries
waitSoh	call	chkQuit		;check for user abort
	mvi	a,3		;3 second timeout for soh
	call	rcvByte		;receive character with timeout
	jz	nakPkt		;timeout
	cpi	SOH		;SOH received?
	jz	haveSoh
	cpi	EOT		;EOT to say we're done?
	jnz	waitSoh		;no, keep looking for SOH
	pop	h		;undo the entry push
	ret			;return with EOT

;  Have SOH, receive block number and not block number

haveSoh	mvi	a,1		;one second timeout once inside a packet
	call	rcvByte		;get the block number
	jz	nakPkt		;timeout, NAK and start over
	sta	rcvBlk		;save the received block number
	mvi	a,1		;one second timeout
	call	rcvByte		;get not block number
	jz	nakPkt		;timeout, NAK and start over
	sta	rcvNBlk		;save not block number

;  Receive the 128 byte block

	mvi	e,0		;init checksum
	mvi	d,pktLen	;d is byte counter
pktLoop	mvi	a,1		;one second timeout
	call	rcvByte		;get next data byte
	jz	nakPkt		;timeout
	mov	m,a		;store the character
	inx	h		;point to next byte
	add	e		;update the checksum
	mov	e,a
	dcr	d		;decrement bytes remaining
	jnz	pktLoop

;  Verify the checksum

	mvi	a,1		;one second timeout
	call	rcvByte		;get the checksum
	jz	nakPkt		;timeout
	cmp	e		;checksum match?
	jnz	nakPkt		;no, packet error

;  Checksum good. Verify block numbers

	lda	rcvNBlk		;verify rcvBlk = not (rcvNBlk)
	cma			;A should = block number now
	mov	b,a		;save in b
	lda	rcvBlk
	cmp	b		;compare rcvBlk = not(rcvNBlk)?
	jnz	nakPkt		;no, error
	lda	blkNum		;compare rcvBlk = expected blkNum
	cmp	b
	jnz	nakPkt		;nak if not the same (also nak's re-send)
	inr	a		;increment expected block number
	sta	blkNum
	pop	b		;get HL off stack, but don't clobber HL
	xra	a		;return a zero
	ret

;-----------------------------------------------------------------------------
; wrtTrk - write and verify NUMSEC sectors to the current track in trkBuf
;   as pointed to by trkPtr. After the track is written, trkPtr is updated
;   by the length of a track to point to the next track buffer. This
;   saved value is also returned in HL.
;-----------------------------------------------------------------------------
wrtTrk	lxi	h,trkNum	;get desired track from trkNum	
	mov	l,m		;and put into l
	call	dSeek		;seek to the track
	call	dChkWP		;check write protect
	mvi	a,WRTRIES	;init write retry counter
	sta	wrRetry

; rtryWrt - write a track entry and retry entry point. First, form the
;    write command and save in wrtCmd. This is used by dNxtSec to issue
;    the command as soon as possible after start of sector.

rtryWrt	lda	trkNum		;a = track number
	adi	(-43 and 0ffh)	;add -43 (1st track for HCS bit = 1)
	mvi	a,0		;set a = 0 without affecting carry
	rar			;080h if track >= 43
	stc
	rar			;0c0 if track >= 43, else 080h
	sta	wrtCmd		;wrtCmd = write command for the controller
	mvi	d,NUMSEC	;d=count of sectors to write
	
; wrtLoop - write a full track starting with any sector.

wrtLoop	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	dWrite		;write the sector
	dcr	d		;decrement sector count
	jnz	wrtLoop		;loop until all sectors written

; Verify the track just written

	xra	a		;turn off write command
	sta	wrtCmd
	call	dNxtSec		;force a 1 sector delay for trim erase
	mvi	d,NUMSEC	;d=count of sectors to verify

vfyLoop	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	dVerify		;verify the sector
	jnz	vfyRtry		;error, go to retry logic
vfyNext	dcr	d		;decrement sector count
	jnz	vfyLoop		;loop until all sectors verified

; Track verified, increment trkPtr to memory location for next track
;    and exit.

	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

; vfyRtry - verify failed, retry reads followed by a re-write
;   of the track in needed.

vfyRtry	mvi	a,RDTRIES	;init retry counter
	sta	rdRetry
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	dVerify		;verify the sector
	jz	vfyNext		;success, go verify next sector

; Re-verify failed. Decrement retry count and try again if not zero. Once
;   retry counter expires, do another write.

	lxi	h,rdRetry	;decrement the read retry counter
	dcr	m
	jnz	retryLp		;try again

; read re-tries expired, decrement the write retry count and re-write
;    if not expired

	lxi	h,wrRetry	;decrement the write retry counter
	dcr	m
	jnz	rtryWrt		;retry starting with the write
				;fall through to disk fail 
;-----------------------------------------------------------------------------
; Disk write failure. Display the track and sector with the error. Restart
;    the program.
;-----------------------------------------------------------------------------
	call	dUnload		;unload drive head

	lxi	h,errTrk	;hl->where to put ascii decimal
	lda	trkNum		;a=track with error on it
	call	bin2dec		;track to ascii

	lxi	h,errSec	;hl->where to put ascii sector
	mov	a,e		;a=sector where error occured
	call	bin2dec

	lxi	h,mDskErr	;display the error message
	call	dispMsg
	lxi	sp,ourStk	;initialize stack pointer
	jmp	getDrv		;start over asking for drive num

;-----------------------------------------------------------------------------
; 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

;-----------------------------------------------------------------------------
; purgSio - Wait for 1 second of idle time on receive line, then transmit the
;	character passed in A (usually ACK or NAK). Clobbers b
;-----------------------------------------------------------------------------
purgSio	push	a
purge	mvi	a,1		;1 second timeout
	call	rcvByte		;wait for 1 second without activity
	jnz	purge
	pop	a		;get back the character to send
				;fall through to sndByte
;-----------------------------------------------------------------------------
; sndByte - send the byte in a through the specified transfer port. 
;     Clobbers b. (assuming serOut clobbers only a).
;-----------------------------------------------------------------------------
sndByte	mov	b,a		;b=byte to transmit
	lda	xfrPort		;a=port to use for transfer
	jmp	serOut		;send the character

;-----------------------------------------------------------------------------
; rcvByte - Receive a byte from the specified transfer port. A wait timeout
;     in seconds is specified in a. 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 the 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	push	d		;save d, e
	mov	d,a		;save timeout in d

initSec	lxi	b,ONESEC	;one second timeout 104 cycles per loop
rcvWait	lda	xfrPort		;(13) a=port to use for transfer
	call	serIn		;(17+45) look for a byte
	jnz	haveChr		;(10) byte received
	dcx	b		;(5) otherwise, decrement timer
	mov	a,b		;(5) one second expire?
	ora	c		;(4)
	jnz	rcvWait		;(10) no, keep waiting

; one second timeout has occured. Decrement the seconds counter.

	dcr	d		;decrement seconds counter
	jnz	initSec		;initialize for another 1 second count
haveChr	pop	d		;restore d, e
	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
;------------------------------------------------------------------
; If running under CP/M, use the BDOS pointer to determine the top
;    of available RAM. Otherwise, size RAM manually.

sizeRam	lhld	BDOS+1		;hl=BDOS entry address
	mvi	l,0		;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

	dcr	h		;force end to FF00 instead of 0000

; ramEnd - end of RAM found. Subtract 256 bytes from this to make room
;   for xmodem packet overflow at the end. 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	dcr	d		;subtract 256 bytes from end of RAM
	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

;--------------------------------------------------------------------
; subHlDe - HL=HL-DE
;--------------------------------------------------------------------
subHlDe	mov	a,l		;subtract HL-DE, do lsbs first
	sub	e
	mov	l,a		;lsb result in l
	mov	a,h		;do msbs
	sbb	d
	mov	h,a		;msb result in h	
	ret

;-----------------------------------------------------------------------------
;   Data Area
;-----------------------------------------------------------------------------
mWelcom	db	cr,lf,lf
	db	'===== PC to Floppy Image Transfer (IMSAI SIO-2) v1.1 ====='
	db	cr,lf,lf
	db	'Writes an Altair 8" floppy with a disk image received via'
	db	cr,lf
	db	'an IMSAI SIO-2 serial port, using the XMODEM protocol.',0

mDrive	db	cr,lf,lf,'Insert and specify destination drive ('
mDrvMin	db	'x-'
mDrvMax	db	'x) 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 (12h/13h)',cr,lf
	db	'  2) Secondary serial port (14h/15h)',cr,lf
	db	'Enter port or X to exit: ',0

mStart	db	cr,lf,lf
	db	'Start XMODEM send now...',0

mDone	db	cr,lf,lf,'Creation of new disk successful!',cr,lf,0

mNoTrk0	db	cr,lf,lf,'Seek to track 0 failed',cr,lf,0

mDskErr	db	cr,lf,lf,'Write failure on track '
errTrk	db	'xx, sector '
errSec	db	'xx. Disk creation aborted.',cr,lf,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	13h		;console port - control register
SIOADR	equ	12h		;console port - data register
SIOBCR	equ	15h		;2nd port - control register
SIOBDR	equ	14h		;2nd port - data register
SIORDA	equ	02h		;read data available flag
SIOTRE	equ	01h		;transmit register empty flag
SIOCTL	equ	18h		;interrupt control register

; 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	19802		;rcvByte loop count for 1 second (2mhz)

;-----------------------------------------------------------------------
; serInit - Initialize 8251 serial ports on the SIO-2
;-----------------------------------------------------------------------
serInit	xra	a
	out	SIOCTL		;no interrupts
	
	out	SIOACR		;account for possible power up into
	out	SIOBCR		;   synchronous mode
	out	SIOACR
	out	SIOBCR
	out	SIOACR
	out	SIOBCR

	mvi	a,40h		;reset 8251
	out	SIOACR
	out	SIOBCR

	mvi	a,4Eh		;8N1, /16
	out	SIOACR
	out	SIOBCR
	
	mvi	a,37h		;reset errors, enable xmit, rcv
	out	SIOACR
	out	SIOBCR

	ret
	
;----------------------------------------------------------------------------
; 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
;****************************************************************************
;
; Altair disk I/O routines
;
;****************************************************************************

; MITS Disk Drive Controller Equates

drvSel	equ	8		;drive select port (out)
drvStat	equ	8		;drive status port (in)
drvCtl	equ	9		;drive control port(out)
drvSec	equ	9		;drive sector position (in)
drvData	equ	10		;drive read/write data

enwdMsk	equ	001h		;enter new write data bit mask
headMsk	equ	004h		;mask to get head load bit alone
moveMsk	equ	002h		;mask to get head move bit alone
trk0Msk	equ	040h		;mask to get track zero bit alone
dSelect	equ	080h		;deselects drive when written to drvSel
selMask	equ	008h		;zero when selected, one otherwise

dcStepI	equ	001h		;drive command - step in
dcStepO	equ	002h		;drive command - step out
dcLoad	equ	004h		;drive command - load head
dcUload	equ	008h		;drive command - unload head
dcWrite	equ	080h		;drive command - start write sequence

;--------------------------------------------------------------
; 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 lxi	b,SECLEN	;b=0, c=sector length

dVfLoop	in	drvStat		;get drive status byte
	ora	a		;wait for NRDA flag true (zero)
	jm	dVfLoop

	in	drvData		;read the byte 
	xra	m		;verify data matches buffer
	ora	b		;accumulate errors in b
	mov	b,a
	inx	h		;increment buffer pointer
	dcr	c		;decrement characters remaining counter
	jz	dVfDone		;done verifying bytes
	in	drvData		;get the 2nd byte
	xra	m		;verify data matches buffer
	ora	b		;accumlate errors in b
	mov	b,a
	inx	h		;increment buffer pointer
	dcr	c		;decrement characters remaining counter
	jnz	dVfLoop		;loop until all bytes read

; dVfDone - all bytes read. If a is zero, data matched.

dVfDone	ora	a		;zero if all bytes verified
	ret			;return status

;--------------------------------------------------------------
; dWrite - Write a sector on current track
; On Entry:
;    Drive is selected, motor is running, sector sync was
;        just previously detected and the write command 
;    	 has already been issued to the controller.
;    hl->buffer address
; On Exit:
;   clobbers b,c,h,l
;--------------------------------------------------------------
dWrite	push	d		;save d,e
	mvi	c,SECLEN	;c=137 bytes to write
	mvi	d,enwdMsk	;Enter New Write Data flag mask
	mov	b,m		;b = 1st byte to write
	inx	h		;point to 2nd byte to write

; dWrLoop - write physical sector loop

dWrLoop	in	drvStat		;read drive status register
	ana	d		;write flag (ENWD) asserted (zero)?
	jnz	dWrLoop		;no, keep waiting

	add	b		;put byte to write into accumulator
	out	drvData		;write the byte
	mov	a,m		;a = next byte to write
	inx	h		;increment source buffer pointer
	mov	b,m		;e = byte to write next time through this loop
	inx	h		;increment source buffer pointer
	dcr	c		;decrement chars remaining (byte just written)
	jz	dWrDone		;zero - sector data written
	dcr	c		;dec chars remaining (byte about to write)
	out	drvData		;write 2nd byte
	jnz	dWrLoop		;loop if count <> 0

; dWrDone - write is done. Now write a last byte of zero

dWrDone	in	drvStat		;wait for another write flag
	ana	d
	jnz	dWrDone
	out	drvData		;write zero byte
	pop	d		;restore d,e
	ret

;--------------------------------------------------------------
; 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 (h,l not clobbered by this version)
;--------------------------------------------------------------
dChkWP	xra	a
	ret			;return zero status

;--------------------------------------------------------------
; dSeek - Seek Track.
; On Entry:
;    curTrk = current track, FFh means we don't know
;    l = desired track
; On Exit:
;    curTrk = current track
; trashes all registers
;--------------------------------------------------------------
dSeek	call	dSelDrv		;make sure drive is selected
	lda	curTrk		;where are we?
	cpi	0ffh
	cz	dRestor		;lost: restore (assumes a returned 0)

; Compute the required number of steps and the direction

	sub	l		;which way to step?
	rz			;already there?
	mvi	b,dcStepO	;assume desired<current (step out)
	jp	dDoSeek		;it is
	cma			;compute a=-a
	inr	a
	mvi	b,dcStepI	;desired>current (step in)

; Save target track and step there

dDoSeek	mov	h,a		;h=number of steps
	mov	a,l		;save new track when done in curTrk
	sta	curTrk
	jmp	dStep		;step to the specified track
	
;--------------------------------------------------------------
; dRestor - Restore to track 0
; On Exit:
;    a=0
;    curTrk=0
; trashes b,c,h (c not clobbered in this version)
;--------------------------------------------------------------
dRestor	call	dSelDrv		;make sure drive is selected
	xra	a
	sta	curTrk		;set current drive track to zero
	in	drvStat		;test for track 0
	ani	trk0Msk
	rz			;at track 0, exit

; Step in three tracks, then step out to track 0

	mvi	h,3		;h=step in 3 tracks
	mvi	b,dcStepI	;b=step in command
	call	dStep		;do 3 steps in
	rz			;already reached track 0

; Seek back out until track 0 detected

	mvi	h,NUMTRK+10	;maximum number of step outs to try
	mvi	b,dcStepO	;step out command
	call	dStep		;step out until track 0
	rz			;track zero reached

; Too many steps, can't find track 0. Display error and start the
;   program over

	call	dUnload		;unload drive head
	lxi	h,mNoTrk0
	call	dispMsg
	lxi	sp,ourStk	;initialize stack pointer
	jmp	getDrv		;start over asking for drive num

;--------------------------------------------------------------
; dStep - Step head (not a required entry). After seek operation
;   is complete, wait an additional 30ms in case another seek
;   operation immediately follows in the opposite direction.
; On Entry:
;   h = number of steps, >0
;   b = step command (dcStepO or dcStepI)
; On Exit:
;   Z set and curTrk=0 if track 0 found
; trashes b,c,h
;--------------------------------------------------------------
dStep	mov	a,b		;a=step command and direction
	out	drvCtl		;issue the step
dStepLp	in	drvStat		;loop until OK to move the head again
	ani	moveMsk
	jnz	dStepLp

; see if we hit track zero while stepping. If so, return with z
;   set and curTrk = 0

	in	drvStat		;test for track 0
	ani	trk0Msk
	jz	dStep0		

; not track zero. Loop until the specified number of steps is done.

	dcr	h		;decrement step counter
	jnz	dStep		;loop until count reaches zero
	mvi	a,30		;delay 30ms for possible dir change
	call	delayMs
	inr	h		;for non-zero status
	ret

;  We stepped to track 0 during this operation. Return with
;     curTrk set to 0 and the Z flag true

dStep0	sta	curTrk		;curTrk = 0
	mvi	a,30		;delay 30ms for possible dir change
	call	delayMs
	ret			;return with z true

;-----------------------------------------------------------------------------
; delayMs - delay for the ms specified in a
;   clobbers b,c
;-----------------------------------------------------------------------------
delayMs	mov	b,a		;b=ms to delay

delay1	mvi	c,(CPUSPED/19)	;19 is cycles in the loop below
delayLp	nop			;(4)
	dcr	c		;(5)
	jnz	delayLp		;(10)

	dcr	b		;decrement ms counter
	jnz	delay1
	ret

;--------------------------------------------------------------
; dSelDrv - Select drive in drvNum. If the drive is not already
;   selected, deselect the old drive and select the new drive.
; On Entry:
;    curDrv = drive currently selected, FFh means we don't know
;    drvNum = desired drive to be selected
; On Exit:
;    curDrv = current selected Drive
; Clobbers none
;--------------------------------------------------------------
dSelDrv	push	h		;save hl
	lxi	h,curDrv	;hl->currently selected drive
	lda	drvNum		;a=desired drive
	cmp	m		;proper drive already chosen?
	mov	m,a		;curDrv=drvNum
	jz	dVfySel		;yes, verify it's selected

; De-select current drive and select desired drive until the
;   drive is selected

dSelLp	mvi	a,dSelect	;deselect a possibly attached drive
	out	drvSel
	lda	drvNum		;a=drive to select
	out	drvSel		
dVfySel	in	drvStat		;loop until drive is selected
	ani	selMask		;drive selected?
	jnz	dSelLp		;no, try again
	pop	h		;restore hl
	ret

;--------------------------------------------------------------
; dDeslct - Deselect drive in drvNum (not a required entry)
;--------------------------------------------------------------
dDeslct	mvi	a,dSelect	;select code to de-select drive
	out	drvSel		
	ret

;--------------------------------------------------------------
; dLoad, dUnload - Load and unload head (drive-specific entry)
;   The head load is not issued if the head is already
;   settled so we don't re-start the head load one-shot.
; On Entry:
;    Drive is selected
; On Exit:
;    head loaded/unloaded
;--------------------------------------------------------------
dLoad	in	drvStat		;head loaded already?
	ani	headMsk
	rz			;yes, exit
	mvi	a,dcLoad	;issue the load head command
	out	drvCtl
	ret
	
; Head unload

dUnload	mvi	a,dcUload	;issue head unload command
	out	drvCtl
	ret

;--------------------------------------------------------------
; 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	in	drvSec		;read sector position register
	rar			;wait for sector true (0=true)
	jc	dWtSec
	ani	01fh		;get sector number alone
	cmp	e		;at the right sector yet?
	jnz	dWtSec		;no, keep looking

; Have sector pulse, return the sector number in e and the
;   byte offset of the sector within a track in bc

	mvi	h,(mult137 SHR 8)  ;h=msb of "multiply by 137" table
	rlc			;sector*2 (2 bytes per table entry)
	mov	l,a		;hl->sec*137 (table on 256 byte boundary)
	mov	c,m		;form bc=sec*137
	inx	h
	mov	b,m		;bc=byte offset of sector within a track
	ret	

;------------------------------------------------------------------
; mult137 - table to multiply byte 0-31 by 137. This table is
;    on a 256 byte boundary to speed up its use.
;------------------------------------------------------------------
	org	($+255) and 0ff00h
mult137	dw	00*137,01*137,02*137,03*137,04*137,05*137,06*137,07*137
	dw	08*137,09*137,10*137,11*137,12*137,13*137,14*137,15*137
	dw	16*137,17*137,18*137,19*137,20*137,21*137,22*137,23*137
	dw	24*137,25*137,26*137,27*137,28*137,29*137,30*137,31*137

;--------------------------------------------------------------
; dNxtSec - Wait for next (any) sector. The command in wrtCmd
;    is issued to the controller right after sector true is
;    detected. If zero, this will do nothing. Otherwise, it
;    should be the write command with the head current bit.
;
; On Entry:
;    Drive is selected, motor is running, wrtCmd set as needed.
; On Exit:
;    drive is at proper sector
;    e = sector number
;    bc = byte offset of this sector in a track
;--------------------------------------------------------------
dNxtSec	in	drvSec		;read sector position register
	rar			;wait for sector true (0=true)
	jc	dNxtSec

; Have sector pulse. wrtCmd is written to the controller. If
;   zero, the command does nothing. Otherwise, wrtCmd enables
;   a write with the proper head current switch.

	ani	01fh		;get sector number alone
	mov	e,a		;e=sector number
	lda	wrtCmd		;a=write command or zero
	out	drvCtl		;issue to controller
	mov	a,e		;a=sector number

; Return the sector number in e and the byte offset of the sector
;    within a track in bc

	mvi	h,(mult137 SHR 8)  ;h=msb of "multiply by 137" table
	rlc			;sector*2 (2 bytes per table entry)
	mov	l,a		;hl->sec*137 (table on 256 byte boundary)
	mov	c,m		;form bc=sec*137
	inx	h
	mov	b,m		;bc=byte offset of sector within a track
	ret	


;**************************************************************************
; 
;  Data area
;
;**************************************************************************
; disk variables

drvNum	ds	1		;drive number to use
curDrv	ds	1		;drive currently selected
curTrk	ds	1		;current track number drive is on
trkNum	ds	1		;track number to read
trkPtr	ds	2		;pointer into trkBuf (start of next track)
bufEnd	ds	2		;end address + 1 of last track spot in RAM
wrtCmd	ds	1		;write command for the controller

; retry logic variables

rdRetry	ds	1		;disk read retry counter
wrRetry	ds	1		;disk write retry counter

; xmodem variables

xfrPort	ds	1		;pseudo port for file transfer
blkNum	ds	1		;current xmodem block number
rcvBlk	ds	1		;block number received
rcvNBlk	ds	1		;"not" block number received
rcvPtr	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	96		;stack space
ourStk	equ	$

; track buffer runs from here to the end of memory

trkBuf	equ	$

	end
