

    .export _exit,__STARTUP__:absolute=1

	.import push0,popa,popax,copydata,_main

	.import __RAM_START__   ,__RAM_SIZE__
	.import __ROM0_START__  ,__ROM0_SIZE__
	.import __STARTUP_LOAD__,__STARTUP_RUN__,__STARTUP_SIZE__
	.import	__CODE_LOAD__   ,__CODE_RUN__   ,__CODE_SIZE__
	.import	__RODATA_LOAD__ ,__RODATA_RUN__ ,__RODATA_SIZE__
	
	.import NES_MAPPER,NES_PRG_BANKS,NES_CHR_BANKS,NES_MIRRORING
	
    .include "zeropage.inc"

PPU_CTRL	=$2000
PPU_MASK	=$2001
PPU_STATUS	=$2002
PPU_OAM_ADDR=$2003
PPU_OAM_DATA=$2004
PPU_SCROLL	=$2005
PPU_ADDR	=$2006
PPU_DATA	=$2007
PPU_OAM_DMA	=$4014
PPU_FRAMECNT=$4017
DMC_FREQ	=$4010
CTRL_PORT1	=$4016
CTRL_PORT2	=$4017



.segment "BSS"

.segment "STARTUP"

.segment "HEADER"

    .byte $4e,$45,$53,$1a
	.byte <NES_PRG_BANKS
	.byte <NES_CHR_BANKS
	.byte <NES_MIRRORING|(<NES_MAPPER<<4)
	.byte <NES_MAPPER&$f0
	.res 8,0


	.include "defines.s"


	.include "neslib.s"
	.include "mmc3.s"
	.include "irq.s"
	.include "nmi.s"
	.include "prg_fixed.s"
	.include "playdump.s"

reset:
_exit:

    sei

	ldx #0

	stx PPU_CTRL
	stx PPU_MASK
	stx MMC3_IRQ_DISABLE
	stx MMC3_MIRROR			;vertical mirroring

	dex
	txs

initPPU:

    bit PPU_STATUS
@1:
    bit PPU_STATUS
    bpl @1
@2:
    bit PPU_STATUS
    bpl @2

clearPalette:

	lda #$3f
	sta PPU_ADDR
	lda #$00
	sta PPU_ADDR
	lda #$0f
	ldx #$20
@1:
	sta PPU_DATA
	dex
	bne @1

clearRAM:

    txa
@1:
    sta $000,x
    sta $100,x
    sta $200,x
    sta $300,x
    sta $400,x
    sta $500,x
    sta $600,x
    sta $700,x
    inx
    bne @1

	lda #PRG_MAIN
	jsr mmc3_set_prg

	lda #0
	jsr _set_irq_handler
	lda #0
	jsr _set_nmi_handler
	
	lda #4
	jsr _pal_bright
	jsr _pal_clear
	jsr _oam_clear_fast

    ;jsr	zerobss				;memory is already zeroed
	jsr	copydata

    lda #<(__RAM_START__+__RAM_SIZE__)
    sta	sp
    lda	#>(__RAM_START__+__RAM_SIZE__)
    sta	sp+1            ; Set argument stack ptr

	;jsr	initlib		;no constructors

	lda #%10000000
	sta <PPU_CTRL_VAR
	sta PPU_CTRL		;enable NMI
	lda #%00000110
	sta <PPU_MASK_VAR

waitSync3:

	lda <FRAME_CNT1
@1:
	cmp <FRAME_CNT1
	beq @1

detectNTSC:

	ldx #52				;blargg's code
	ldy #24
@1:
	dex
	bne @1
	dey
	bne @1

	lda PPU_STATUS
	and #$80
	;eor #$80
	sta <NTSC_MODE

	jsr _ppu_off

	lda #0
	sta PPU_SCROLL
	sta PPU_SCROLL
	sta PPU_OAM_ADDR
	
	lda #$fd
	sta <RAND_SEED
	sta <RAND_SEED+1

	jsr playdump_init
	
	lda #PRG_MAIN
	jsr mmc3_set_prg

	lda #$40
	sta CTRL_PORT2			;disable apu frame irq
	cli						;enable irq for mmc3

	jmp _main				;no parameters



.segment "VECTORS"

	.word NMI_CALL
    .word reset
   	.word IRQ_CALL

	.include "prg.s"
	.include "chr.s"