@echo off
mode con: cols=80 lines=40
rem -- create input and output folders
if not exist .\[EFE_IN] mkdir [EFE_IN]
if not exist .\[WAV_OUT] mkdir [WAV_OUT]
cls
echo ####################################
echo # Ensoniq EFE to WAV Decoder v0.40 #
echo ####################################
echo.
echo Input files must be Ensoniq instruments (EFE/EFA/INS) placed within the 
echo [EFE_IN] folder. Files extracted by various Ensoniq utilities such as 
echo EpsLin, EPSDisk, EnsoniqFS, and Translator are accepted. 
echo.
echo Sub-folders within [EFE_IN] are also supported. 
echo.
echo Each EFE instrument will be extracted to WAVs and placed in a corresponding 
echo sub-folder within the parent [WAV_OUT] folder. 
echo.
pause
echo.

rem -- check for required tools and metadata
if not exist .\tools\sox\sox.exe (
	echo Critical Error: SoX cannot be found. Aborting!
	goto ENDITALL
)
if not exist .\tools\EFE2WAV.exe (
	echo Critical Error: EFE2WAV cannot be found. Aborting!
	goto ENDITALL
)

rem -- check for any present EFA, EFE, or INS disk images, including within subfolders -- silences normal command output and also any errors produced by next "dir" command
dir /S /B /A-D .\[EFE_IN]\*.EFE .\[EFE_IN]\*.EFA .\[EFE_IN]\*.INS >NUL 2>&1
if %ERRORLEVEL% NEQ 0 (
	echo Critical Error: No EFA, EFE, or INS files found to convert. Aborting!
	goto ENDITALL
)

rem -- allows for dynamic variables within for loops when using !variable! instead of %variable%
setlocal ENABLEDELAYEDEXPANSION

rem scan entire [EFE_IN] folder for any EFA/EFE/INS banks present
rem needs delims== so for loop does not cut off at first space generated by DIR
for /F "delims==" %%R in ('dir /S /B /A-D .\[EFE_IN]\*.EFE .\[EFE_IN]\*.EFA .\[EFE_IN]\*.INS') do (
	echo Extracting WAVs from "%%~NR"...
	echo.
	.\tools\EFE2WAV "%%R"
	if !ERRORLEVEL! EQU 0 (
		echo %%~NR has been extracted to WAV.
	) else (
		echo Warning: %%~NR could not be extracted to WAV.
	)
	if not exist ".\[WAV_OUT]\%%~NR" mkdir ".\[WAV_OUT]\%%~NR" >NUL
	if exist *.WAV move *.WAV ".\[WAV_OUT]\%%~NR" >NUL
	echo.
)

rem -- disable delayed expansion for the rest of the batch (return ability to use exclamations and carets)
ENDLOCAL

rem -- remove any annoying [03] extensions in WAV directories -- silences normal command output and also any errors produced by next "dir" command
dir /S /B /AD .\[WAV_OUT]\*.[??] >NUL 2>&1
if %ERRORLEVEL% equ 0 (
	rem needs delims== so for loop does not cut off at first space generated by DIR
	for /F "delims==" %%d in ('dir /S /B /AD .\[WAV_OUT]\*.[??]') do (
		rem -- change any [xx] directories to straight name
		ren "%%d" "%%~Nd." >NUL 2>&1
	)
)

echo Process complete.
echo.
echo WAV files should now be present within the [WAV_OUT] folder.

:ENDITALL
echo.
pause