@IF EXIST "%~dp0Output\%~n1.mp4" GOTO exist
@IF EXIST "%~dpn1.mkv" GOTO matroska
@IF EXIST "%~dpn1.avi" GOTO avi
GOTO other

:matroska
START /LOW /B /WAIT "" "%~dp0Tools\MediaInfo.exe" --Inform=Text;%%ID%% "%~f1" > "%~dp0Temp\text_id"
set /p text_id_t= < "%~dp0Temp\text_id"
set text_id=%text_id_t:~0,1%
set /a text_id_2= %text_id% - 1
START /LOW /B /WAIT "" "%~dp0Tools\mkvextract.exe" tracks "%~f1" %text_id_2%:"%~dp0Temp\%~n1_subs.ass"
echo LoadPlugin("%~dp0Tools\vsfilter.dll") > "%~dp0Temp\%~n1_Avisynth.avs"
echo LoadPlugin("%~dp0Tools\ffms2.dll") >> "%~dp0Temp\%~n1_Avisynth.avs"
echo Import("%~dp0Tools\FFMS2.avsi") >> "%~dp0Temp\%~n1_Avisynth.avs"
echo Fonts = DirectShowSource("%~f1", video=false) >> "%~dp0Temp\%~n1_Avisynth.avs"
echo FFVideoSource("%~f1") >> "%~dp0Temp\%~n1_Avisynth.avs"
echo TextSub("%~dp0Temp\%~n1_subs.ass") >> "%~dp0Temp\%~n1_Avisynth.avs"
echo AudioDub(BlankClip, DirectShowSource("%~f1", video=false)) > "%~dp0Temp\%~n1_audio.avs"
START /LOW /B /WAIT "" "%~dp0Tools\avs2pipemod.exe" -wav "%~dp0Temp\%~n1_audio.avs" | "%~dp0Tools\neroAacEnc.exe" -q 0.7 -lc -ignorelength -if - -of "%~dp0Temp\%~n1_audio.m4a"
START /LOW /B /WAIT "" "%~dp0Tools\x264.exe" --preset slow --psy-rd 0.7:0.0 --crf 19 --audiofile "%~dp0Temp\%~n1_audio.m4a" --acodec copy --output "%~dp0Output\%~n1.mp4" "%~dp0Temp\%~n1_Avisynth.avs"
del "%~dp0Temp\%~n1_audio.m4a"
del "%~dp0Temp\%~n1_Avisynth.avs"
del "%~dp0Temp\%~n1_audio.avs"
del "%~f1.ffindex"
del "%~dp0Temp\%~n1_subs.ass"
del "%~dp0Temp\text_id"
goto end

:other
echo LoadPlugin("%~dp0Tools\ffms2.dll") > "%~dp0Temp\%~n1_Avisynth.avs"
echo Import("%~dp0Tools\FFMS2.avsi") >> "%~dp0Temp\%~n1_Avisynth.avs"
echo FFVideoSource("%~f1") >> "%~dp0Temp\%~n1_Avisynth.avs"
echo Spline36Resize(960,544) >> "%~dp0Temp\%~n1_Avisynth.avs"
START /LOW /B /WAIT "" "%~dp0Tools\x264.exe" --preset slow --psy-rd 0.7:0.0 --crf 19 --audiofile "%~f1" --acodec copy --output "%~dp0Output\%~n1.mp4" "%~dp0Temp\%~n1_Avisynth.avs"
del "%~dp0Temp\%~n1_Avisynth.avs"
del "%~f1.ffindex"
goto end

:avi
echo AVISource("%~f1") > "%~dp0Temp\%~n1_Avisynth.avs"
echo Spline36Resize(960,544) >> "%~dp0Temp\%~n1_Avisynth.avs"
START /LOW /B /WAIT "" "%~dp0Tools\x264.exe" --preset slow --psy-rd 0.7:0.0 --crf 19 --audiofile "%~f1" --acodec copy --output "%~dp0Output\%~n1.mp4" "%~dp0Temp\%~n1_Avisynth.avs"
del "%~dp0Temp\%~n1_Avisynth.avs"
goto end

:exist
@echo off
cls
color 0c
echo.
echo.
echo.
echo.
echo.
echo.
echo.
echo.
echo.
echo             File already encoded - See %~dp0Output
echo.
pause > NUL
:end