;	1351 PROPORTIONAL MOUSE DRIVER FOR THE C64
;
;	COMMODORE BUSINESS MACHINES, INC.   27OCT86
;		BY HEDLEY DAVIS AND FRED BOWEN

IIRQ	= $0314
VIC	= $D000
SID	= $D400
CIA	= $DC00
CIA.DDR	= $DC02
POTX	= SID+$19
POTY	= SID+$1A

XPOS	= VIC+$00	;X POSITION (LSB)
YPOS	= VIC+$01	;Y POSITION
XPOSMSB	= VIC+$10	;X POSITION (MSB)

	*=$C0F0

IIRQ2		*=*+2
OPOTX		*=*+1
OPOTY		*=*+1
NEWVALUE	*=*+1
OLDVALUE	*=*+1
CIASAVE		*=*+1


	* = $C000

	JMP INSTALL.1	;INSTALL MOUSE IN PORT 1
	JMP INSTALL.2	;INSTALL MOUSE IN PORT 2
	JMP REMOVE	;REMOVE MOUSE WEDGE


INSTALL.1	LDX #0		;PORT 1 MOUSE
		.BYTE $2C

INSTALL.2	LDX #2		;PORT 2 MOUSE

	LDA IIRQ+1	;INSTALL IRQ WEDGE
	CMP #>MIRQ.1
	BEQ 90$		;...BRANCH IF ALREADY INSTALLED!
	PHP
	SEI

	LDA IIRQ	;SAVE CURRENT IRQ INDIRECT FOR OUR EXIT
	STA IIRQ2
	LDA IIRQ+1
	STA IIRQ2+1

	LDA PORT,X	;POINT IRQ INDIRECT TO MOUSE DRIVER
	STA IIRQ
	LDA PORT+1,X
	STA IIRQ+1
	PLP
90$	RTS

PORT	.WORD MIRQ.1
	.WORD MIRQ.2


REMOVE	LDA IIRQ+1	;REMOVE IRQ WEDGE
	CMP #>MIRQ.1
	BNE 90$		;...BRANCH IF ALREADY REMOVED!
	PHP
	SEI
	LDA IIRQ2	;RESTORE SAVED INDIRECT
	STA IIRQ
	LDA IIRQ2+1
	STA IIRQ+1
	PLP
90$	RTS



MIRQ.2	LDA #$80	;PORT2 MOUSE SCAN
	.BYTE $2C

MIRQ.1	LDA #$40	;PORT1 MOUSE SCAN

	JSR SETPOT	;CONFIGURE CIA PER .A

	LDA POTX	;GET DELTA VALUES FOR X
	LDY OPOTX
	JSR MOVCHK
	STY OPOTX

	CLC		;MODIFY LOW ORDER X POSITION
	ADC XPOS
	STA XPOS
	TXA
	ADC #$00
	AND #%00000001
	EOR XPOSMSB
	STA XPOSMSB

	LDA POTY	;GET DELTA VALUE FOR Y
	LDY OPOTY
	JSR MOVCHK
	STY OPOTY

	SEC		;MODIFY Y POSITION (DECREASE Y FOR INCREASE IN POT)
	EOR #$FF
	ADC YPOS
	STA YPOS

	LDX CIASAVE	;RESTORE KEYBOARD
	STX CIA

90$	JMP (IIRQ2)	;CONTINUE W/ IRQ OPERATION



; MOVCHK
;	ENTRY	Y = OLD VALUE OF POT REGISTER
;		A = CURRRENT VALUE OF POT REGISTER
;	EXIT	Y = VALUE TO USE FOR OLD VALUE
;		X,A = DELTA VALUE FOR POSITION
;

MOVCHK	STY OLDVALUE	;SAVE OLD & NEW VALUES
	STA NEWVALUE
	LDX #0		;PRELOAD X W/ 0

	SEC		;A = MOD64(NEW-OLD)
	SBC OLDVALUE
	AND #%01111111	
	CMP #%01000000	;IF A > 0
	BCS 50$
	LSR A		;   THEN A = A/2
	BEQ 80$		;      IF A <> 0
	LDY NEWVALUE	;         THEN Y = NEWVALUE
	RTS		;              RETURN

50$	ORA #%11000000	;   ELSE OR-IN HIGH ORDER BITS
	CMP #$FF	;      IF A <> -1
	BEQ 80$
	SEC		;         THEN A = A/2
	ROR A
	LDX #$FF	;              X = -1
	LDY NEWVALUE	;              Y = NEWVALUE
	RTS		;              RETURN

80$	LDA #0		;A = 0
	RTS		;RETURN W/ Y = OLD VALUE



SETPOT	LDX CIA		;SAVE KEYBOARD LINES
	STX CIASAVE

	STA CIA		;CONNECT APPROPRIATE PORT TO SID

	LDX #4
	LDY #$C7	;DELAY 4MS TO LET LINES SETTLE & GET SYNC-ED
10$	DEY 
	BNE 10$
	DEX
	BNE 10$
	RTS

	.END
