code:
;*
;* Gameboy Hardware definitions
;*
;* Based on Jones' hardware.inc
;* And based on Carsten Sorensen's ideas.
;*
;* Rev 1.1 - 15-Jul-97 : Added define check
;* Rev 1.2 - 18-Jul-97 : Added revision check macro
;* Rev 1.3 - 19-Jul-97 : Modified for RGBASM V1.05
;* Rev 1.4 - 27-Jul-97 : Modified for new subroutine prefixes
;* Rev 1.5 - 15-Aug-97 : Added _HRAM, PAD, CART defines
;*                     :  and Nintendo Logo
;* Rev 1.6 - 30-Nov-97 : Added rDIV, rTIMA, rTMA, & rTAC
;* Rev 1.7 - 31-Jan-98 : Added _SCRN0, _SCRN1
;* Rev 1.8 - 15-Feb-98 : Added rSB, rSC
;* Rev 1.9 - 16-Feb-98 : Converted I/O registers to $FFXX format
;* Rev 2.0 -           : Added GBC registers
;* Rev 2.1 -           : Added MBC5 & cart RAM enable/disable defines
;* Rev 2.2 -           : Fixed NR42,NR43, & NR44 equates
;* Rev 2.3 -           : Fixed incorrect _HRAM equate
;* Rev 2.4 - 27-Apr-13 : Added some cart defines (AntonioND)
;* Rev 2.5 - 03-May-15 : Fixed format (AntonioND)
;* Rev 2.6 - 09-Apr-16 : Added GBC OAM and cart defines (AntonioND)
;* Rev 2.7 - 19-Jan-19 : Added rPCMXX (ISSOtm)
;* Rev 2.8 - 03-Feb-19 : Added audio registers flags (Álvaro Cuesta)
;* Rev 2.9 - 28-Feb-20 : Added utility rP1 constants
;* Rev 3.0 - 27-Aug-20 : Register ordering, byte-based sizes, OAM additions, general cleanup (Blitter Object)
;* Rev 4.0 - 03-May-21 : Updated to use RGBDS 0.5.0 syntax, changed IEF_LCDC to IEF_STAT (Eievui)
;* Rev 4.1 - 16-Aug-21 : Added more flags, bit number defines, and offset constants for OAM and window positions (rondnelson99)
;* Rev 4.2 - 04-Sep-21 : Added CH3- and CH4-specific audio registers flags (ISSOtm)
;* Rev 4.3 - 07-Nov-21 : Deprecate VRAM address constants (Eievui)
;* Rev 4.4 - 11-Jan-22 : Deprecate VRAM CART_SRAM_2KB constant (avivace)
;* Rev 4.5 - 03-Mar-22 : Added bit number definitions for OCPS, BCPS and LCDC (sukus)
;* Rev 4.6 - 15-Jun-22 : Added MBC3 registers and special values
;* Rev 4.7.0 - 27-Jun-22 : Added alternate names for some constants
;* Rev 4.7.1 - 05-Jul-22 : Added RPB_LED_ON constant
;* Rev 4.8.0 - 25-Oct-22 : Changed background addressing constants (zlago)

; NOTE: REVISION NUMBER CHANGES MUST BE REFLECTED
; IN `rev_Check_hardware_inc` BELOW!

IF __RGBDS_MAJOR__ == 0 && __RGBDS_MINOR__ < 5
    FAIL "This version of 'hardware.inc' requires RGBDS version 0.5.0 or later."
ENDC

; If all of these are already defined, don't do it again.

    IF !DEF(HARDWARE_INC)
DEF HARDWARE_INC EQU 1

; Usage: rev_Check_hardware_inc <min_ver>
; Examples: rev_Check_hardware_inc 4.1.2
;           rev_Check_hardware_inc 4.1 (equivalent to 4.1.0)
;           rev_Check_hardware_inc 4 (equivalent to 4.0.0)
MACRO rev_Check_hardware_inc
    DEF CUR_VER equs "4,8,0"    ; ** UPDATE THIS LINE WHEN CHANGING THE REVISION NUMBER **

    DEF MIN_VER equs STRRPL("\1", ".", ",")
    DEF INTERNAL_CHK equs """MACRO ___internal
    IF \\1 != \\4 || \\2 < \\5 || (\\2 == \\5 && \\3 < \\6)
    	FAIL "Version \\1.\\2.\\3 of 'hardware.inc' is incompatible with requested version \\4.\\5.\\6"
    ENDC
\nENDM"""
    INTERNAL_CHK
    ___internal {CUR_VER}, {MIN_VER},0,0
    PURGE CUR_VER, MIN_VER, INTERNAL_CHK, ___internal
ENDM

;***************************************************************************
;*
;* General memory region constants
;*
;***************************************************************************

DEF _VRAM        EQU $8000 ; $8000->$9FFF
DEF _SCRN0       EQU $9800 ; $9800->$9BFF
DEF _SCRN1       EQU $9C00 ; $9C00->$9FFF
DEF _SRAM        EQU $A000 ; $A000->$BFFF
DEF _RAM         EQU $C000 ; $C000->$CFFF / $C000->$DFFF
DEF _RAMBANK     EQU $D000 ; $D000->$DFFF
DEF _OAMRAM      EQU $FE00 ; $FE00->$FE9F
DEF _IO          EQU $FF00 ; $FF00->$FF7F,$FFFF
DEF _AUD3WAVERAM EQU $FF30 ; $FF30->$FF3F
DEF _HRAM        EQU $FF80 ; $FF80->$FFFE

;***************************************************************************
;*
;* MBC registers
;*
;***************************************************************************

; *** Common ***

; --
; -- RAMG ($0000-$1FFF)
; -- Controls whether access to SRAM (and the MBC3 RTC registers) is allowed (W)
; --
DEF rRAMG EQU $0000

DEF CART_SRAM_ENABLE  EQU $0A
DEF CART_SRAM_DISABLE EQU $00

; --
; -- ROMB0 ($2000-$3FFF)
; -- Selects which ROM bank is mapped to the ROMX space ($4000-$7FFF) (W)
; --
; -- The range of accepted values, as well as the behavior of writing $00,
; -- varies depending on the MBC.
; --
DEF rROMB0 EQU $2000

; --
; -- RAMB ($4000-$5FFF)
; -- Selects which SRAM bank is mapped to the SRAM space ($A000-$BFFF) (W)
; --
; -- The range of accepted values varies depending on the cartridge configuration.
; --
DEF rRAMB EQU $4000

; *** MBC3-specific registers ***

; Write one of these to rRAMG to map the corresponding RTC register to all SRAM space
DEF RTC_S  EQU $08 ; Seconds  (0-59)
DEF RTC_M  EQU $09 ; Minutes  (0-59)
DEF RTC_H  EQU $0A ; Hours    (0-23)
DEF RTC_DL EQU $0B ; Lower 8 bits of Day Counter ($00-$FF)
DEF RTC_DH EQU $0C ; Bit 7 - Day Counter Carry Bit (1=Counter Overflow)
                   ; Bit 6 - Halt (0=Active, 1=Stop Timer)
                   ; Bit 0 - Most significant bit of Day Counter (Bit 8)

; --
; -- RTCLATCH ($6000-$7FFF)
; -- Write $00 then $01 to latch the current time into the RTC registers (W)
; --
DEF rRTCLATCH EQU $6000

; *** MBC5-specific register ***

; --
; -- ROMB1 ($3000-$3FFF)
; -- A 9th bit that "extends" ROMB0 if more than 256 banks are present (W)
; --
; -- Also note that rROMB0 thus only spans $2000-$2FFF.
; --
DEF rROMB1 EQU $3000

; Bit 3 of RAMB enables the rumble motor (if any)
DEF CART_RUMBLE_ON EQU 1 << 3

;***************************************************************************
;*
;* Memory-mapped registers
;*
;***************************************************************************

; --
; -- P1 ($FF00)
; -- Register for reading joy pad info. (R/W)
; --
DEF rP1 EQU $FF00

DEF P1F_5 EQU %00100000 ; P15 out port, set to 0 to get buttons
DEF P1F_4 EQU %00010000 ; P14 out port, set to 0 to get dpad
DEF P1F_3 EQU %00001000 ; P13 in port
DEF P1F_2 EQU %00000100 ; P12 in port
DEF P1F_1 EQU %00000010 ; P11 in port
DEF P1F_0 EQU %00000001 ; P10 in port

DEF P1F_GET_DPAD EQU P1F_5
DEF P1F_GET_BTN  EQU P1F_4
DEF P1F_GET_NONE EQU P1F_4 | P1F_5

; --
; -- SB ($FF01)
; -- Serial Transfer Data (R/W)
; --
DEF rSB EQU $FF01

; --
; -- SC ($FF02)
; -- Serial I/O Control (R/W)
; --
DEF rSC EQU $FF02

DEF SCF_START  EQU %10000000 ; Transfer Start Flag (1=Transfer in progress, or requested)
DEF SCF_SPEED  EQU %00000010 ; Clock Speed (0=Normal, 1=Fast) ** CGB Mode Only **
DEF SCF_SOURCE EQU %00000001 ; Shift Clock (0=External Clock, 1=Internal Clock)

DEF SCB_START  EQU 7
DEF SCB_SPEED  EQU 1
DEF SCB_SOURCE EQU 0

; --
; -- DIV ($FF04)
; -- Divider register (R/W)
; --
DEF rDIV EQU $FF04

; --
; -- TIMA ($FF05)
; -- Timer counter (R/W)
; --
DEF rTIMA EQU $FF05

; --
; -- TMA ($FF06)
; -- Timer modulo (R/W)
; --
DEF rTMA EQU $FF06

; --
; -- TAC ($FF07)
; -- Timer control (R/W)
; --
DEF rTAC EQU $FF07

DEF TACF_START  EQU %00000100
DEF TACF_STOP   EQU %00000000
DEF TACF_4KHZ   EQU %00000000
DEF TACF_16KHZ  EQU %00000011
DEF TACF_65KHZ  EQU %00000010
DEF TACF_262KHZ EQU %00000001

DEF TACB_START  EQU 2

; --
; -- IF ($FF0F)
; -- Interrupt Flag (R/W)
; --
DEF rIF EQU $FF0F

; --
; -- AUD1SWEEP/NR10 ($FF10)
; -- Sweep register (R/W)
; --
; -- Bit 6-4 - Sweep Time
; -- Bit 3   - Sweep Increase/Decrease
; --           0: Addition    (frequency increases???)
; --           1: Subtraction (frequency increases???)
; -- Bit 2-0 - Number of sweep shift (# 0-7)
; -- Sweep Time: (n*7.8ms)
; --
DEF rNR10 EQU $FF10
DEF rAUD1SWEEP EQU rNR10

DEF AUD1SWEEP_UP   EQU %00000000
DEF AUD1SWEEP_DOWN EQU %00001000

; --
; -- AUD1LEN/NR11 ($FF11)
; -- Sound length/Wave pattern duty (R/W)
; --
; -- Bit 7-6 - Wave Pattern Duty (00:12.5% 01:25% 10:50% 11:75%)
; -- Bit 5-0 - Sound length data (# 0-63)
; --
DEF rNR11 EQU $FF11
DEF rAUD1LEN EQU rNR11

; --
; -- AUD1ENV/NR12 ($FF12)
; -- Envelope (R/W)
; --
; -- Bit 7-4 - Initial value of envelope
; -- Bit 3   - Envelope UP/DOWN
; --           0: Decrease
; --           1: Range of increase
; -- Bit 2-0 - Number of envelope sweep (# 0-7)
; --
DEF rNR12 EQU $FF12
DEF rAUD1ENV EQU rNR12

; --
; -- AUD1LOW/NR13 ($FF13)
; -- Frequency low byte (W)
; --
DEF rNR13 EQU $FF13
DEF rAUD1LOW EQU rNR13

; --
; -- AUD1HIGH/NR14 ($FF14)
; -- Frequency high byte (W)
; --
; -- Bit 7   - Initial (when set, sound restarts)
; -- Bit 6   - Counter/consecutive selection
; -- Bit 2-0 - Frequency's higher 3 bits
; --
DEF rNR14 EQU $FF14
DEF rAUD1HIGH EQU rNR14

; --
; -- AUD2LEN/NR21 ($FF16)
; -- Sound Length; Wave Pattern Duty (R/W)
; --
; -- see AUD1LEN for info
; --
DEF rNR21 EQU $FF16
DEF rAUD2LEN EQU rNR21

; --
; -- AUD2ENV/NR22 ($FF17)
; -- Envelope (R/W)
; --
; -- see AUD1ENV for info
; --
DEF rNR22 EQU $FF17
DEF rAUD2ENV EQU rNR22

; --
; -- AUD2LOW/NR23 ($FF18)
; -- Frequency low byte (W)
; --
DEF rNR23 EQU $FF18
DEF rAUD2LOW EQU rNR23

; --
; -- AUD2HIGH/NR24 ($FF19)
; -- Frequency high byte (W)
; --
; -- see AUD1HIGH for info
; --
DEF rNR24 EQU $FF19
DEF rAUD2HIGH EQU rNR24

; --
; -- AUD3ENA/NR30 ($FF1A)
; -- Sound on/off (R/W)
; --
; -- Bit 7   - Sound ON/OFF (1=ON,0=OFF)
; --
DEF rNR30 EQU $FF1A
DEF rAUD3ENA EQU rNR30

DEF AUD3ENA_OFF EQU %00000000
DEF AUD3ENA_ON  EQU %10000000

; --
; -- AUD3LEN/NR31 ($FF1B)
; -- Sound length (R/W)
; --
; -- Bit 7-0 - Sound length
; --
DEF rNR31 EQU $FF1B
DEF rAUD3LEN EQU rNR31

; --
; -- AUD3LEVEL/NR32 ($FF1C)
; -- Select output level
; --
; -- Bit 6-5 - Select output level
; --           00: 0/1 (mute)
; --           01: 1/1
; --           10: 1/2
; --           11: 1/4
; --
DEF rNR32 EQU $FF1C
DEF rAUD3LEVEL EQU rNR32

DEF AUD3LEVEL_MUTE EQU %00000000
DEF AUD3LEVEL_100  EQU %00100000
DEF AUD3LEVEL_50   EQU %01000000
DEF AUD3LEVEL_25   EQU %01100000

; --
; -- AUD3LOW/NR33 ($FF1D)
; -- Frequency low byte (W)
; --
; -- see AUD1LOW for info
; --
DEF rNR33 EQU $FF1D
DEF rAUD3LOW EQU rNR33

; --
; -- AUD3HIGH/NR34 ($FF1E)
; -- Frequency high byte (W)
; --
; -- see AUD1HIGH for info
; --
DEF rNR34 EQU $FF1E
DEF rAUD3HIGH EQU rNR34

; --
; -- AUD4LEN/NR41 ($FF20)
; -- Sound length (R/W)
; --
; -- Bit 5-0 - Sound length data (# 0-63)
; --
DEF rNR41 EQU $FF20
DEF rAUD4LEN EQU rNR41

; --
; -- AUD4ENV/NR42 ($FF21)
; -- Envelope (R/W)
; --
; -- see AUD1ENV for info
; --
DEF rNR42 EQU $FF21
DEF rAUD4ENV EQU rNR42

; --
; -- AUD4POLY/NR43 ($FF22)
; -- Polynomial counter (R/W)
; --
; -- Bit 7-4 - Selection of the shift clock frequency of the (scf)
; --           polynomial counter (0000-1101)
; --           freq=drf*1/2^scf (not sure)
; -- Bit 3 -   Selection of the polynomial counter's step
; --           0: 15 steps
; --           1: 7 steps
; -- Bit 2-0 - Selection of the dividing ratio of frequencies (drf)
; --           000: f/4   001: f/8   010: f/16  011: f/24
; --           100: f/32  101: f/40  110: f/48  111: f/56  (f=4.194304 Mhz)
; --
DEF rNR43 EQU $FF22
DEF rAUD4POLY EQU rNR43

DEF AUD4POLY_15STEP EQU %00000000
DEF AUD4POLY_7STEP  EQU %00001000

; --
; -- AUD4GO/NR44 ($FF23)
; --
; -- Bit 7 -   Initial (when set, sound restarts)
; -- Bit 6 -   Counter/consecutive selection
; --
DEF rNR44 EQU $FF23
DEF rAUD4GO EQU rNR44

; --
; -- AUDVOL/NR50 ($FF24)
; -- Channel control / ON-OFF / Volume (R/W)
; --
; -- Bit 7   - Vin->SO2 ON/OFF (left)
; -- Bit 6-4 - SO2 output level (left speaker) (# 0-7)
; -- Bit 3   - Vin->SO1 ON/OFF (right)
; -- Bit 2-0 - SO1 output level (right speaker) (# 0-7)
; --
DEF rNR50 EQU $FF24
DEF rAUDVOL EQU rNR50

DEF AUDVOL_VIN_LEFT  EQU %10000000 ; SO2
DEF AUDVOL_VIN_RIGHT EQU %00001000 ; SO1

; --
; -- AUDTERM/NR51 ($FF25)
; -- Selection of Sound output terminal (R/W)
; --
; -- Bit 7   - Output channel 4 to SO2 terminal (left)
; -- Bit 6   - Output channel 3 to SO2 terminal (left)
; -- Bit 5   - Output channel 2 to SO2 terminal (left)
; -- Bit 4   - Output channel 1 to SO2 terminal (left)
; -- Bit 3   - Output channel 4 to SO1 terminal (right)
; -- Bit 2   - Output channel 3 to SO1 terminal (right)
; -- Bit 1   - Output channel 2 to SO1 terminal (right)
; -- Bit 0   - Output channel 1 to SO1 terminal (right)
; --
DEF rNR51 EQU $FF25
DEF rAUDTERM EQU rNR51

; SO2
DEF AUDTERM_4_LEFT  EQU %10000000
DEF AUDTERM_3_LEFT  EQU %01000000
DEF AUDTERM_2_LEFT  EQU %00100000
DEF AUDTERM_1_LEFT  EQU %00010000
; SO1
DEF AUDTERM_4_RIGHT EQU %00001000
DEF AUDTERM_3_RIGHT EQU %00000100
DEF AUDTERM_2_RIGHT EQU %00000010
DEF AUDTERM_1_RIGHT EQU %00000001

; --
; -- AUDENA/NR52 ($FF26)
; -- Sound on/off (R/W)
; --
; -- Bit 7   - All sound on/off (sets all audio regs to 0!)
; -- Bit 3   - Sound 4 ON flag (read only)
; -- Bit 2   - Sound 3 ON flag (read only)
; -- Bit 1   - Sound 2 ON flag (read only)
; -- Bit 0   - Sound 1 ON flag (read only)
; --
DEF rNR52 EQU $FF26
DEF rAUDENA EQU rNR52

DEF AUDENA_ON    EQU %10000000
DEF AUDENA_OFF   EQU %00000000  ; sets all audio regs to 0!

; --
; -- LCDC ($FF40)
; -- LCD Control (R/W)
; --
DEF rLCDC EQU $FF40

DEF LCDCF_OFF     EQU %00000000 ; LCD Control Operation
DEF LCDCF_ON      EQU %10000000 ; LCD Control Operation
DEF LCDCF_WIN9800 EQU %00000000 ; Window Tile Map Display Select
DEF LCDCF_WIN9C00 EQU %01000000 ; Window Tile Map Display Select
DEF LCDCF_WINOFF  EQU %00000000 ; Window Display
DEF LCDCF_WINON   EQU %00100000 ; Window Display
DEF LCDCF_BLK21   EQU %00000000 ; BG & Window Tile Data Select
DEF LCDCF_BLK01   EQU %00010000 ; BG & Window Tile Data Select
DEF LCDCF_BG9800  EQU %00000000 ; BG Tile Map Display Select
DEF LCDCF_BG9C00  EQU %00001000 ; BG Tile Map Display Select
DEF LCDCF_OBJ8    EQU %00000000 ; OBJ Construction
DEF LCDCF_OBJ16   EQU %00000100 ; OBJ Construction
DEF LCDCF_OBJOFF  EQU %00000000 ; OBJ Display
DEF LCDCF_OBJON   EQU %00000010 ; OBJ Display
DEF LCDCF_BGOFF   EQU %00000000 ; BG Display
DEF LCDCF_BGON    EQU %00000001 ; BG Display

DEF LCDCB_ON      EQU 7 ; LCD Control Operation
DEF LCDCB_WIN9C00 EQU 6 ; Window Tile Map Display Select
DEF LCDCB_WINON   EQU 5 ; Window Display
DEF LCDCB_BLKS    EQU 4 ; BG & Window Tile Data Select
DEF LCDCB_BG9C00  EQU 3 ; BG Tile Map Display Select
DEF LCDCB_OBJ16   EQU 2 ; OBJ Construction
DEF LCDCB_OBJON   EQU 1 ; OBJ Display
DEF LCDCB_BGON    EQU 0 ; BG Display
; "Window Character Data Select" follows BG

; --
; -- STAT ($FF41)
; -- LCDC Status   (R/W)
; --
DEF rSTAT EQU $FF41

DEF STATF_LYC     EQU  %01000000 ; LYC=LY Coincidence (Selectable)
DEF STATF_MODE10  EQU  %00100000 ; Mode 10
DEF STATF_MODE01  EQU  %00010000 ; Mode 01 (V-Blank)
DEF STATF_MODE00  EQU  %00001000 ; Mode 00 (H-Blank)
DEF STATF_LYCF    EQU  %00000100 ; Coincidence Flag
DEF STATF_HBL     EQU  %00000000 ; H-Blank
DEF STATF_VBL     EQU  %00000001 ; V-Blank
DEF STATF_OAM     EQU  %00000010 ; OAM-RAM is used by system
DEF STATF_LCD     EQU  %00000011 ; Both OAM and VRAM used by system
DEF STATF_BUSY    EQU  %00000010 ; When set, VRAM access is unsafe

DEF STATB_LYC     EQU  6
DEF STATB_MODE10  EQU  5
DEF STATB_MODE01  EQU  4
DEF STATB_MODE00  EQU  3
DEF STATB_LYCF    EQU  2
DEF STATB_BUSY    EQU  1

; --
; -- SCY ($FF42)
; -- Scroll Y (R/W)
; --
DEF rSCY EQU $FF42

; --
; -- SCX ($FF43)
; -- Scroll X (R/W)
; --
DEF rSCX EQU $FF43

; --
; -- LY ($FF44)
; -- LCDC Y-Coordinate (R)
; --
; -- Values range from 0->153. 144->153 is the VBlank period.
; --
DEF rLY EQU $FF44

; --
; -- LYC ($FF45)
; -- LY Compare (R/W)
; --
; -- When LY==LYC, STATF_LYCF will be set in STAT
; --
DEF rLYC EQU $FF45

; --
; -- DMA ($FF46)
; -- DMA Transfer and Start Address (W)
; --
DEF rDMA EQU $FF46

; --
; -- BGP ($FF47)
; -- BG Palette Data (W)
; --
; -- Bit 7-6 - Intensity for %11
; -- Bit 5-4 - Intensity for %10
; -- Bit 3-2 - Intensity for %01
; -- Bit 1-0 - Intensity for %00
; --
DEF rBGP EQU $FF47

; --
; -- OBP0 ($FF48)
; -- Object Palette 0 Data (W)
; --
; -- See BGP for info
; --
DEF rOBP0 EQU $FF48

; --
; -- OBP1 ($FF49)
; -- Object Palette 1 Data (W)
; --
; -- See BGP for info
; --
DEF rOBP1 EQU $FF49

; --
; -- WY ($FF4A)
; -- Window Y Position (R/W)
; --
; -- 0 <= WY <= 143
; -- When WY = 0, the window is displayed from the top edge of the LCD screen.
; --
DEF rWY EQU $FF4A

; --
; -- WX ($FF4B)
; -- Window X Position (R/W)
; --
; -- 7 <= WX <= 166
; -- When WX = 7, the window is displayed from the left edge of the LCD screen.
; -- Values of 0-6 and 166 are unreliable due to hardware bugs.
; --
DEF rWX EQU $FF4B

DEF WX_OFS EQU 7 ; add this to a screen position to get a WX position

; --
; -- SPEED ($FF4D)
; -- Select CPU Speed (R/W)
; --
DEF rKEY1 EQU $FF4D
DEF rSPD  EQU rKEY1

DEF KEY1F_DBLSPEED EQU %10000000 ; 0=Normal Speed, 1=Double Speed (R)
DEF KEY1F_PREPARE  EQU %00000001 ; 0=No, 1=Prepare (R/W)

; --
; -- VBK ($FF4F)
; -- Select Video RAM Bank (R/W)
; --
; -- Bit 0 - Bank Specification (0: Specify Bank 0; 1: Specify Bank 1)
; --
DEF rVBK EQU $FF4F

; --
; -- HDMA1 ($FF51)
; -- High byte for Horizontal Blanking/General Purpose DMA source address (W)
; -- CGB Mode Only
; --
DEF rHDMA1 EQU $FF51

; --
; -- HDMA2 ($FF52)
; -- Low byte for Horizontal Blanking/General Purpose DMA source address (W)
; -- CGB Mode Only
; --
DEF rHDMA2 EQU $FF52

; --
; -- HDMA3 ($FF53)
; -- High byte for Horizontal Blanking/General Purpose DMA destination address (W)
; -- CGB Mode Only
; --
DEF rHDMA3 EQU $FF53

; --
; -- HDMA4 ($FF54)
; -- Low byte for Horizontal Blanking/General Purpose DMA destination address (W)
; -- CGB Mode Only
; --
DEF rHDMA4 EQU $FF54

; --
; -- HDMA5 ($FF55)
; -- Transfer length (in tiles minus 1)/mode/start for Horizontal Blanking, General Purpose DMA (R/W)
; -- CGB Mode Only
; --
DEF rHDMA5 EQU $FF55

DEF HDMA5F_MODE_GP  EQU %00000000 ; General Purpose DMA (W)
DEF HDMA5F_MODE_HBL EQU %10000000 ; HBlank DMA (W)
DEF HDMA5B_MODE EQU 7 ; DMA mode select (W)

; -- Once DMA has started, use HDMA5F_BUSY to check when the transfer is complete
DEF HDMA5F_BUSY EQU %10000000 ; 0=Busy (DMA still in progress), 1=Transfer complete (R)

; --
; -- RP ($FF56)
; -- Infrared Communications Port (R/W)
; -- CGB Mode Only
; --
DEF rRP EQU $FF56

DEF RPF_ENREAD   EQU %11000000
DEF RPF_DATAIN   EQU %00000010 ; 0=Receiving IR Signal, 1=Normal
DEF RPF_WRITE_HI EQU %00000001
DEF RPF_WRITE_LO EQU %00000000

DEF RPB_LED_ON   EQU 0
DEF RPB_DATAIN   EQU 1

; --
; -- BCPS/BGPI ($FF68)
; -- Background Color Palette Specification (aka Background Palette Index) (R/W)
; --
DEF rBCPS EQU $FF68
DEF rBGPI EQU rBCPS

DEF BCPSF_AUTOINC EQU %10000000 ; Auto Increment (0=Disabled, 1=Increment after Writing)
DEF BCPSB_AUTOINC EQU 7
DEF BGPIF_AUTOINC EQU BCPSF_AUTOINC
DEF BGPIB_AUTOINC EQU BCPSB_AUTOINC

; --
; -- BCPD/BGPD ($FF69)
; -- Background Color Palette Data (aka Background Palette Data) (R/W)
; --
DEF rBCPD EQU $FF69
DEF rBGPD EQU rBCPD

; --
; -- OCPS/OBPI ($FF6A)
; -- Object Color Palette Specification (aka Object Background Palette Index) (R/W)
; --
DEF rOCPS EQU $FF6A
DEF rOBPI EQU rOCPS

DEF OCPSF_AUTOINC EQU %10000000 ; Auto Increment (0=Disabled, 1=Increment after Writing)
DEF OCPSB_AUTOINC EQU 7
DEF OBPIF_AUTOINC EQU OCPSF_AUTOINC
DEF OBPIB_AUTOINC EQU OCPSB_AUTOINC

; --
; -- OCPD/OBPD ($FF6B)
; -- Object Color Palette Data (aka Object Background Palette Data) (R/W)
; --
DEF rOCPD EQU $FF6B
DEF rOBPD EQU rOCPD

; --
; -- SMBK/SVBK ($FF70)
; -- Select Main RAM Bank (R/W)
; --
; -- Bit 2-0 - Bank Specification (0,1: Specify Bank 1; 2-7: Specify Banks 2-7)
; --
DEF rSVBK EQU $FF70
DEF rSMBK EQU rSVBK

; --
; -- PCM12 ($FF76)
; -- Sound channel 1&2 PCM amplitude (R)
; --
; -- Bit 7-4 - Copy of sound channel 2's PCM amplitude
; -- Bit 3-0 - Copy of sound channel 1's PCM amplitude
; --
DEF rPCM12 EQU $FF76

; --
; -- PCM34 ($FF77)
; -- Sound channel 3&4 PCM amplitude (R)
; --
; -- Bit 7-4 - Copy of sound channel 4's PCM amplitude
; -- Bit 3-0 - Copy of sound channel 3's PCM amplitude
; --
DEF rPCM34 EQU $FF77

; --
; -- IE ($FFFF)
; -- Interrupt Enable (R/W)
; --
DEF rIE EQU $FFFF

DEF IEF_HILO   EQU %00010000 ; Transition from High to Low of Pin number P10-P13
DEF IEF_SERIAL EQU %00001000 ; Serial I/O transfer end
DEF IEF_TIMER  EQU %00000100 ; Timer Overflow
DEF IEF_STAT   EQU %00000010 ; STAT
DEF IEF_VBLANK EQU %00000001 ; V-Blank

DEF IEB_HILO   EQU 4
DEF IEB_SERIAL EQU 3
DEF IEB_TIMER  EQU 2
DEF IEB_STAT   EQU 1
DEF IEB_VBLANK EQU 0

;***************************************************************************
;*
;* Flags common to multiple sound channels
;*
;***************************************************************************

; --
; -- Square wave duty cycle
; --
; -- Can be used with AUD1LEN and AUD2LEN
; -- See AUD1LEN for more info
; --
DEF AUDLEN_DUTY_12_5    EQU %00000000 ; 12.5%
DEF AUDLEN_DUTY_25      EQU %01000000 ; 25%
DEF AUDLEN_DUTY_50      EQU %10000000 ; 50%
DEF AUDLEN_DUTY_75      EQU %11000000 ; 75%

; --
; -- Audio envelope flags
; --
; -- Can be used with AUD1ENV, AUD2ENV, AUD4ENV
; -- See AUD1ENV for more info
; --
DEF AUDENV_UP           EQU %00001000
DEF AUDENV_DOWN         EQU %00000000

; --
; -- Audio trigger flags
; --
; -- Can be used with AUD1HIGH, AUD2HIGH, AUD3HIGH
; -- See AUD1HIGH for more info
; --
DEF AUDHIGH_RESTART     EQU %10000000
DEF AUDHIGH_LENGTH_ON   EQU %01000000
DEF AUDHIGH_LENGTH_OFF  EQU %00000000

;***************************************************************************
;*
;* CPU values on bootup (a=type, b=qualifier)
;*
;***************************************************************************

DEF BOOTUP_A_DMG    EQU $01 ; Dot Matrix Game
DEF BOOTUP_A_CGB    EQU $11 ; Color GameBoy
DEF BOOTUP_A_MGB    EQU $FF ; Mini GameBoy (Pocket GameBoy)

; if a=BOOTUP_A_CGB, bit 0 in b can be checked to determine if real CGB or
; other system running in GBC mode
DEF BOOTUP_B_CGB    EQU %00000000
DEF BOOTUP_B_AGB    EQU %00000001   ; GBA, GBA SP, Game Boy Player, or New GBA SP

;***************************************************************************
;*
;* Header
;*
;***************************************************************************

;*
;* Nintendo scrolling logo
;* (Code won't work on a real GameBoy)
;* (if next lines are altered.)
MACRO NINTENDO_LOGO
    DB  $CE,$ED,$66,$66,$CC,$0D,$00,$0B,$03,$73,$00,$83,$00,$0C,$00,$0D
    DB  $00,$08,$11,$1F,$88,$89,$00,$0E,$DC,$CC,$6E,$E6,$DD,$DD,$D9,$99
    DB  $BB,$BB,$67,$63,$6E,$0E,$EC,$CC,$DD,$DC,$99,$9F,$BB,$B9,$33,$3E
ENDM

; $0143 Color GameBoy compatibility code
DEF CART_COMPATIBLE_DMG     EQU $00
DEF CART_COMPATIBLE_DMG_GBC EQU $80
DEF CART_COMPATIBLE_GBC     EQU $C0

; $0146 GameBoy/Super GameBoy indicator
DEF CART_INDICATOR_GB       EQU $00
DEF CART_INDICATOR_SGB      EQU $03

; $0147 Cartridge type
DEF CART_ROM                     EQU $00
DEF CART_ROM_MBC1                EQU $01
DEF CART_ROM_MBC1_RAM            EQU $02
DEF CART_ROM_MBC1_RAM_BAT        EQU $03
DEF CART_ROM_MBC2                EQU $05
DEF CART_ROM_MBC2_BAT            EQU $06
DEF CART_ROM_RAM                 EQU $08
DEF CART_ROM_RAM_BAT             EQU $09
DEF CART_ROM_MMM01               EQU $0B
DEF CART_ROM_MMM01_RAM           EQU $0C
DEF CART_ROM_MMM01_RAM_BAT       EQU $0D
DEF CART_ROM_MBC3_BAT_RTC        EQU $0F
DEF CART_ROM_MBC3_RAM_BAT_RTC    EQU $10
DEF CART_ROM_MBC3                EQU $11
DEF CART_ROM_MBC3_RAM            EQU $12
DEF CART_ROM_MBC3_RAM_BAT        EQU $13
DEF CART_ROM_MBC5                EQU $19
DEF CART_ROM_MBC5_BAT            EQU $1A
DEF CART_ROM_MBC5_RAM_BAT        EQU $1B
DEF CART_ROM_MBC5_RUMBLE         EQU $1C
DEF CART_ROM_MBC5_RAM_RUMBLE     EQU $1D
DEF CART_ROM_MBC5_RAM_BAT_RUMBLE EQU $1E
DEF CART_ROM_MBC7_RAM_BAT_GYRO   EQU $22
DEF CART_ROM_POCKET_CAMERA       EQU $FC
DEF CART_ROM_BANDAI_TAMA5        EQU $FD
DEF CART_ROM_HUDSON_HUC3         EQU $FE
DEF CART_ROM_HUDSON_HUC1         EQU $FF

; $0148 ROM size
; these are kilobytes
DEF CART_ROM_32KB   EQU $00 ; 2 banks
DEF CART_ROM_64KB   EQU $01 ; 4 banks
DEF CART_ROM_128KB  EQU $02 ; 8 banks
DEF CART_ROM_256KB  EQU $03 ; 16 banks
DEF CART_ROM_512KB  EQU $04 ; 32 banks
DEF CART_ROM_1024KB EQU $05 ; 64 banks
DEF CART_ROM_2048KB EQU $06 ; 128 banks
DEF CART_ROM_4096KB EQU $07 ; 256 banks
DEF CART_ROM_8192KB EQU $08 ; 512 banks
DEF CART_ROM_1152KB EQU $52 ; 72 banks
DEF CART_ROM_1280KB EQU $53 ; 80 banks
DEF CART_ROM_1536KB EQU $54 ; 96 banks

; $0149 SRAM size
; these are kilobytes
DEF CART_SRAM_NONE  EQU 0
DEF CART_SRAM_8KB   EQU 2 ; 1 bank
DEF CART_SRAM_32KB  EQU 3 ; 4 banks
DEF CART_SRAM_128KB EQU 4 ; 16 banks

; $014A Destination code
DEF CART_DEST_JAPANESE     EQU $00
DEF CART_DEST_NON_JAPANESE EQU $01

;***************************************************************************
;*
;* Keypad related
;*
;***************************************************************************

DEF PADF_DOWN   EQU $80
DEF PADF_UP     EQU $40
DEF PADF_LEFT   EQU $20
DEF PADF_RIGHT  EQU $10
DEF PADF_START  EQU $08
DEF PADF_SELECT EQU $04
DEF PADF_B      EQU $02
DEF PADF_A      EQU $01

DEF PADB_DOWN   EQU $7
DEF PADB_UP     EQU $6
DEF PADB_LEFT   EQU $5
DEF PADB_RIGHT  EQU $4
DEF PADB_START  EQU $3
DEF PADB_SELECT EQU $2
DEF PADB_B      EQU $1
DEF PADB_A      EQU $0

;***************************************************************************
;*
;* Screen related
;*
;***************************************************************************

DEF SCRN_X    EQU 160 ; Width of screen in pixels
DEF SCRN_Y    EQU 144 ; Height of screen in pixels. Also corresponds to the value in LY at the beginning of VBlank.
DEF SCRN_X_B  EQU 20  ; Width of screen in bytes
DEF SCRN_Y_B  EQU 18  ; Height of screen in bytes

DEF SCRN_VX   EQU 256 ; Virtual width of screen in pixels
DEF SCRN_VY   EQU 256 ; Virtual height of screen in pixels
DEF SCRN_VX_B EQU 32  ; Virtual width of screen in bytes
DEF SCRN_VY_B EQU 32  ; Virtual height of screen in bytes

;***************************************************************************
;*
;* OAM related
;*
;***************************************************************************

; OAM attributes
; each entry in OAM RAM is 4 bytes (sizeof_OAM_ATTRS)
RSRESET
DEF OAMA_Y              RB  1   ; y pos plus 16
DEF OAMA_X              RB  1   ; x pos plus 8
DEF OAMA_TILEID         RB  1   ; tile id
DEF OAMA_FLAGS          RB  1   ; flags (see below)
DEF sizeof_OAM_ATTRS    RB  0

DEF OAM_Y_OFS EQU 16 ; add this to a screen-relative Y position to get an OAM Y position
DEF OAM_X_OFS EQU 8  ; add this to a screen-relative X position to get an OAM X position

DEF OAM_COUNT           EQU 40  ; number of OAM entries in OAM RAM

; flags
DEF OAMF_PRI        EQU %10000000 ; Priority
DEF OAMF_YFLIP      EQU %01000000 ; Y flip
DEF OAMF_XFLIP      EQU %00100000 ; X flip
DEF OAMF_PAL0       EQU %00000000 ; Palette number; 0,1 (DMG)
DEF OAMF_PAL1       EQU %00010000 ; Palette number; 0,1 (DMG)
DEF OAMF_BANK0      EQU %00000000 ; Bank number; 0,1 (GBC)
DEF OAMF_BANK1      EQU %00001000 ; Bank number; 0,1 (GBC)

DEF OAMF_PALMASK    EQU %00000111 ; Palette (GBC)

DEF OAMB_PRI        EQU 7 ; Priority
DEF OAMB_YFLIP      EQU 6 ; Y flip
DEF OAMB_XFLIP      EQU 5 ; X flip
DEF OAMB_PAL1       EQU 4 ; Palette number; 0,1 (DMG)
DEF OAMB_BANK1      EQU 3 ; Bank number; 0,1 (GBC)

; Deprecated constants. Please avoid using.

DEF IEF_LCDC   EQU %00000010 ; LCDC (see STAT)
DEF _VRAM8000  EQU _VRAM
DEF _VRAM8800  EQU _VRAM+$800
DEF _VRAM9000  EQU _VRAM+$1000
DEF CART_SRAM_2KB   EQU 1 ; 1 incomplete bank
DEF LCDCF_BG8800  EQU %00000000 ; BG & Window Tile Data Select
DEF LCDCF_BG8000  EQU %00010000 ; BG & Window Tile Data Select
DEF LCDCB_BG8000  EQU 4 ; BG & Window Tile Data Select

    ENDC ;HARDWARE_INC


code:
; joypad buttons
	const_def
	const BIT_D_RIGHT  ; 0
	const BIT_D_LEFT   ; 1
	const BIT_D_UP     ; 2
	const BIT_D_DOWN   ; 3
	const BIT_A_BUTTON ; 4
	const BIT_B_BUTTON ; 5
	const BIT_SELECT   ; 6
	const BIT_START    ; 7

DEF NO_INPUT   EQU %00000000
DEF D_RIGHT  EQU 1 << BIT_D_RIGHT  ; $01
DEF D_LEFT   EQU 1 << BIT_D_LEFT   ; $02
DEF D_UP     EQU 1 << BIT_D_UP     ; $04
DEF D_DOWN   EQU 1 << BIT_D_DOWN   ; $08
DEF A_BUTTON EQU 1 << BIT_A_BUTTON ; $10
DEF B_BUTTON EQU 1 << BIT_B_BUTTON ; $20
DEF SELECT   EQU 1 << BIT_SELECT   ; $40
DEF START    EQU 1 << BIT_START    ; $80

DEF D_PAD      EQU D_RIGHT | D_LEFT | D_UP | D_DOWN     ; $0f
DEF BUTTONS    EQU A_BUTTON | B_BUTTON | SELECT | START ; $f0

DEF R_DPAD     EQU %00100000 ; $20
DEF R_BUTTONS  EQU %00010000 ; $10

repo_name: pizdex/survivalkids

license: unknown


code:
INCLUDE "constants.asm"

SECTION "Home", ROM0

INCLUDE "home/header.asm"
INCLUDE "home/bank0.asm"


code:
_Start::
	di
	ld sp, wc100
	ld [wCGB], a
	xor a
	ld [wc10f], a

	call Func_01e5

	ld a, %00001100
	ldh [hff88], a
	ldh [rBGP], a

	di
	xor a
	ldh [rIF], a
	ld [wc140], a
	ldh [hff8f], a
	ld [wc141], a
	inc a ; $01
	ldh [rIE], a

	ld sp, wc100
	ld a, $7f
	ld [wc102], a

	ld a, [wCGB]
	cp BOOTUP_A_CGB
	jr nz, .speed_set
	ld hl, rKEY1
	bit 7, [hl] ; KEY1F_DBLSPEED
	jr nz, .speed_set

; Set Double Speed
	set 0, [hl] ; KEY1F_PREPARE
	xor a
	ldh [rIF], a
	ldh [rIE], a
	ld a, $30
	ldh [rP1], a
	stop

.speed_set:
	ld a, LCDCF_ON | LCDCF_BLK01 | LCDCF_BG9800 | LCDCF_BGON
	ldh [hff84], a
	ldh [rLCDC], a
	farcall Func_0f_503e
	farcall Func_06_7a57

	call WriteOAMDMACodeToHRAM
	call Func_0c9e
	call Func_3042
	call Func_05ce

	ld a, $01
	ldh [hff80], a
	call Func_0c11
	ld a, $03
	ldh [hff80], a
	call Func_0c11
	xor a
	ld [wc131], a

	ei
	call Func_0acc
	call Func_0bf2
	homecall Func_0d_4cbe
	jr nc, .asm_01df
	ld a, $ff
	ld [wc10f], a
	call Func_0d_4d13

.asm_01df
	call Func_0acc
	jp Func_062a

Func_01e5::
	call Func_01ef
	call InitRAM
	call Func_303b
	ret

Func_01ef::
	xor a
	ldh [hffad], a
	ldh [hff98], a
	ldh [hff9d], a
	ldh [hffa2], a
	ldh [hffa7], a
	ldh [hffb4], a
	ldh [hffb9], a
	ret

InitRAM::
	ld a, $01
	ld [rROMB0], a
	ld [wROMBank], a
	xor a ; $00
	ld [rRAMB], a
	ld [wSRAMBank], a

	ld a, $01
	ld [$6000], a
	ld a, CART_SRAM_ENABLE
	ld [rRAMG], a

	ld a, [wCGB]
	cp BOOTUP_A_CGB
	jr nz, .ret

	ld a, $01
	ld [wWRAMBank], a
	ldh [rSVBK], a
.ret
	ret

Func_0227::
	push af
	ld a, [wROMBank]
	ld [$a725], a
	pop af
	push hl
	ld hl, wc103
	set 1, [hl]
	push de
	push bc
	push af
	call Func_02b5
	ld a, [$a725]
	ld [wROMBank], a
	ld [rROMB0], a
	pop af
	pop bc
	pop de
	ld hl, wc103
	res 1, [hl]
	pop hl
	ret

Func_024e::
	dr $024e, $027d

Func_027d::
; Init audio registers
	ld c, LOW(rNR50)
	ld a, %01110111
	ld [c], a
	inc c
	ld a, %11111111
	ld [c], a ; rNR51
	ld [$a70f], a
	inc c
	ld a, AUDENA_ON
	ld [c], a ; rNR52

	ld h, $a0
	ld a, $11
	call .asm_02aa
	ld a, $1b
	call .asm_02aa
	ld a, $20
	call .asm_02aa
	ld a, $11
	call .asm_02aa
	ld a, $16
	call .asm_02aa
	ld a, $1b
.asm_02aa:
	ld l, $1b
	ld [hli], a
	inc a
	ld [hli], a
	inc a
	ld [hli], a
	inc a
	ld [hli], a
	inc h
	ret

Func_02b5::
	ld [$a709], a
	or a
	jr nz, .asm_02cd

	ld [$a726], a
	ld a, BANK(Func_1d_48fb)
	ld [wROMBank], a
	ld [rROMB0], a
	jp Func_1d_48fb

.asm_02c9
	ld [$a71c], a
	ret

.asm_02cd:
	dr $02cd, $0425

Func_0425::
	dr $0425, $05ce

Func_05ce::
	call InitIO
	ldh a, [hff84]
	and $e7
	or $44
	ldh [hff84], a
	call Func_027d

	xor a
	ld [wc146], a
	ld [wc16c], a
	ld [wc16d], a
	ld [wc160], a
	ld [wc161], a
	ld [wc162], a
	ld [wc163], a
	ld [wc164], a
	ld [wc165], a
	ld [wc166], a
	ld [wc167], a
	ld [wc168], a
	ld [wc169], a
	ld [wc16a], a
	ld [wc16b], a
	ret

InitIO::
	ld hl, .io_data
.copy
	ld a, [hli] ; get addr
	ld c, a
	ld a, [hli] ; get value
	ld [c], a
	inc c
	jr nz, .copy
	ret

.io_data
	db LOW(rP1), $00
	db LOW(rSB), $00
	db LOW(rSC), $00
	db LOW(rDIV), $00
	db LOW(rTIMA), $00
	db LOW(rTMA), $c0
	db LOW(rTAC), $00
	db LOW(rSTAT), %01000000 ; STATF_LYC?
	db LOW(rLYC), 0
	db LOW(rIE), %00000001 ; IEF_VBLANK?

Func_062a::
	xor a
	ld [wc114], a
	ld [wc113], a
	call Func_06a3
	call Func_0c11
	call ReadJoypad
	call Func_063f
	jr Func_062a

Func_063f::
	ld hl, hff80
.loop
	bit 0, [hl]
	jr nz, .asm_064a
	halt
	nop
	jr .loop

.asm_064a
	ld a, $03
	xor [hl]
	ld [hl], a
	ret

INCLUDE "home/joypad.asm"

Func_06a3::
	ld hl, wc16c
	inc [hl]
	jr nc, .asm_06ab
	inc hl
	inc [hl]

.asm_06ab:
	call Func_2ff8
	ld a, [wc160]
	call Func_0b1d

.table
	dab Func_06_605b
	dab Func_0d_422d
	dab Func_06_6083
	dab Func_0711
	dab Func_05_5c72

Func_06c3:
	ld a, $2b
	call BankswitchHome
	ld hl, $4000
	call Func_0987
	call Func_0acc
	call Func_0bf2
	ld a, 0
	call Func_2ef9
	ld a, $04
	jp Func_06ee

Func_06de::
	ld hl, wc165
	xor a
REPT 5
	ld [hld], a
ENDR
	inc [hl]
	ld a, $02
	ld [wc131], a
	ret

Func_06ee::
	ld [wc160], a
	xor a
	ld [wc161], a
	ld [wc162], a
	ld [wc163], a
	ld [wc164], a
	ld [wc165], a
	ld a, $02
	ld [wc131], a
	ret

Func_0707::
	ld hl, wc165
	xor a
REPT 4
	ld [hld], a
ENDR
	inc [hl]
	ret

Func_0711::
	dr $0711, $072d

Func_072d::
	rst JumptableRST

.table
	dw Func_0736 ; $00
	dw Func_241b ; $01
	dw Func_07ac ; $02
	dw Func_07a5 ; $03

Func_0736::
	farcall Func_06_6785
	ret

Func_073d::
	ld [wc161], a
	xor a
	ld [wc162], a
	ld [wc163], a
	ld [wc164], a
	ld [wc165], a
	ret

Func_074e::
	ld hl, wd902
	ld b, $14
	ld c, $0c
.asm_0755:
	bit 7, [hl]
	jr z, .asm_0760
	push bc
	push hl
	call Func_0767
	pop hl
	pop bc

.asm_0760:
	ld a, c
	add l
	ld l, a
	dec b
	jr nz, .asm_0755
	ret

Func_0767::
	ld a, [hld]
	and $3f
	dec hl
	call Func_0b1d

.table
	dab ret_07a4
	dwb $4ecf, $0e
	dwb $4f3e, $0e
	dwb $7267, $0f
	dwb $5282, $0e
	dab ret_07a4
	dwb $52ce, $0e
	dwb $6fac, $0b
	dwb $6e8e, $0f
	dwb $5322, $0e
	dwb $532e, $0e
	dwb $6392, $0b
	dab ret_07a4
	dwb $6996, $0f
	dwb $47ca, $0b
	dwb $5835, $0f
	dwb $5fa2, $0f
	dwb $4506, $24

ret_07a4::
	ret

Func_07a5::
	farcall Func_0e_57c3
	ret

Func_07ac::
	ld a, [wc162]
	rst JumptableRST

.table
	dw Func_07ba
	dw $36c9

Func_07b6::
	ld a, 0
	ld [wc162], a
	ret

Func_07ba::
	dr $07ba, $0902

Func_0902::
	dr $0902, $0987

Func_0987::
	dr $0987, $09c5

Func_09c5:
	ld a, [hli]
	ld e, a
	ld a, [hli]
	ld d, a
	ld a, $ff
	cp e
	jr nz, .asm_09d0
	cp d
	ret z

.asm_09d0:
	ld a, [hli]
	ld c, a
	ld a, [hli]
	ld b, a
	push hl
	ld h, d
	ld l, e
	call Func_09dd
	pop hl
	jr Func_09c5

Func_09dd::
	dr $09dd, $0a24

Func_0a24::
	dr $0a24, $0ac5

BankswitchHome::
; Switches to bank # in a
; Only use this when in the home bank!
	ld [wROMBank], a
	ld [rROMB0], a
	ret

Func_0acc::
	push af
	ld a, $01

Func_0acf::
	ld [wROMBank], a
	ld [rROMB0], a
	pop af
	ret

Func_0ad7::
	push af
	ld a, $02
	jr Func_0acf

Func_0adc::
	push af
	ld a, $03
	jr Func_0acf

Func_0ae1::
	push af
	ld a, $04
	jr Func_0acf

Func_0ae6::
	push af
	ld a, $05
	jr Func_0acf

Func_0aeb::
	push af
	ld a, $06
	jr Func_0acf

Func_0af0::
	push af
	ld a, $07
	jr Func_0acf

Func_0af5::
	push af
	ld a, $08
	jr Func_0acf

Func_0afa::
	push af
	ld a, $09
	jr Func_0acf

Func_0aff::
	push af
	ld a, $0a
	jr Func_0acf

Func_0b04::
	push af
	ld a, $0b
	jr Func_0acf

Func_0b09::
	push af
	ld a, $0c
	jr Func_0acf

Func_0b0e::
	push af
	ld a, $0d
	jr Func_0acf

Func_0b13::
	push af
	ld a, $0e
	jr Func_0acf

Func_0b18::
	push af
	ld a, $0f
	jr Func_0acf

Func_0b1d::
; FarJumptable?
	push af
	ld a, l
	ld [wc107], a
	ld a, h
	ld [wc107 + 1], a
	pop af

	push de
	ld hl, sp+$02
	ld e, [hl]
	inc hl
	ld d, [hl]
	ld [hl], HIGH(Func_0b43)
	dec hl
	ld [hl], LOW(Func_0b43)
	ld h, d
	ld l, a
	add a
	jr nc, .asm_0b38
	inc h

.asm_0b38
	add l
	jr nc, .asm_0b3c
	inc h

.asm_0b3c
	add e
	ld l, a
	jr nc, .asm_0b41
	inc h

.asm_0b41
	pop de
	ret

Func_0b43::
	ld [wc104], a
	ld a, e
	ld [wc105], a
	ld a, d
	ld [wc105 + 1], a
	push hl

	ld a, [wc102]
	ld l, a
	dec a
	ld [wc102], a
	ld h, $db
	ld a, [wROMBank]
	ld [hl], a

	pop hl
	ld a, [hli]
	ld [wc109], a
	ld a, [hli]
	ld [wc109 + 1], a
	ld a, [hl]
	call BankswitchHome
	call FarcallSetup

	push af
	push hl
	ld a, [wc102]
	inc a
	ld [wc102], a
	ld l, a
	ld h, $db
	ld a, [hl]
	call BankswitchHome
	pop hl
	pop af
	ret

Farcall::
	; Save registers in WRAM (they cba with stack)
	ld [wc104], a
	ld a, e
	ld [wc105], a
	ld a, d
	ld [wc105 + 1], a
	ld a, l
	ld [wc107], a
	ld a, h
	ld [wc107 + 1], a

	ld a, [wc102]
	ld l, a
	dec a
	ld [wc102], a
	ld h, $db
	ld a, [wROMBank]
	ld [hl], a

	ld hl, sp+$00
	ld e, [hl]
	inc hl
	ld d, [hl]
	ld a, [de]
	inc de
	ld [wc109], a
	ld a, [de]
	inc de
	ld [wc109 + 1], a
	ld a, [de]
	inc de
	ld [hl], d
	dec hl
	ld [hl], e
	call BankswitchHome
	call FarcallSetup

	push af
	push hl
	ld a, [wc102]
	inc a
	ld [wc102], a
	ld l, a
	ld h, $db
	ld a, [hl]
	call BankswitchHome
	pop hl
	pop af
	ret

FarcallSetup::
; Restore saved registers and jump to target address
	ld a, [wc109]
	ld l, a
	ld a, [wc109 + 1]
	ld h, a
	push hl

	ld a, [wc105]
	ld e, a
	ld a, [wc105 + 1]
	ld d, a
	ld a, [wc107]
	ld l, a
	ld a, [wc107 + 1]
	ld h, a
	ld a, [wc104]
	ret

BankswitchSRAM::
	ld [wSRAMBank], a
	ld [rRAMB], a
	ret

Func_0bf2::
	push af
	xor a

Func_0bf4::
	ld [wSRAMBank], a
	ld [rRAMB], a
	pop af
	ret

Func_0bfc::
	push af
	ld a, $01
	jr Func_0bf4

Func_0c01::
	push af
	ld a, $02
	jr Func_0bf4

Func_0c06::
	push af
	ld a, $03
	jr Func_0bf4

BankswitchWRAM::
	ld [wWRAMBank], a
	ldh [rSVBK], a
	ret

Func_0c11::
	ldh a, [hff80]
	rra
	rra
	jr c, .asm_0c20

	ld hl, hff84
	ld de, wc124
	jp wFunc_CopyBytesUnrolled + (($28 - 9) * 3) ; copy 9 bytes

.asm_0c20
	ld hl, hff84
	ld de, wc118
	jp wFunc_CopyBytesUnrolled + (($28 - 9) * 3) ; copy 9 bytes

Func_0c29::
	dr $0c29, $0c97

Func_0c97::
	ld a, l
	ldh [hff86], a
	ld a, h
	ldh [hff87], a
	ret

Func_0c9e::
	ld hl, $0000
	call Func_0c97
	ld hl, $0790 ; window coords

Func_0ca7::
	ld a, l
	ldh [hff8b], a
	ld a, h
	ldh [hff8c], a
	ret

Func_0cae::
	dr $0cae, $0d45

Func_0d45::
	dr $0d45, $0da1

Func_0da1::
	ldh a, [rLCDC]
	and $08
	srl a
	jr Func_0da9.asm_0daf

Func_0da9::
	ldh a, [rLCDC]
	and $40
	swap a

.asm_0daf:
	ld hl, $9800
	add h
	ld h, a
	ld a, b
	ld b, 0
	add hl, bc
	ld b, a
	ld c, 0
REPT 3
	srl b
	rr c
ENDR
	add hl, bc
	ret

Func_0dc9::
	ld a, [wCGB]
	cp BOOTUP_A_CGB
	ret nz

	ld a, [wROMBank]
	push af
	push hl
	ld a, [hli]
	ld b, a
	ld a, [hli]
	ld h, [hl]
	ld l, a
	ld a, b
	call BankswitchHome
	ld de, wd030
	ld c, $40
	call wFunc_CopyBytes
	pop hl
	pop af
	call BankswitchHome

	push af
	inc hl
	inc hl
	inc hl
	ld a, [hli]
	ld b, a
	ld a, [hli]
	ld h, [hl]
	ld l, a
	ld a, b
	call BankswitchHome

	ld de, wd070
	ld c, $40
	call wFunc_CopyBytes
	pop af
	jp BankswitchHome

Func_0e03::
	dr $0e03, $0e57

Func_0e57::
	dr $0e57, $1071

Func_1071::
	dr $1071, $1103

Jumptable::
	push hl
	push de
	; Get address of table (return pointer)
	ld hl, sp+$04
	ld e, [hl]
	inc hl
	ld d, [hl]

	; de = [de + (a*2)]
	ld l, a
	ld h, 0
	add hl, hl
	add hl, de
	ld e, [hl]
	inc hl
	ld d, [hl]

	; Put pointer onto stack and ret
	ld hl, sp+$04
	ld [hl], e
	inc hl
	ld [hl], d
	pop de
	pop hl
	ret

INCLUDE "home/load_oam.asm"

Func_113a::
	dr $113a, $131c

Func_131c::
	dr $131c, $1b4a

Func_1b4a::
	dr $1b4a, $1bee

Func_1bee::
	dr $1bee, $1dbe

Func_1dbe::
	dr $1dbe, $221d

Func_221d::
	dr $221d, $241b

Func_241b::
	dr $241b, $24a2

Func_24a2::
	dr $24a2, $29ec

Func_29ec::
	dr $29ec, $29f5

Func_29f5::
	dr $29f5, $2a89

Func_2a89::
	dr $2a89, $2c50

Func_2c50::
	ld hl, wc430
	ld b, $06
	jp Func_29ec

Func_2c58::
	push bc
	push de
	push hl
	push hl
	pop de
	ld hl, wc430
	ld c, a
	ld b, $08
.asm_2c63:
	inc hl
	ld a, [hli]
	or a
	jr nz, .asm_2c71

	dec hl
	dec hl
	ld [hl], e
	inc hl
	ld [hl], d
	inc hl
	ld [hl], c
	jr .asm_2c75

.asm_2c71
	inc hl
	dec b
	jr nz, .asm_2c63

.asm_2c75
	pop hl
	pop de
	pop bc
	ret

Func_2c79::
	dr $2c79, $2ef9

Func_2ef9::
	dr $2ef9, $2fd6

Func_2fd6::
	push af
	di
	ld a, [wROMBank]
	ld [wc10c], a
	ld a, [wSRAMBank]
	ld [wc10d], a
	ei
	call Func_0bf2
	pop af
	call Func_0227
	ld a, [wc10c]
	call BankswitchHome
	ld a, [wc10d]
	jp BankswitchSRAM

Func_2ff8::
	ld a, [wc138]
	ld b, a
	ld a, [wc137]
	ld c, a
	or a
	jr nz, .asm_3006
	or b
	jr z, .asm_3013

.asm_3006:
	dec bc
	ld a, c
	ld [wc137], a
	ld a, b
	ld [wc138], a
	or c
	call z, Func_3033

.asm_3013:
	ld a, [wc135]
	ld b, a
	ld a, [wc134]
	ld c, a
	or a
	jr nz, .asm_3020
	or b
	ret z

.asm_3020:
	dec bc
	ld a, c
	ld [wc134], a
	ld a, b
	ld [wc135], a
	or c
	ret nz
	ld a, [wc133]
	or a
	ret z
	jp Func_2fd6

Func_3033:
	ld a, [wc136]
	or a
	ret z
	jp Func_2fd6

Func_303b::
	xor a
	ld [wc103], a
	ldh [rNR50], a
	ret

Func_3042::
	xor a
	ld [wc133], a
	ld [wc134], a
	ld [wc135], a
	ld [wc136], a
	ld [wc137], a
	ld [wc138], a

	ld hl, $a000
	call .fill
	ld hl, $a100
	call .fill
	ld hl, $a200
	call .fill
	ld hl, $a300
	call .fill
	ld hl, $a400
	call .fill
	ld hl, $a500
	call .fill
	ld hl, $a600
	call .fill
	ld hl, $a700
.fill
	xor a
	ld c, $a0
	jp wFunc_FillBytes

ret_3088::
	ret

Func_3089::
	dr $3089, $313f

Func_313f::
	push af
	push bc
	push de
	push hl
	farcall Func_06_6140

	ld a, [wca4e]
	and $0f
	cp $03
	jr z, .asm_3190
	cp $05
	jr z, .asm_3190
	cp $06
	jr z, .asm_3190

	ld h, $07
	ld l, $68
	call Func_0ca7
	call Func_2c50
	ld hl, $43ac
	ld a, $0a
	call Func_2c58
	ld a, [wROMBank]
	push af
	ld a, [wca4e]
	and $0f
	cp $02
	jr z, .asm_318c

	ld a, $0a
	call BankswitchHome
	call Func_0a_5767
	call Func_0a_7665
	call Func_0a_5674
	ld a, $02
	ld [wca4e], a

.asm_318c:
	pop af
	call BankswitchHome

.asm_3190:
	pop hl
	pop de
	pop bc
	pop af
	ret

Func_3195::
	push af
	push bc
	push de
	push hl
	ld a, h
	ld [wca55], a
	ld a, l
	ld [wca56], a
	ld b, d

.asm_31a2:
	ld c, e
	push de
	push bc
	call Func_0da9
	ld a, [wca72]
	or a
	jr z, .asm_31bc

	pop bc
	push bc
	push hl
	ld c, b
	ld a, $0c
	ld hl, $72ae
	call Func_32a0
	pop hl
	add hl, de

.asm_31bc:
	di
	ldh a, [rSTAT]
	bit 1, a
	jr nz, .asm_31bc

	xor a
	ld [hli], a
	ei
	pop bc
	pop de
	inc c
	push de
	push bc
	ld a, [wca56]
	cp c
	jr nc, .asm_31bc

	pop bc
	pop de
	inc b
	ld a, [wca55]
	cp b
	jr nc, .asm_31a2

	pop hl
	pop de
	pop bc
	pop af
	ret

Func_31df::
	dr $31df, $32a0

Func_32a0::
	dr $32a0, $3586

Func_3586::
	dr $3586, $35e6

Func_35e6::
	dr $35e6, $3653

Func_3653::
	ld a, $03
	ld [wca4e], a
	jr Func_3663

Func_365a::
	xor a
	ld [wcaac], a

Func_365e::
	ld a, $06
	ld [wca4e], a

Func_3663:
	dr $3663, $3690

Func_3690::
	ld a, [wca4e]
	cp $21
	jp z, Func_35e6

	and $0f
	rst JumptableRST

.table
	dw Func_24a2 ; $00
	dw Func_24a2 ; $01
	dw Func_24a2 ; $02
	dw Func_3586 ; $03
	dw Func_24a2 ; $04
	dw Func_3586 ; $05
	dw Func_3586 ; $06

Func_36a9::
	ld a, $01
	ld [wcaac], a
	jp Func_3653

Func_36b1::
	ld a, $02
	ld [wcaac], a
	jp Func_3653

Func_36b9::
	ld a, $01
	ld [wcaac], a
	jp Func_365e

Func_36c1::
	ld a, $02
	ld [wcaac], a
	jp Func_365e

Func_36c9::
	call Func_074e
	call Func_1dbe
	ld a, [wca62]
	call Func_0b1d

.table
	dab Func_0a_484a
	dab Func_03_40d9
	dab Func_0a_488c
	dab Func_0a_6769

Func_36e1::
	dr $36e1, $3dc8

Func_3dc8::
	ld a, [wc16c]
	bit 0, a
	ret z

	ld a, [wc17e]
	bit 7, a
	jp nz, Func_1b4a
	bit 6, a
	jp nz, Func_1bee
	jp hl


code:
; rst vectors (called through the rst instruction)

SECTION "rst0", ROM0[$0000]
JumptableRST::
	jp Jumptable

SECTION "rst8", ROM0[$0008]
	ld a, [hli]
	ld h, [hl]
	ld l, a
	ret

SECTION "rst10", ROM0[$0010]
	cpl
	inc a
	ret z
	add l
	ld l, a
	ret c
	dec h
	ret

SECTION "rst18", ROM0[$0018]
	cpl
	inc a
	ret z
	add e
	ld e, a
	ret c
	dec d
	ret

SECTION "rst20", ROM0[$0020]
	cpl
	inc a
	ret z
	add c
	ld c, a
	ret c
	dec b
	ret

SECTION "rst28", ROM0[$0028]
	add l
	ld l, a
	ret nc
	inc h
	ret

SECTION "rst30", ROM0[$0030]
	add e
	ld e, a
	ret nc
	inc d
	ret

SECTION "rst38", ROM0[$0038]
	add c
	ld c, a
	ret nc
	inc b
	ret

; Game Boy hardware interrupts

SECTION "vblank", ROM0[$0040]
	jr VBlank

SECTION "lcd", ROM0[$0048]
	reti

SECTION "timer", ROM0[$0050]
	reti

SECTION "serial", ROM0[$0058]
	reti

SECTION "joypad", ROM0[$0060]
	reti

SECTION "header misc", ROM0[$0066]

	db $00, $01

VBlank::
	push af
	push bc
	push de
	push hl
	call Func_1071
	ei
	call Func_0078
	pop hl
	pop de
	pop bc
	pop af
	reti

Func_0078:
	ld hl, wc103
	ld a, [hl]
	and 3
	jr nz, .ret

	set 0, [hl]
	ld a, [wSRAMBank]
	push af
	ld a, 0
	ld [rRAMB], a
	call Func_0425
	pop af
	ld [rRAMB], a
	ld hl, wc103
	res 0, [hl]

.ret
	ret

SECTION "Header", ROM0[$0100]

Start::
	nop
	jp _Start

; The Game Boy cartridge header data is patched over by rgbfix.
; This makes sure it doesn't get used for anything else.

	ds $0150 - @, $00


code:
ReadJoypad::
	ld a, [wJoypadDown]
	ld [wJoypadDownBackup], a
	ld a, [wJoypadPressed]
	ld [wJoypadDown], a
	ld a, [wJoypadReleased]
	ld [wJoypadReleasedBackup], a
; We can only get four inputs at a time.
; We take d-pad first for no particular reason.
	ld a, R_DPAD
	ldh [rP1], a
; Read three times to give the request time to take.
	ldh a, [rP1]
	ldh a, [rP1]
	ldh a, [rP1]
; The Joypad register output is in the lo nybble (inversed).
; We make the lo nybble of our new container d-pad input.
	cpl
	and $0f
; We'll keep this in b for now.
	ld b, a

; Buttons make 8 total inputs (A, B, Select, Start).
; We can fit this into one byte.
	ld a, R_BUTTONS
	ldh [rP1], a
; Wait for input to stabilize.
REPT 9
	ldh a, [rP1]
ENDR
; Buttons take the hi nybble.
	cpl
	and $0f
	swap a
	or b
	ld c, a

	cp A_BUTTON | B_BUTTON | D_RIGHT | D_LEFT
	jr nz, .asm_0692
	ld c, 0

.asm_0692
; To get the delta we xor the last frame's input with the new one.
	ld a, [wJoypadDown]
	xor c
; Newly pressed this frame:
	and c
	ld [wJoypadReleased], a
; Currently pressed:
	ld a, c
	ld [wJoypadPressed], a

; Reset the joypad register since we're done with it.
	ld a, $30
	ldh [rP1], a
	ret


code:
WriteOAMDMACodeToHRAM::
	ld c, LOW(hTransferVirtualOAM)
	ld b, $12
	ld hl, OAMDMACode
.copy
	ld a, [hli]
	ld [c], a
	inc c
	dec b
	jr nz, .copy
	ret

OAMDMACode::
; This code is defined in ROM, but
; copied to and called from HRAM.
LOAD "OAM DMA", HRAM[$ffe0]
hTransferVirtualOAM::
	ldh a, [hff80]
	bit 1, a
	ld a, HIGH(wdc00)
	jr z, .asm_1132
	ld a, HIGH(wdd00)
.asm_1132
	ldh [rDMA], a
	ld a, 40
.wait
	dec a
	jr nz, .wait
	ret
ENDL


code:
SECTION "HRAM", HRAM

hff80:: ds 1 ; ff80
hff81:: ds 1 ; ff81
hff82:: ds 1 ; ff82
hff83:: ds 1 ; ff83

hff84:: ds 1 ; ff84
hff85:: ds 1 ; ff85
hff86:: ds 1 ; ff86
hff87:: ds 1 ; ff87
hff88:: ds 1 ; ff88
hff89:: ds 1 ; ff89
hff8a:: ds 1 ; ff8a
hff8b:: ds 1 ; ff8b
hff8c:: ds 1 ; ff8c
hff8d:: ds 1 ; ff8d

hff8e:: ds 1 ; ff8e
hff8f:: ds 1 ; ff8f
hff90:: ds 1 ; ff90
hff91:: ds 1 ; ff91
hff92:: ds 1 ; ff92
hff93:: ds 1 ; ff93
hff94:: ds 1 ; ff94
hff95:: ds 1 ; ff95
hff96:: ds 1 ; ff96
hff97:: ds 1 ; ff97
hff98:: ds 1 ; ff98
hff99:: ds 1 ; ff99
hff9a:: ds 1 ; ff9a
hff9b:: ds 1 ; ff9b
hff9c:: ds 1 ; ff9c
hff9d:: ds 1 ; ff9d
hff9e:: ds 1 ; ff9e
hff9f:: ds 1 ; ff9f
hffa0:: ds 1 ; ffa0
hffa1:: ds 1 ; ffa1
hffa2:: ds 1 ; ffa2
hffa3:: ds 1 ; ffa3
hffa4:: ds 1 ; ffa4
hffa5:: ds 1 ; ffa5
hffa6:: ds 1 ; ffa6
hffa7:: ds 1 ; ffa7
hffa8:: ds 1 ; ffa8
hffa9:: ds 1 ; ffa9
hffaa:: ds 1 ; ffaa
hffab:: ds 1 ; ffab
hffac:: ds 1 ; ffac
hffad:: ds 1 ; ffad
hffae:: ds 1 ; ffae
hffaf:: ds 1 ; ffaf
hffb0:: ds 1 ; ffb0
hffb1:: ds 1 ; ffb1
hffb2:: ds 1 ; ffb2
hffb3:: ds 1 ; ffb3
hffb4:: ds 1 ; ffb4
hffb5:: ds 1 ; ffb5
hffb6:: ds 1 ; ffb6
hffb7:: ds 1 ; ffb7
hffb8:: ds 1 ; ffb8
hffb9:: ds 1 ; ffb9
hffba:: ds 1 ; ffba
hffbb:: ds 1 ; ffbb
hffbc:: ds 1 ; ffbc
hffbd:: ds 1 ; ffbd
hffbe:: ds 1 ; ffbe
hffbf:: ds 1 ; ffbf
hffc0:: ds 1 ; ffc0
hffc1:: ds 1 ; ffc1
hffc2:: ds 1 ; ffc2
hffc3:: ds 1 ; ffc3
hffc4:: ds 1 ; ffc4
hffc5:: ds 1 ; ffc5
hffc6:: ds 1 ; ffc6
hffc7:: ds 1 ; ffc7
hffc8:: ds 1 ; ffc8
hffc9:: ds 1 ; ffc9
hffca:: ds 1 ; ffca
hffcb:: ds 1 ; ffcb
hffcc:: ds 1 ; ffcc
hffcd:: ds 1 ; ffcd
hffce:: ds 1 ; ffce
hffcf:: ds 1 ; ffcf
hffd0:: ds 1 ; ffd0
hffd1:: ds 1 ; ffd1
hffd2:: ds 1 ; ffd2
hffd3:: ds 1 ; ffd3
hffd4:: ds 1 ; ffd4
hffd5:: ds 1 ; ffd5
hffd6:: ds 1 ; ffd6
hffd7:: ds 1 ; ffd7
hffd8:: ds 1 ; ffd8
hffd9:: ds 1 ; ffd9
hffda:: ds 1 ; ffda
hffdb:: ds 1 ; ffdb
hffdc:: ds 1 ; ffdc
hffdd:: ds 1 ; ffdd
hffde:: ds 1 ; ffde
hffdf:: ds 1 ; ffdf


code:
INCLUDE "macros/const.asm"
INCLUDE "macros/farcall.asm"
INCLUDE "macros/data.asm"


code:
; Enumerate constants

MACRO const_def
	IF _NARG >= 1
		DEF const_value = \1
	ELSE
		DEF const_value = 0
	ENDC
	IF _NARG >= 2
		DEF const_inc = \2
	ELSE
		DEF const_inc = 1
	ENDC
ENDM

MACRO const
	DEF \1 EQU const_value
	DEF const_value += const_inc
ENDM

MACRO shift_const
	DEF \1 EQU 1 << const_value
	DEF const_value += const_inc
ENDM

MACRO const_skip
	if _NARG >= 1
		DEF const_value += const_inc * (\1)
	else
		DEF const_value += const_inc
	endc
ENDM

MACRO const_next
	if (const_value > 0 && \1 < const_value) || (const_value < 0 && \1 > const_value)
		fail "const_next cannot go backwards from {const_value} to \1"
	else
		DEF const_value = \1
	endc
ENDM


code:
; Value macros

DEF percent EQUS "* $ff / 100"

MACRO bcd2
	dn ((\1) / 1000) % 10, ((\1) / 100) % 10
	dn ((\1) / 10) % 10, (\1) % 10
ENDM

MACRO bcd3
	dn ((\1) / 100000) % 10, ((\1) / 10000) % 10
	dn ((\1) / 1000) % 10, ((\1) / 100) % 10
	dn ((\1) / 10) % 10, (\1) % 10
ENDM

; Constant data (db, dw, dl) macros

MACRO dbw
	db \1
	dw \2
ENDM

MACRO dwb
	dw \1
	db \2
ENDM

MACRO dn ; nybbles
	REPT _NARG / 2
		db ((\1) << 4) | (\2)
		SHIFT 2
	ENDR
ENDM

MACRO dba ; dbw bank, address
	REPT _NARG
		dbw BANK(\1), \1
		SHIFT
	ENDR
ENDM

MACRO dab ; dwb address, bank
	REPT _NARG
		dwb \1, BANK(\1)
		SHIFT
	ENDR
ENDM

MACRO dr
	INCBIN "baserom.gbc", \1, \2 +- \1
ENDM


code:
MACRO farcall
	call Farcall
	dwb \1, BANK(\1)
ENDM

MACRO farjp
	ld b, BANK(\1)
	ld hl, \1
	jp Bankswitch
ENDM

MACRO homecall
	ld a, BANK(\1)
	call BankswitchHome
	call \1
ENDM


code:
INCLUDE "constants.asm"

SECTION "bank01", ROMX, BANK[$01]

INCLUDE "banks/bank_01.asm"

SECTION "bank02", ROMX, BANK[$02]

INCLUDE "banks/bank_02.asm"

SECTION "bank03", ROMX, BANK[$03]

INCLUDE "banks/bank_03.asm"

SECTION "bank04", ROMX, BANK[$04]

INCLUDE "banks/bank_04.asm"

SECTION "bank05", ROMX, BANK[$05]

INCLUDE "banks/bank_05.asm"

SECTION "bank06", ROMX, BANK[$06]

INCLUDE "banks/bank_06.asm"

SECTION "bank07", ROMX, BANK[$07]

INCLUDE "banks/bank_07.asm"

SECTION "bank08", ROMX, BANK[$08]

INCLUDE "banks/bank_08.asm"

SECTION "bank09", ROMX, BANK[$09]

INCLUDE "banks/bank_09.asm"

SECTION "bank0a", ROMX, BANK[$0a]

INCLUDE "banks/bank_0a.asm"

SECTION "bank0b", ROMX, BANK[$0b]

INCLUDE "banks/bank_0b.asm"

SECTION "bank0c", ROMX, BANK[$0c]

INCLUDE "banks/bank_0c.asm"

SECTION "bank0d", ROMX, BANK[$0d]

INCLUDE "banks/bank_0d.asm"

SECTION "bank0e", ROMX, BANK[$0e]

INCLUDE "banks/bank_0e.asm"

SECTION "bank0f", ROMX, BANK[$0f]

INCLUDE "banks/bank_0f.asm"

SECTION "bank10", ROMX, BANK[$10]

INCLUDE "banks/bank_10.asm"

SECTION "bank11", ROMX, BANK[$11]

INCLUDE "banks/bank_11.asm"

SECTION "bank12", ROMX, BANK[$12]

INCLUDE "banks/bank_12.asm"

SECTION "bank13", ROMX, BANK[$13]

INCLUDE "banks/bank_13.asm"

SECTION "bank14", ROMX, BANK[$14]

INCLUDE "banks/bank_14.asm"

SECTION "bank15", ROMX, BANK[$15]

INCLUDE "banks/bank_15.asm"

SECTION "bank16", ROMX, BANK[$16]

INCLUDE "banks/bank_16.asm"

SECTION "bank17", ROMX, BANK[$17]

INCLUDE "banks/bank_17.asm"

SECTION "bank18", ROMX, BANK[$18]

INCLUDE "banks/bank_18.asm"

SECTION "bank19", ROMX, BANK[$19]

INCLUDE "banks/bank_19.asm"

SECTION "bank1a", ROMX, BANK[$1a]

INCLUDE "banks/bank_1a.asm"

SECTION "bank1b", ROMX, BANK[$1b]

INCLUDE "banks/bank_1b.asm"

SECTION "bank1c", ROMX, BANK[$1c]

INCLUDE "banks/bank_1c.asm"

SECTION "bank1d", ROMX, BANK[$1d]

INCLUDE "banks/bank_1d.asm"

SECTION "bank1e", ROMX, BANK[$1e]

INCLUDE "banks/bank_1e.asm"

SECTION "bank1f", ROMX, BANK[$1f]

INCLUDE "banks/bank_1f.asm"

SECTION "bank20", ROMX, BANK[$20]

INCLUDE "banks/bank_20.asm"

SECTION "bank21", ROMX, BANK[$21]

INCLUDE "banks/bank_21.asm"

SECTION "bank22", ROMX, BANK[$22]

INCLUDE "banks/bank_22.asm"

SECTION "bank23", ROMX, BANK[$23]

INCLUDE "banks/bank_23.asm"

SECTION "bank24", ROMX, BANK[$24]

INCLUDE "banks/bank_24.asm"

SECTION "bank25", ROMX, BANK[$25]

INCLUDE "banks/bank_25.asm"

SECTION "bank26", ROMX, BANK[$26]

INCLUDE "banks/bank_26.asm"

SECTION "bank27", ROMX, BANK[$27]

INCLUDE "banks/bank_27.asm"

SECTION "bank28", ROMX, BANK[$28]

INCLUDE "banks/bank_28.asm"

SECTION "bank29", ROMX, BANK[$29]

INCLUDE "banks/bank_29.asm"

SECTION "bank2a", ROMX, BANK[$2a]

INCLUDE "banks/bank_2a.asm"

SECTION "bank2b", ROMX, BANK[$2b]

INCLUDE "banks/bank_2b.asm"

SECTION "bank2c", ROMX, BANK[$2c]

INCLUDE "banks/bank_2c.asm"

SECTION "bank2d", ROMX, BANK[$2d]

INCLUDE "banks/bank_2d.asm"

SECTION "bank2e", ROMX, BANK[$2e]

INCLUDE "banks/bank_2e.asm"

SECTION "bank2f", ROMX, BANK[$2f]

INCLUDE "banks/bank_2f.asm"

SECTION "bank30", ROMX, BANK[$30]

INCLUDE "banks/bank_30.asm"

SECTION "bank31", ROMX, BANK[$31]

; Empty

SECTION "bank32", ROMX, BANK[$32]

; Empty

SECTION "bank33", ROMX, BANK[$33]

; Empty

SECTION "bank34", ROMX, BANK[$34]

; Empty

SECTION "bank35", ROMX, BANK[$35]

; Empty

SECTION "bank36", ROMX, BANK[$36]

; Empty

SECTION "bank37", ROMX, BANK[$37]

; Empty

SECTION "bank38", ROMX, BANK[$38]

; Empty

SECTION "bank39", ROMX, BANK[$39]

; Empty

SECTION "bank3a", ROMX, BANK[$3a]

; Empty

SECTION "bank3b", ROMX, BANK[$3b]

; Empty

SECTION "bank3c", ROMX, BANK[$3c]

; Empty

SECTION "bank3d", ROMX, BANK[$3d]

; Empty

SECTION "bank3e", ROMX, BANK[$3e]

; Empty

SECTION "bank3f", ROMX, BANK[$3f]

; Empty


code:
.PHONY: all clean

CC := gcc
CFLAGS := -O3 -std=c99 -Wall -Wextra -Wno-missing-field-initializers

tools := \
	scan_includes \

all: $(tools)
	@:

clean:
	rm -f $(tools)

%: %.c
	$(CC) $(CFLAGS) -o $@ $<

path: tools/Makefile


code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <getopt.h>

void usage(void) {
	printf("Usage: scan_includes [-h] [-s] filename\n"
	       "-h, --help\n"
	       "    Print usage and exit\n"
	       "-s, --strict\n"
	       "    Fail if a file cannot be read\n");
}

struct Options {
	bool help;
	bool strict;
};

struct Options Options = {0};

void scan_file(char* filename) {
	FILE *f = fopen(filename, "rb");
	if (!f) {
		if (Options.strict) {
			fprintf(stderr, "Could not open file: '%s'\n", filename);
			exit(1);
		} else {
			return;
		}
	}

	fseek(f, 0, SEEK_END);
	long size = ftell(f);
	rewind(f);

	char *buffer = malloc(size + 1);
	char *orig = buffer;
	size = fread(buffer, 1, size, f);
	buffer[size] = '\0';
	fclose(f);

	for (; buffer && (buffer - orig < size); buffer++) {
		bool is_include = false;
		bool is_incbin = false;
		switch (*buffer) {
			case ';':
				buffer = strchr(buffer, '\n');
				if (!buffer) {
					fprintf(stderr, "%s: no newline at end of file\n", filename);
					break;
				}
				break;

			case '"':
				buffer++;
				buffer = strchr(buffer, '"');
				if (!buffer) {
					fprintf(stderr, "%s: unterminated string\n", filename);
					break;
				}
				buffer++;
				break;

			case 'i':
			case 'I':
				if ((strncmp(buffer, "INCBIN", 6) == 0) || (strncmp(buffer, "incbin", 6) == 0)) {
					is_incbin = true;
				} else if ((strncmp(buffer, "INCLUDE", 7) == 0) || (strncmp(buffer, "include", 7) == 0)) {
					is_include = true;
				}
				if (is_incbin || is_include) {
					buffer = strchr(buffer, '"');
					if (!buffer) {
						break;
					}
					buffer++;
					int length = strcspn(buffer, "\"");
					char *include = malloc(length + 1);
					strncpy(include, buffer, length);
					include[length] = '\0';
					printf("%s ", include);
					if (is_include) {
						scan_file(include);
					}
					free(include);
					buffer = strchr(buffer, '"');
				}
				break;

		}
		if (!buffer) {
			break;
		}

	}

	free(orig);
}

int main(int argc, char* argv[]) {
	int i = 0;
	struct option long_options[] = {
		{"strict", no_argument, 0, 's'},
		{"help", no_argument, 0, 'h'},
		{0}
	};
	int opt = -1;
	while ((opt = getopt_long(argc, argv, "sh", long_options, &i)) != -1) {
		switch (opt) {
		case 's':
			Options.strict = true;
			break;
		case 'h':
			Options.help = true;
			break;
		default:
			usage();
			exit(1);
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (Options.help) {
		usage();
		return 0;
	}
	if (argc < 1) {
		usage();
		exit(1);
	}
	scan_file(argv[0]);
	return 0;
}


code:
SECTION "VRAM0", VRAM

vTiles0:: ds $800
vTiles1:: ds $800
vTiles2:: ds $800
vBGMap0:: ds $400
vBGMap1:: ds $400


code:
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto

###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs     diff=csharp

###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln       merge=binary
#*.csproj    merge=binary
#*.vbproj    merge=binary
#*.vcxproj   merge=binary
#*.vcproj    merge=binary
#*.dbproj    merge=binary
#*.fsproj    merge=binary
#*.lsproj    merge=binary
#*.wixproj   merge=binary
#*.modelproj merge=binary
#*.sqlproj   merge=binary
#*.wwaproj   merge=binary

###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg   binary
#*.png   binary
#*.gif   binary

###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc   diff=astextplain
#*.DOC   diff=astextplain
#*.docx  diff=astextplain
#*.DOCX  diff=astextplain
#*.dot   diff=astextplain
#*.DOT   diff=astextplain
#*.pdf   diff=astextplain
#*.PDF   diff=astextplain
#*.rtf   diff=astextplain
#*.RTF   diff=astextplain

path: .gitattributes


code:
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/

# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# Visual Studio 2017 auto generated files
Generated\ Files/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUNIT
*.VisualState.xml
TestResult.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

# Benchmark Results
BenchmarkDotNet.Artifacts/

# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/

# StyleCop
StyleCopReport.xml

# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb

# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap

# Visual Studio Trace Files
*.e2e

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# JustCode is a .NET coding add-in
.JustCode

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json

# Visual Studio code coverage results
*.coverage
*.coveragexml

# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj

# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets

# Microsoft Azure Build Output
csx/
*.build.csdef

# Microsoft Azure Emulator
ecf/
rcf/

# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx

# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/

# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs

# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk

# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak

# SQL Server files
*.mdf
*.ldf
*.ndf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- Backup*.rdl

# Microsoft Fakes
FakesAssemblies/

# GhostDoc plugin setting file
*.GhostDoc.xml

# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt

# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw

# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions

# Paket dependency manager
.paket/paket.exe
paket-files/

# FAKE - F# Make
.fake/

# JetBrains Rider
.idea/
*.sln.iml

# CodeRush personal settings
.cr/personal

# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config

# Tabs Studio
*.tss

# Telerik's JustMock configuration file
*.jmconfig

# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

# OpenCover UI analysis results
OpenCover/

# Azure Stream Analytics local run output
ASALocalRun/

# MSBuild Binary and Structured Log
*.binlog

# NVidia Nsight GPU debugger configuration file
*.nvuser

# MFractors (Xamarin productivity tool) working folder
.mfractor/

# Local History for Visual Studio
.localhistory/

# BeatPulse healthcheck temp database
healthchecksdb
/Source/Patches/PawnAnimationPatches/HarmonyPatch_Pawn_DrawTracker.cs
/Source/Patches/PawnAnimationPatches/HarmonyPatch_PawnRotation.cs
/Source/Patches/PawnAnimationPatches/HarmonyPatch_PawnRenderer.cs
/Source/Patches/OtherModPatches/HarmonyPatch_ShowHairWithHats.cs
/Source/Patches/OtherModPatches/HarmonyPatch_FacialAnimation.cs
/Source/Patches/OtherModPatches/HarmonyPatch_DontShaveYourHead.cs
/Source/Patches/OtherModPatches/HarmonyPatch_CSL.cs
/Source/Patches/OtherModPatches/HarmonyPatch_AlienRace.cs
/Source/Patches/ThingAnimationPatches/HarmonyPatch_ThingDrawAt.cs
/Defs/AnimationDefs/Animations_SexToys.xml
/1.5/Defs/AnimationDefs/BasicBestiality/HumanRotatedOffset.xml
/1.5/Defs/AnimationDefs/BasicBestiality/BasicBestiality4v1.xml
/1.5/Defs/AnimationDefs/BasicBestiality/BasicBestiality3v1.xml
/1.5/Defs/AnimationDefs/BasicBestiality/BasicBestiality2v1.xml
/1.5/Defs/AnimationDefs/BasicBestiality/BasicBestiality1v1.xml
/1.5/Defs/AnimationDefs/BasicBestiality/!BasicBestiality.xml
/1.5/Defs/TestDoNotPush
/1.5/Textures/AnimationProps/BEV

path: .gitignore