@echo on

set cdreplace="%~dp0tool\cd-replace\cd-replace"
set cuetool="%~dp0tool\cuetool"
REM You literally can't name the variable XDELTA or it fucks it up.
REM Incredible software design, thank you.
set xdeltapath="%~dp0tool\xdelta3-3_0_11\xdelta3-3.0.11-i686"

REM The below is just to figure out the name of the bin and cue, basically.
REM If you're looking at this file, you probably can just ignore
REM this part and the path setup, and skip to :perform

IF "%~1"=="" GOTO :argerr

:pathset
set workpath=%~dp0work\
set patchpath=%~dp0patches\
if not exist "%workpath%" mkdir "%workpath%"
set cuename="%~1"
set outdir=%~dp1
set outname=%outdir%RSG_EX_SAT
set outbinname="%outname%.bin"
set outcuename="%outname%.cue"

%cuetool% %cuename% > "%workpath%binname.txt"
set /p binname= <"%workpath%binname.txt"
set binname="%binname%"

:perform
@REM We don't want to modify in-place, so make a copy to the output files
@ECHO Copying disc image...
copy %binname% %outbinname%
copy %cuename% %outcuename%

@ECHO Extracting game files...
%cdreplace% -e %binname% "SS\GAME.BIN" "%workpath%GAME.BIN"
%cdreplace% -e %binname% "SS\OPTION.BIN" "%workpath%OPTION.BIN"
%cdreplace% -e %binname% "SS\BACK_CHK.BIN" "%workpath%BACK_CHK.BIN"

@ECHO Patching game files...
%xdeltapath% -f -d -s "%workpath%GAME.BIN" "%patchpath%GAME.xdelta3" "%workpath%GAME.NEW.BIN"
%xdeltapath% -f -d -s "%workpath%OPTION.BIN" "%patchpath%OPTION.xdelta3" "%workpath%OPTION.NEW.BIN"
%xdeltapath% -f -d -s "%workpath%BACK_CHK.BIN" "%patchpath%BACK_CHK.xdelta3" "%workpath%BACK_CHK.NEW.BIN"

@REM Copy the patched files in
@REM SS=Saturn mode, STV=Arcade mode, yes they're supposed to be identical...
@ECHO Inserting game files...
%cdreplace% -r %outbinname% "SS\GAME.BIN" "%workpath%GAME.NEW.BIN"
%cdreplace% -r %outbinname% "STV\GAME.BIN" "%workpath%GAME.NEW.BIN"
%cdreplace% -r %outbinname% "SS\OPTION.BIN" "%workpath%OPTION.NEW.BIN"
%cdreplace% -r %outbinname% "STV\OPTION.BIN" "%workpath%OPTION.NEW.BIN"
%cdreplace% -r %outbinname% "SS\BACK_CHK.BIN" "%workpath%BACK_CHK.NEW.BIN"

@REM Fix up the cue sheet; both timing and bin filename!
@ECHO Fixing up cue sheet...
%cuetool% %outcuename% %cuename% %outbinname% %binname%

@ECHO Done!
@pause
@exit /b 0

:argerr
@ECHO Please drag your cue onto this batch.
@pause
@exit /b -1
