.include "testing.s"

reset:
	sei
	cld
	ldx #$FF
	txs

	; Init PPU
	bit PPUSTATUS
vwait1:
	bit PPUSTATUS
	bpl vwait1
vwait2:
	bit PPUSTATUS
	bpl vwait2

	lda #$04
	sta SNDCHN
	lda #$FF
	sta TRIANGLE_LINEAR_C
	lda #$37
	sta TRIANGLE_TIMER_LOW
	lda #$00
	sta TRIANGLE_LEN_T_HIGH
; TRIANGLE_LINEAR_C = $4008
; TRIANGLE_TIMER_LOW = $400A
; TRIANGLE_LEN_T_HIGH = $400B

	lda #$80
	sta PPUCTRL ; NMI on, PPU slave, Small sprites, 0 addresses
	lda #$00
loop:
	; sta SNDMODE
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	; nop
	jmp loop

; zp_res 
zp_res TIMER_LOW
update_audio:
	; adc TIMER_LOW
	; sta PULSE_CH1_TLOW
	; sta TIMER_LOW

	rts

zp_res PRESSED_A
zp_res PRESSED_B

nmi:
	pha
	txa
	pha
	tya
	pha
	lda PPUSTATUS
	lda #%00000110
	sta PPUMASK ; Force blank

	lda #$01
	sta JOY1
	lda #$00
	sta JOY1

	lda JOY1 ; A
	and #$01
	tax
	eor PRESSED_A
	beq done
	stx PRESSED_A
	txa
	and #$01
	beq done

	lda #$08
	jsr update_audio

done:
	bit JOY1 ; B
	and #$01
	tax
	eor PRESSED_B
	beq done_b
	stx PRESSED_B
	txa
	and #$01
	beq done_b

	lda #$F7
	jsr update_audio

done_b:
	bit JOY1 ; Select
	bit JOY1 ; Start
	bit JOY1 ; Up
	bit JOY1 ; Down
	bit JOY1 ; Left
	bit JOY1 ; Right

	lda #$00
	sta PPUSCROLL
	sta PPUSCROLL
	
	lda #%00001110
	sta PPUMASK ; Enable rendering
	pla
	tay
	pla
	tax
	pla
	rti

irq:
	rti
