; Builds program as iNES ROM

; Default is 32K PRG and 8K CHR ROM, NROM (0)

.if 0 ; Options to set before .include "shell.inc":
CHR_RAM=1       ; Use CHR-RAM instead of CHR-ROM
CART_WRAM=1     ; Use mapper that supports 8K WRAM in cart
CUSTOM_MAPPER=n ; Specify mapper number
.endif

.ifndef CUSTOM_MAPPER
	.ifdef CART_WRAM
		CUSTOM_MAPPER = 2 ; UNROM
	.else
		CUSTOM_MAPPER = 0 ; NROM
	.endif
.endif

;;;; iNES header
.ifndef CUSTOM_HEADER
	.segment "HEADER"
		.byte $4E,$45,$53,26 ; "NES" EOF
		
		.ifdef CHR_RAM
			.byte 2,0 ; 32K PRG, CHR RAM
		.else
			.byte 2,1 ; 32K PRG, 8K CHR
		.endif
		
		.byte CUSTOM_MAPPER*$10+$01 ; vertical mirroring
.endif

.ifndef CUSTOM_VECTORS
	.segment "VECTORS"
		.word $FFFF,$FFFF,$FFFF, nmi, reset, irq
.endif

;;;; CHR-RAM/ROM
.ifdef CHR_RAM
	.define CHARS "CHARS_PRG"
	.segment CHARS
		ascii_chr:
	
	.segment "CHARS_PRG_ASCII"
		.align $200
			.incbin "ascii.chr"
		ascii_chr_end:
.else
	.define CHARS "CHARS"
	.segment "CHARS_ASCII"
		.align $200
		.incbin "ascii.chr"
		.res $1800
.endif

	.segment "CODE"
.ifndef CUSTOM_RESET
reset:
.endif
std_reset:
	jmp main

	zp_byte nmi_count
	zp_byte flags_from_nmi
	zp_byte pclo_from_nmi
	zp_byte nmi_temp
.ifndef CUSTOM_NMI
nmi:
.endif
std_nmi:
	sta nmi_temp
	pla
	sta flags_from_nmi
	pla
	sta pclo_from_nmi
	pha
	lda flags_from_nmi
	pha
	lda nmi_temp
	inc nmi_count
	rti

	zp_byte flags_from_irq
	zp_byte pclo_from_irq
	zp_byte irq_count
	
.ifndef CUSTOM_IRQ
irq:
.endif
std_irq: ; Record flags and PC low byte from stack
	pla
	sta flags_from_irq
	pla
	sta pclo_from_irq
	pha
	lda flags_from_irq
	pha
	inc irq_count
	bit SNDCHN  ; clear frame IRQ flag
	rti

fail:
	lda #$01
.ifndef CUSTOM_EXIT
exit:
.endif
std_exit:
	.byte $02

.segment CHARS
	.res $10,0

; Move code to $C000
.segment "CODE"
	.res $4000

.code
.align 256
