::**************************************************
:: PSXMinimise-Decompress is part of:
:: PSXMinimise v0.52 by jcx - Released on 2021-07-15
:: https://jcx.life/tech/psxminimise
::**************************************************

@echo off

if "%~1"=="" cls
:header
if "%~1"=="" color 5F
call psxminimise-header.bat
if "%~1"=="" echo PSXMinimise is running in decompression mode.
if "%~1"=="" timeout /T 3

:begin
IF EXIST "*.arc" ( 
goto decompress
) ELSE (
set errormsg=Archive not found.
goto error
)

:decompress
if "%~1"=="1" echo ---------------------------------------------------------
echo Unpacking .ARC
if "%~1"=="1" echo ---------------------------------------------------------
if "%~1"=="1" freearc e *.arc
if "%~1"=="" freearc e *.arc >NUL
IF %ERRORLEVEL% EQU 0 GOTO removeecm
set errormsg=Error unpacking archive.
GOTO error

:removeecm
if "%~1"=="1" echo ---------------------------------------------------------
echo Re-adding Error Code Modulation to Track 1
if "%~1"=="1" echo ---------------------------------------------------------
IF EXIST "*(Track 01).bin.ecm" ( 
if "%~1"=="1" unecm *"(Track 01).bin.ecm" 
if "%~1"=="" unecm *"(Track 01).bin.ecm" >NUL 2>NUL
del *"(Track 01).bin.ecm"
goto audioextract
) ELSE (
IF EXIST "*(Track 1).bin.ecm" (
if "%~1"=="1" unecm *"(Track 1).bin.ecm"
if "%~1"=="" unecm *"(Track 1).bin.ecm" >NUL 2>NUL
del *"(Track 1).bin.ecm" 
goto audioextract
) ELSE ( 
if "%~1"=="1" unecm *".bin.ecm"
if "%~1"=="" unecm *".bin.ecm" >NUL 2>NUL

GOTO verify
)
)

:audioextract
if "%~1"=="1" echo ---------------------------------------------------------
echo Uncompressing CD audio tracks
if "%~1"=="1" echo ---------------------------------------------------------
if "%~1"=="1" flac -d --delete-input-file --force-raw-format --endian little --sign=signed *.flac
if "%~1"=="" flac -d --silent --delete-input-file --force-raw-format --endian little --sign=signed *.flac
rename *.raw *.bin
rem del *.flac
goto verify

:verify
if "%~1"=="1" echo ---------------------------------------------------------
echo Verifying Checksums
if "%~1"=="1" echo ---------------------------------------------------------
rem removed-1
if "%~1"=="1" call hashsum.bat /c /nh /ns uncompressed.sha256 
if "%~1"=="" call hashsum.bat /c /nh /nm uncompressed.sha256 
	IF %ERRORLEVEL% EQU 0 GOTO success
	set errormsg=Checksum verification failure.
GOTO error

:success
IF EXIST "*.arc" ( 
del *.arc
)
IF EXIST "uncompressed.sha256" ( 
del uncompressed.sha256
)

if "%~1"=="" cls
if "%~1"=="" color 2f
if "%~1"=="" call psxminimise-header.bat
echo Unpacking has been completed successfully.
if "%~1"=="" timeout /T 5
GOTO END

:error
color 4F
if "%~1"=="1" echo ---------------------------------------------------------
if "%~1"=="" color 4f
echo An error %ERRORLEVEL% occured.
echo %errormsg%
if "%~1"=="1" echo ---------------------------------------------------------
if "%~1"=="" pause
GOTO END
:end
