@echo off

REM Welp, this was pointless.
REM
REM There's really no way to put raw PCM audio
REM in an MP4 container. MP4 is already a really
REM shitty format for a number of other reasons
REM (no real subtitle support, VERY limited codec
REM options, etc.), which is why I prefer using
REM Matroska for literally anything outside of
REM Vegas.
REM
REM However, I learned how to make an arguments
REM parser in fucking Batch out of all things,
REM so maybe there was a purpose for this after
REM all.
REM
REM TL;DR: I didn't even come close to solving the
REM problem this was meant to fix, and MP4 is a
REM godawful container. :D

setlocal EnableDelayedExpansion
call :argparser %*
if %count% LSS 3 goto usage
if not exist "%inputmp4%" (
	call :error "Input MP4 file doesn't exist!"
	goto usage
)
if not exist "%inputwav%" (
	call :error "Input WAV file doesn't exist!"
	goto usage
)
if exist "%outputmp4%" call :warning "Output MP4 file already exists!"
REM mp4 barely supports flac, matroska ftw
REM
REM vegas pro sucks and has barely any support
REM for different codecs in MP4s (see: yuv 4:4:4),
REM and really *only* supports AAC. this sucks,
REM cause AAC can be a bitch at times
if not defined acodec set "acodec=flac"

ffmpeg -y -i "!inputmp4!" -i "!inputwav!" -c:v copy -c:a !acodec! ^
	-strict -2 -loglevel quiet -stats "!outputmp4!"
goto cleanup

:usage
echo.Usage:
echo.  %~n0.bat ^<input.mp4^> ^<input.wav^> ^<output.mp4^> [--acodec ^<codec^>]
echo.          [--debug]
echo.
echo.Arguments:
echo.  ^<input.mp4^>:        input mp4 with at least 1 video stream
echo.  ^<input.wav^>:        input wav (or flac)
echo.  ^<output.mp4^>:       output mp4
echo.  [--acodec ^<codec^>]: (optional) audio codec to use
echo.  [--debug]:          prints all commands to the terminal
echo.
REM we don't know if the user is running from a terminal or not...
echo.Press any key to exit...
pause 1>NUL 2>&1

:cleanup
REM this MIGHT fuck up someone's environment variables
REM i don't care :). deal with it
set "inputmp4="
set "inputwav="
set "outputmp4="
set "acodec="
set "count="
exit /b 0

REM -------------- Functions --------------

:argparser
	set "count=0"
:argparser_loop
	if not "x%~1x" == "xx" (
		set "var=%~1"
		if "!var:~0,2!"=="--" (
			if "!var!"=="--acodec" (
				shift
				set "acodec=%~2"
				goto :argparser_end
			)
			if "!var!"=="--debug" (
				@echo on
				goto :argparser_end
			)
		) else (
			if %count% EQU 0 set "inputmp4=%~1"
			if %count% EQU 1 set "inputwav=%~1"
			if %count% EQU 2 set "outputmp4=%~1"
			set /a "count+=1"
		)
		:argparser_end
		shift
		goto :argparser_loop
	)
	set "var="
exit /b 0

:error
	echo [ERROR]: %~1
exit /b 0

:warning
	echo [WARNING]: %~1
exit /b 0

:info
	echo [INFO]: %~1
exit /b 0
