.include "testing.s"
.include "audio_inp.s"

zp_res TIMER_LOW
zp_res SWEEP
zp_res DLCV
; zp_res TIMER_LOW

reset:
	sei
	cld
	ldx #$FF
	txs

	lda #$01
	sta SNDCHN
	lda #$BF ; Duty 2, LC halted, evelope enabled, volume = F
	sta PULSE_CH1_DLCV
	sta DLCV
	lda #$7F ; 
	sta PULSE_CH1_SWEEP
	sta SWEEP
	lda #$6F
	sta PULSE_CH1_TLOW
	sta TIMER_LOW
	lda #$F0
	sta PULSE_CH1_LCTH
; PULSE_CH1_DLCV = $4000
; PULSE_CH1_SWEEP = $4001
; PULSE_CH1_TLOW = $4002
; PULSE_CH1_LCTH = $4003

	jsr init_view

	load_ppu_addr $2041
	write_char_x 't'
	write_char_x 'i'
	write_char_x 'm'
	write_char_x 'e'
	write_char_x 'r'
	write_char_x ' '
	write_char_x 'l'
	write_char_x 'o'
	write_char_x 'w'
	write_char_x ':'

	load_ppu_addr $2061
	write_char_x 's'
	write_char_x 'w'
	write_char_x 'e'
	write_char_x 'e'
	write_char_x 'p'
	write_char_x ':'

	load_ppu_addr $2081
	write_char_x 'd'
	write_char_x 'l'
	write_char_x 'c'
	write_char_x 'v'
	write_char_x ':'

	load_ppu_addr $204C
	lda TIMER_LOW
	jsr write_hex_a

	load_ppu_addr $206C
	lda SWEEP
	jsr write_hex_a

	load_ppu_addr $208C
	lda DLCV
	jsr write_hex_a

	jsr enable_rendering
loop:
	jmp loop

; Joystick is in A and JOYTEMP
	zp_res JOY_PREV
audio_nmi:
	EOR JOY_PREV
	STA JOY_PREV

	lda JOYTEMP
	and #JOY_UP_MASK
	and JOY_PREV
	beq down
	load_ppu_addr $204C
	lda #$01
	adc TIMER_LOW
	sta TIMER_LOW
	sta PULSE_CH1_TLOW
	jsr write_hex_a

down:
	lda JOYTEMP
	and #JOY_DOWN_MASK
	and JOY_PREV
	beq left
	load_ppu_addr $204C
	lda #$FF
	adc TIMER_LOW
	sta TIMER_LOW
	sta PULSE_CH1_TLOW
	jsr write_hex_a

left:
	lda JOYTEMP
	and #JOY_LEFT_MASK
	and JOY_PREV
	beq right
	load_ppu_addr $206C
	lda #$FF
	adc SWEEP
	sta SWEEP
	sta PULSE_CH1_SWEEP
	jsr write_hex_a

right:
	lda JOYTEMP
	and #JOY_RIGHT_MASK
	and JOY_PREV
	beq joy_a
	load_ppu_addr $206C
	lda #$01
	adc SWEEP
	sta SWEEP
	sta PULSE_CH1_SWEEP
	jsr write_hex_a

joy_a:
	lda JOYTEMP
	and #JOY_A_MASK
	and JOY_PREV
	beq joy_b
	load_ppu_addr $208C
	lda DLCV
	eor #$10
	sta DLCV
	sta PULSE_CH1_DLCV
	jsr write_hex_a
	; sta PULSE_CH1_DLCV
	lda #$F0
	sta PULSE_CH1_LCTH

joy_b:
	lda JOYTEMP
	and #JOY_B_MASK
	and JOY_PREV
	beq done
	load_ppu_addr $204C
	lda #$00
	; adc TIMER_LOW
	; sta TIMER_LOW
	sta PULSE_CH1_TLOW
	; jsr write_hex_a
done:


	lda JOYTEMP
	STA JOY_PREV
	rts

irq:
	rti
