;==========================================================================================
;
;   UNOFFICIAL SNES POWERPAK FIRMWARE V2.01 (CODENAME: "SIMBA")
;   (c) 2012/2013 by ManuLöwe (http://www.manuloewe.de/)
;
;	*** CF MODULE: SN (ROM BROWSER & LOADER) ***
;	Code in this file based on v1.0X code written by:
;	- bunnyboy (SNES PowerPak creator), (c) 2009
;
;==========================================================================================



; ****************************** Includes ******************************

; More includes at end of file!

	.INCLUDE "module_rommakeup.inc"		; MemoryMap, VectorTable, HeaderInfo

	.INCLUDE "global_variables.asm"		; Global Variables



; ************************ File extension table ************************
;
; File extensions to look for, mapped to search variables:
;
;           |     | +1  | +2  | +3  | +4  | +5  | +6  | +7  | +8  | +9  | +10 |
; ------------------------------------------------------------------------------
; extMatch1 |  S  |  S  |  S  |  G  |  S  |  B  |  F  |     |     |     |     |
; ------------------------------------------------------------------------------
; extMatch2 |  M  |  W  |  F  |  D  |  P  |  I  |  I  |     |     |     |     |
; ------------------------------------------------------------------------------
; extMatch3 |  C  |  C  |  C  |  3  |  C  |  N  |  G  |     |     |     |     |
; ------------------------------------------------------------------------------
;
; When adding one or more extensions, don't forget to increase the value
; of variable "extNum" a few lines below!



; ******************************** Main ********************************

Main:
	sep #A_8BIT				; 8 bit Accumulator, 16 bit X/Y
	rep #XY_8BIT

	stz Joy1New				; reset input buttons
	stz Joy1New+1
	stz Joy1Press
	stz Joy1Press+1

	lda #$07				; number of file types to look for (7, see table above)
	sta extNum
	stz extNum+1

	lda #'S'				; using the least possible amount of lda/sta commands
	sta extMatch1
	sta extMatch1+1
	sta extMatch1+2
	sta extMatch1+4

	lda #'M'
	sta extMatch2

	lda #'W'
	sta extMatch2+1

	lda #'F'
	sta extMatch1+6
	sta extMatch2+2

	lda #'P'
	sta extMatch2+4

	lda #'C'
	sta extMatch3
	sta extMatch3+1
	sta extMatch3+2
	sta extMatch3+4

	lda #'G'
	sta extMatch1+3
	sta extMatch3+6

	lda #'D'
	sta extMatch2+3

	lda #'3'
	sta extMatch3+3

	lda #'B'
	sta extMatch1+5

	lda #'I'
	sta extMatch2+5
	sta extMatch2+6

	lda #'N'
	sta extMatch3+5

	InitFileBrowser



FileBrowserLoop:
	wai

; ------ V2.00 DEBUG STUFF ---------------------
;	SetCursorPos 22, 24
;	PrintHexNum selectedEntry+1
;	PrintString "-"
;	PrintHexNum selectedEntry
;	stz BGPrintMon
;	SetCursorPos 23, 24
;	PrintHexNum filesInDir+1
;	PrintString "-"
;	PrintHexNum filesInDir
;	stz BGPrintMon
; ------ END DEBUG -----------------------------



UpCheck:
	lda Joy1+1
	and #%00001000
	beq UpDone

UpPressed:
	lda cursorYCounter
	bne UpDone
	lda scrollYCounter
	bne UpDone

UpScroll:
	lda #$08
	sta speedScroll
	lda #$01
	sta speedCounter

	jump jScrollUp

	ldx #$0015				; 21 frames
-
	wai
	lda Joy1+1
	and #%00001000
	beq UpDone
	dex
	cpx #$0000
	bne -

UpHeld:
	lda cursorYCounter
	bne UpDone
	lda scrollYCounter
	bne UpDone

UpScroll2:
	lda #$08
	sta speedScroll
	lda #$01
	sta speedCounter

	jump jScrollUp

	ldx #$0003				; 3 frames
-
	wai
	lda Joy1+1
	and #%00001000
	beq UpDone
	dex
	cpx #$0000
	bne -
	bra UpHeld

UpDone:



DownCheck:
	lda Joy1+1
	and #%00000100
	beq DownDone

DownPressed:
	lda cursorYCounter
	bne DownDone
	lda scrollYCounter
	bne DownDone

DownScroll:
	lda #$08
	sta speedScroll
	lda #$01
	sta speedCounter

	jump jScrollDown

	ldx #$0015				; 21 frames
-
	wai
	lda Joy1+1
	and #%00000100
	beq DownDone
	dex
	cpx #$0000
	bne -

DownHeld:
	lda cursorYCounter
	bne DownDone
	lda scrollYCounter
	bne DownDone

DownScroll2:
	lda #$08
	sta speedScroll
	lda #$01
	sta speedCounter

	jump jScrollDown

	ldx #$0003				; 3 frames
-
	wai
	lda Joy1+1
	and #%00000100
	beq DownDone
	dex
	cpx #$0000
	bne -
	bra DownHeld

DownDone:



LeftCheck:
	lda Joy1Press+1
	and #%00000010
	beq LeftDone

LeftPressed:
	lda cursorYCounter
	bne LeftDone
	lda scrollYCounter
	bne LeftDone

LeftScroll:
	lda #$04
	sta speedScroll
	lda #$02
	sta speedCounter

	jump jScrollUp

LeftDone:



RightCheck:
	lda Joy1Press+1
	and #%00000001
	beq RightDone

RightPressed:
	lda cursorYCounter
	bne RightDone
	lda scrollYCounter
	bne RightDone

RightScroll:
	lda #$04
	sta speedScroll
	lda #$02
	sta speedCounter

	jump jScrollDown

RightDone:



LCheck:
	lda Joy1New
	and #%00100000
	beq LDone

	jsr PageUp

LDone:



RCheck:
	lda Joy1New
	and #%00010000
	beq RDone

	jsr PageDown

RDone:



ACheck:						; A = select game / load dir
	lda Joy1New
	and #%10000000
	beq __ACheckDone

	lda #'S'
	sta bufferType

	jump jDirGetEntry			; get selected entry

	lda tempEntry.tempDirFlag		; check if directory
	cmp #$01
	beq +

	jmp NextModule

+	jump jNextDir

__ACheckDone:



BCheck:						; B = go up one directory
	lda Joy1New+1
	and #%10000000
	beq __BCheckDone

	lda sourceCluster			; check if current dir = root dir ...
	cmp rootDirCluster
	bne __NotRootDir

	lda sourceCluster+1
	cmp rootDirCluster+1
	bne __NotRootDir

	lda sourceCluster+2
	cmp rootDirCluster+2
	bne __NotRootDir

	lda sourceCluster+3
	cmp rootDirCluster+3
	bne __NotRootDir

	jmp NextModuleSI			; ... if yes, load intro module

__NotRootDir:
	lda #$00				; otherwise, load entry $0001, which is
	sta selectedEntry+1			; always "/.." except for when already in root dir
	lda #$01
	sta selectedEntry

	lda #'S'
	sta bufferType

	jump jDirGetEntry

	jump jNextDir

__BCheckDone:



StartCheck:
	lda Joy1New+1
	and #%00010000
	beq StartDone
	jsr LoadLastGame			; Start pressed, load last game info
	jmp NextModuleSOLast

StartDone:



;----------------------- removed 2.0 (PowerPak crashes!) -----------------------
; Removed the whole Select checking code because CardVerifyFile seems broken,
; and who needs a verify feature anyway? ;-)
;
;SelectCheck:        ;;SELECT = verify loaded file
;	lda Joy1New+1
;	and #%00100000
;	beq SelectDone
;
;	jump jDirGetEntry       ;get selected entry
;	lda tempEntry.tempCluster
;	sta sourceCluster
;	lda tempEntry.tempCluster+1
;	sta sourceCluster+1
;	lda tempEntry.tempCluster+2
;	sta sourceCluster+2
;	lda tempEntry.tempCluster+3
;	sta sourceCluster+3      ;copy to source cluster
;
;	lda #$00
;	sta DMAWRITELO
;	lda #$FE
;	sta DMAWRITEHI
;	lda #$FF
;	sta DMAWRITEBANK   ;;read file so dma wraps, erasing header
;
;	stz sectorCounter
;	stz bankCounter
;  jsr CardVerifyFile				; this crashed the PowerPak!
;
;SelectDone:
;-------------------------------------------------------------------------------

	jmp FileBrowserLoop



NextModule:
	ldy #$0000

CopyGameNameLoop:				; this affects the options screen (SO.MAP)
	lda tempEntry, y
	sta gameName, y
	iny
	cpy #$0080				; 128 bytes
	bne CopyGameNameLoop

;	stz gameName+$35			; game name is NUL-terminated in SO.MAP

	lda gameName.gCluster			; copy game cluster to source cluster
	sta sourceCluster
	lda gameName.gCluster+1
	sta sourceCluster+1
	lda gameName.gCluster+2
	sta sourceCluster+2
	lda gameName.gCluster+3
	sta sourceCluster+3

	lda #<sectorBuffer1
	sta destLo
	lda #>sectorBuffer1
	sta destHi				; put first sector into sector RAM
	stz destBank

	stz sectorCounter
	stz bankCounter

	jump jClusterToLBA			; sourceCluster -> first sourceSector

	lda #kDestWRAM
	sta destType

	jump jCardReadSector			; sector -> WRAM

	lda sectorBuffer1+$05
	cmp #'S'				; check for SPC file (SPC files start with ASCII string SNES-SPC700)
	bne NextModuleSO

	lda sectorBuffer1+$06
	cmp #'P'
	bne NextModuleSO

	lda sectorBuffer1+$07
	cmp #'C'
	bne NextModuleSO

	jmp NextModuleSP			; SPC file detected, go to player



NextModuleSO:
	jsr ShowLoadingMsg

	FindFile "SA.MAP"

	jump jCardLoadModule			; load auto save loading module



NextModuleSI:
	FindFile "SI.MAP"

	jump jPrintClearScreen

	jump jLoadRomVersion

	jump jCardLoadModule			; return to titlescreen



NextModuleSP:
	jsr ShowLoadingMsg

	stz nextModule				; make sure not to leave SPC player again

	FindFile "SP.MAP"

	jump jCardLoadModule			; load SPC player module



NextModuleSOLast:				; only invoked by pressing Start in the filebrowser
	jsr ShowLoadingMsg

	FindFile "SO.MAP"

	jump jCardLoadModule			; load options module



;----------------------- removed 2.0 (PowerPak crashes!) -----------------------
; Removed the whole broken CardVerifyFile routine, too
;
;CardVerifyFile:					; sourceCluster already set
;	wai
;	ClearLine 20
;	ClearLine 21
;	ClearLine 22
;	SetCursorPos 20, 1
;	PrintString "Verifying File\n"
;
;	lda #$00
;	sta bankCounter
;	sta bankOffset
;	sta bankOffset+1
;
;	lda #$00
;	sta DMAWRITEBANK
;	sta DMAWRITELO
;	sta DMAWRITEHI
;
;	lda #$00
;	sta gameSize
;	sta gameSize+1
;	jump jClusterToLBA            ;sourceCluster -> first sourceSector
;
;CardVerifyFileLoop:
;	clc
;	lda gameSize
;	adc #$01
;	sta gameSize
;	lda gameSize+1
;	adc #$00
;	sta gameSize+1            ;;keep track of game size
;
;
;	jsr CardVerifySector
;
;	lda destHi
;	pha
;	lda destLo
;	pha
;	jump jLoadNextSectorNum
;	pla
;	sta destLo
;	pla
;	sta destHi
;
;CardVerifyFileLastSectorCheck:
;	lda #$0F
;	sta temp
;	lda #$FF
;	sta temp+1                            ;;FAT32 last cluster = 0x0FFFFFFF
;	sta temp+2
;	sta temp+3
;
;	lda fat32Enabled
;	cmp #$01
;	beq CardVerifyFileLastSectorCheck2        ;;if FAT32, last cluster mask done
;
;	lda #$00
;	sta temp
;	sta temp+1                             ;;FAT16 last cluster = 0x0000FFFF
;
;CardVerifyFileLastSectorCheck2:
;check if cluster = last cluster
; if match, jmp to last entry found
;	lda temp
;	cmp sourceCluster+3
;	bne CardVerifyFileNextSector
;	lda temp+1
;	cmp sourceCluster+2
;	bne CardVerifyFileNextSector
;	lda temp+2
;	cmp sourceCluster+1
;	bne CardVerifyFileNextSector
;	lda temp+3
;	cmp sourceCluster+0
;	bne CardVerifyFileNextSector
;	jmp CardVerifyFileDone
;
;CardVerifyFileNextSector:
;	inc destHi
;	inc destHi
;  inc bankCounter
;  lda bankCounter
;  cmp #$00                 ;;only load 256x512=128KB for modules
;  beq CardVerifyFileDone
;
;
;	jmp CardVerifyFileLoop
;
;CardVerifyFileDone:
;	PrintString "Verify Passed"
;rts
;
;
;
;CardVerifySector:
;PrintHexNum bankCounter
;	PrintString "jCardWaitNotBusy\n"
;	jump jCardWaitNotBusy
;PrintHexNum bankCounter
;	PrintString "jCardWaitReady\n"
;	jump jCardWaitReady
;PrintHexNum bankCounter
;	PrintString "jCardCheckError\n"
;	jump jCardCheckError
;PrintHexNum bankCounter
;	PrintString "jCardLoadLBA\n"
;	jump jCardLoadLBA
;
;	lda #$00
;	sta sourceBytes16
;	lda #$02
;	sta sourceBytes16+1
;
;  PrintHexNum bankCounter
;	PrintString "jCardWaitNotBusy\n"
;	jump jCardWaitNotBusy
;  PrintHexNum bankCounter
;	PrintString "jCardWaitReady\n"
;	jump jCardWaitReady
;  PrintHexNum bankCounter
;	PrintString "jCardCheckError\n"
;	jump jCardCheckError
;
;	lda #$20
;	sta CARDCOMMAND           ;send card read sector command
;	nop
;	nop
 ; jump jCardWaitNotBusy
 ; jump jCardWaitReady
;  PrintHexNum bankCounter
;	PrintString "jCardCheckError\n"
;	jump jCardCheckError
;  PrintHexNum bankCounter
;	PrintString "jCardWaitDataReq\n"
;	jump jCardWaitDataReq
;
;	jsr CardVerifyBytesToSDRAM
;
;CardVerifySectorCheckDone:
;  PrintHexNum bankCounter
;	PrintString "jCardCheckError\n"
;	jump jCardCheckError
;CardVerifySectorDone:
;rts
;
;
;
;
;CardVerifyBytesToSDRAM:         ;use DMA, no increment source or dest
;	ldx sourceBytes16
;CardVerifyBytesToSDRAMLoop:
;	lda $21FF
;	sta errorCode
;	lda CARDDATAREAD  ;;READ DATA BYTE
;	sta errorCode+1
;	cmp errorCode
;	bne CardVerifyBytesToSDRAMLoopError
;
;CardVerifyBytesToSDRAMLoopNext:
;	lda bankOffset
;	clc
;	adc #$01
;	sta bankOffset
;	lda bankOffset+1
;	adc #$00
;	sta bankOffset+1
;	lda bankCounter
;	adc #$00
;	sta bankCounter
;
;	dex
;	bne CardVerifyBytesToSDRAMLoop
;rts
;
;CardVerifyBytesToSDRAMLoopError:
;	phx
;	SetCursorPos 21, 0
;	PrintString "Verify Error\n wanted $"
;	PrintHexNum errorCode+1
;	PrintString " read $"
;	PrintHexNum errorCode
;	PrintString " @$"
;	PrintHexNum bankCounter
;	PrintHexNum bankOffset+1
;	PrintHexNum bankOffset
;	PrintString "\n"
;CardVerifyError:
;  wai
;  jmp CardVerifyError
;	plx
;	jmp CardVerifyBytesToSDRAMLoopNext
;-------------------------------------------------------------------------------



; ************************ Show loading message ************************

ShowLoadingMsg:
	lda #$FF				; hide cursor
	sta cursorX
	lda #$F0
	sta cursorY

	stz scrollY				; make sure prior scrolling won't affect string position
	stz scrollYCounter
	stz scrollYUp
	stz scrollYDown
	stz speedCounter
	stz speedScroll

	jump jPrintClearScreen

	SetCursorPos 11, 11
	PrintString "Loading ..."
rts



; ****************************** Includes ******************************

	.INCLUDE "global_func_lastload.inc.asm"	; Module-specific functions

	.INCLUDE "global_func_pagenav.inc.asm"
