Anri-chan/Source/anri.bat

From SDA Knowledge Base

< Anri-chan‎ | Source
Revision as of 14:24, 6 December 2009 by Ballofsnow (Talk | contribs)

Jump to: navigation, search
@ECHO OFF

REM ---------------------------------------------------------------------------
REM                                   Credits
REM ---------------------------------------------------------------------------

REM metroid 2002 speed demos archive anri-chan
REM http://www.metroid2002.com/
REM http://speeddemosarchive.com/
REM nathan jahnke <njahnke@gmail.com>
REM Ian Bennett
REM Philip "ballofsnow" Cornell
REM Brett "Psonar" Ables


REM ---------------------------------------------------------------------------
REM             Set Anri-chan to low priority mode. ( & other params)
REM
REM  Environment variables remain even if you call anri-chan on top of itself.
REM  So don't worry about losing information. The loop looks for parameters
REM  that have been sent to anri.bat. Order doesn't matter as you can see. When
REM  setting anri.bat to low priority, you send the parameter "anrilow" so that
REM  anri-chan knows, and doesn't go into an infinite loop.
REM ---------------------------------------------------------------------------

FOR %%G IN (%*) DO (
  IF %%G==anrilow (SET anrilow=y)
  IF %%G==samplemode (SET samplemode=y)
  IF %%G==auto (SET auto=y)
)
IF NOT DEFINED anrilow ( GOTO setanribat )


REM ---------------------------------------------------------------------------
REM                                Initialisation
REM
REM Some obvious stuff in here. todo: describe desktop location
REM ---------------------------------------------------------------------------

(SET anri_ver=3)
(SET in_anrichan=y)
REM includes \
SET anri_dir=%~dp0
SET anri_path=%~dp0anri.bat
(SET dgmpgdec_dir=dgmpgdec150)
(SET vdub=virtualdub-1.9.7)

REM ---------------------------------------------------------------------------
REM                              Color Initialization
REM
REM Edit by: Psonar  -  Brett Ables
REM Below is the code necessary to use the CECHO.exe function
REM to add color to anrichan. Run CECHO.exe /? for usage help.
REM CECHO.exe was written by Thomas Polaert.
REM
REM The environment variable CECHO is set to the absolute path
REM of the CECHO.exe program so that %CECHO% may be used 
REM to call the function regardless of the working directory
REM
REM RESET_COLOR is used to reset the default color scheme 
REM after CECHO has been used to output different colors.
REM
REM Color is a DOS function that affects the whole command 
REM window at once.  It is used only once here to initialize the
REM background color of the window. 80 is the same as {black on gray}.
REM 
REM CECHO is used in out_cls, out_info, out_error, and out_section.
REM ---------------------------------------------------------------------------

(SET CECHO="%anri_dir%cecho.exe")
(SET RESET_COLOR=%CECHO% {black on gray})
Color 80

REM ----------------- End Color Initialization ----------------------------

REM log name
(SET log=log_%time%)
(SET log=%log::=%)
(SET log=%log: =%)
(SET log=%log:.=%.txt)

REM get the name of the desktop ... old method for safety...
(SET DESKTOP=%HOMEDRIVE%%HOMEPATH%\desktop)
REM then new method..
FOR /F "skip=4 tokens=2 delims=\" %%G IN ('REG QUERY "hkcu\software\microsoft\windows\currentversion\explorer\user shell folders" /v desktop') DO SET desktop=%HOMEDRIVE%%HOMEPATH%\%%G

REG ADD "HKEY_CURRENT_USER\Software\VirtualDub.org\VirtualDub\Persistence" /v "Update input pane" /t REG_DWORD /d 1 /f > NUL
REG ADD "HKEY_CURRENT_USER\Software\VirtualDub.org\VirtualDub\Persistence" /v "Update output pane" /t REG_DWORD /d 0 /f > NUL

CALL "%anri_dir%ini.bat"
IF NOT DEFINED project_parentdir SET project_parentdir=%DESKTOP%

REM ---------------------------------------------------------------------------
REM                                Main menu
REM 
REM  Anri-chan's home. 
REM ---------------------------------------------------------------------------

:proc_main
CALL :out_cls
IF "%main_anri_updated%"=="y" GOTO die
IF "%using_settings%"=="y" GOTO proc_check_settings
CALL :out_cls
CALL :out_info ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!
CALL :out_section Main
rem IF NOT "%auto%"=="y" (CALL :q_projname)

:q_main_options
ECHO  1. Rip DVD to hard drive (required for DVD material)
ECHO  2. Start new project
ECHO  3. Extract sample (for DFnD)
ECHO  4. Station ID preview
ECHO  5. Exit
ECHO.
SET s=
SET /P s=[1-5]: 
CALL :set_var_in mainoption q_main_options 12345

IF %mainoption%==1 CALL :rip_dvd
IF %mainoption%==2 CALL :project
IF %mainoption%==3 CALL :proc_sample
IF %mainoption%==4 CALL "%anri_dir%statid.bat"
IF %mainoption%==5 GOTO :DIE

GOTO :proc_main

REM ---------------------------------------------------------------------------
REM                          Sample extraction procedure
REM 
REM  Sample extraction is basically regular mode minus a bunch of questions.
REM  There isn't much documentation about how this works since this was
REM  meant to be short. One thing that's different is that the sample video
REM  will have separated fields. This is to avoid the problem with interlacing
REM  and the Yv12 colorspace.
REM ---------------------------------------------------------------------------

:proc_sample
CALL :out_cls
SETLOCAL ENABLEDELAYEDEXPANSION
CD /D "%DESKTOP%"
(SET no_pause_before_indexing=y)
(SET projname=sample)
CALL :make_projdir
CALL :load_plugins
CALL :out_cls_section Sample extraction
CALL :q_dvdsource
IF "%dvdsource%"=="y" (
  CALL :index_dvd
) ELSE CALL :q_avi
CALL :out_info This sample will be 300 frames long, pick the starting frame of a scene with action.
COPY /B "sample.avs" "sample_trimtemp.avs" 1> NUL
ECHO lanczos4resize^(320,240^) >> "sample_trimtemp.avs"
PAUSE
START "trimming vdub" "%anri_dir%%vdub%\virtualdub.exe" "sample_trimtemp.avs"
CALL :q_trimval
SET /A trim2=!trimval! + 299
ECHO trim^(!trimval!,!trim2!^) >> sample.avs
ECHO AssumeTFF >> sample.avs
ECHO SeparateFields >> sample.avs
ECHO last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP >> sample.avs
ECHO converttoyv12 >> sample.avs
CALL :1pass sample.avs sample 128000 19 1
DEL sample*.avs 2> NUL | DEL sample.bak 2> NUL | DEL sample*.d2v 2> NUL | DEL sampleVTS* 2> NUL | DEL log*.txt 2> NUL
ECHO.
ECHO.
%CECHO% "{white on gray}Finished. You will find a sample folder on your desktop. Feel free to rename the video to something more descriptive like nameofgame_sample.mp4.{\n}"
ECHO.
%CECHO% "{red on gray} - READ -{white on gray} You will see that the video has been resized vertically (it's slightly more complicated than that..), {red on gray}THIS IS NORMAL{white on gray} and will make it easier for the techies to help you.{\n}"
%RESET_COLOR%
ECHO.
PAUSE
@ECHO ON
ENDLOCAL ENABLEDELAYEDEXPANSION
EXIT

REM ---------------------------------------------------------------------------
REM                              Main procedure
REM 
REM  Anri-chan's home.. housing the program flow. This is beginning to end for
REM  encoding the video.
REM 
REM  The first section sets up the project name and folder, or if one already
REM  exists it will find the existing settings and go to the encoding stage.
REM ---------------------------------------------------------------------------

:project
CALL :out_cls
CALL :out_info ON HERMESUS LUC ARSUS ESTARIAS AUC ELTRAS LI CELES! Now, let's get to work!
CALL :out_section PROJECT SETUP
IF NOT "%auto%"=="y" (CALL :q_projname)
CALL :make_projdir
CALL :load_plugins
CALL :find_existing_settings
IF "%using_settings%"=="y" GOTO proc_check_settings

REM ---------------------------------------------------------------------------
REM  Main procedure - Movie source
REM 
REM  It's either DVD or AVI, no exceptions (for now). The current method for
REM  DVD extraction is as follows: Find and validate the DVD folder. Check for
REM  the existence of IFO files (has details on structure of DVD). If they are
REM  found, the IFO is analyzed and ripped with Mplayer. Otherwise it goes
REM  straight to DGindex.
REM
REM  Why Mplayer? It has the ability to rip files per program chain. There is
REM  a problem where indexing multiple program chains can cause audio desync.
REM  Now that we get the data on a per PGC basis, we can index them individually
REM  and join them up later in AviSynth which can properly align video/audio.
REM 
REM  There are two methods for loading AVI files. Either the user enters the
REM  paths to the file individually, or specifies a directory and anri-chan
REM  loads all AVI files alphabetically. There is currently no validation for
REM  AVI files with different video properties.
REM ---------------------------------------------------------------------------

CALL :out_cls_section MOVIE SOURCE
CALL :out_info If you used a capture card with DVD or MPEG settings, place those files in
CALL :out_info %dvdripto_parentdir%\foldername\ and then answer y to the question below.
ECHO.
IF NOT "%auto%"=="y" CALL :q_dvdsource
IF "%dvdsource%"=="y" (
  REM automation changes for q_driveletter are handled within the function b/c 
  REM important code related to ripping and dgindex is found there.
  CALL :index_dvd
) ELSE (
  REM q_avi must be called (even in "auto" mode) for avs files to be set up properly
  CALL :q_avi
)

REM ---------------------------------------------------------------------------
REM  Main procedure - Movie source verification and properties
REM 
REM Verify that AviSynth can load the source files. Also an opportunity to
REM extract media info.
REM ---------------------------------------------------------------------------

ECHO.
ECHO Verifying source...
COPY /Y "%projname%.avs" "%projname%_verifysource.avs" > NUL
REM Grab some properties of the video while we're here..
ECHO WriteFileStart^("mediainfo.txt",	""" "Width:" """,					"last.Width",					append=false^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "Height:" """,					"last.Height",					append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "FrameCount:" """,				"last.FrameCount",				append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "FrameRate:" """,				"last.FrameRate",				append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "FrameRateNumerator:" """,		"last.FrameRateNumerator",		append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "FrameRateDenominator:" """,	"last.FrameRateDenominator",	append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "AudioRate:" """,				"last.AudioRate",				append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "AudioLength:" """,				"last.AudioLength",				append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "AudioLengthF:" """,			"last.AudioLengthF",			append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "AudioChannels:" """,			"last.AudioChannels",			append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "AudioBits:" """,				"last.AudioBits",				append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "IsAudioFloat:" """,			"last.IsAudioFloat",			append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "IsAudioInt:" """,				"last.IsAudioInt",				append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "HasAudio:" """,				"last.HasAudio",				append=true^) >> "%projname%_verifysource.avs"
ECHO WriteFileStart^("mediainfo.txt",	""" "HasVideo:" """,				"last.HasVideo",				append=true^) >> "%projname%_verifysource.avs"
ECHO trim^(0,-1^) >> "%projname%_verifysource.avs"
"%anri_dir%%vdub%\vdub.exe" /i "%anri_dir%RunNullVideoPass.vcf" "%projname%_verifysource.avs" > NUL
IF NOT %ERRORLEVEL%==0 (
  CALL :out_error There was a problem loading the videos.
  ECHO Possible causes:
  ECHO  - Path to video file no longer valid
  ECHO  - Video codec not installed properly
  ECHO  - The videos do not have the same resolution and/or framerate
  ECHO.
  ECHO Ask for help in the Tech Support forum.
  ECHO Anri will now exit.
  ECHO.
  GOTO :DIE
)
DEL "%projname%_verifysource.avs" > NUL


REM ---------------------------------------------------------------------------
REM  Main procedure - Game properties
REM 
REM  The purpose here is to find resolution, framerate and whether there are
REM  flickering effects in the game. An online database is maintained at
REM  http://speeddemosarchive.com/kb/index.php/DF to hold this information since
REM  there isn't really a way to do it programmatically. Probably need C++ for
REM  that... but even then. 
REM  
REM  SDA has decided on minimum quantizers of 17 and 19 for low/high resolution
REM  videos.
REM ---------------------------------------------------------------------------

:proc_gameproperties
CALL :out_cls_section GAME PROPERTIES
IF "%dvdsource%"=="n" (
  IF NOT "%auto%"=="y" (
    CALL :out_info Is this a PC game recorded with screen capture software, or simply a non-console run? If you say no, your video will be treated as NTSC / PAL.
    CALL :q_isPCGAME
  )
)
IF "%isPCGAME%"=="y" (
  IF NOT DEFINED d      (SET d=1)
  IF NOT DEFINED f      (SET f=1)
  IF NOT DEFINED twod   (SET twod=n)
  IF NOT DEFINED hqq    (SET hqq=19)
  IF NOT DEFINED prog   (SET prog=y)
  GOTO proc_gameproperties_p2
)

IF NOT "%auto%"=="y" CALL :q_dfnd
IF "%dfnd_set%"=="y" GOTO dfnd_is_set
IF NOT "%auto%"=="y" CALL :q_d
IF NOT "%auto%"=="y" CALL :q_f
IF NOT "%f%"=="1" (SET twod=n) ELSE (
    IF NOT "%auto%"=="y" (
        CALL :q_2d
    )
)
IF NOT "%auto%"=="y" CALL :q_submit_dfnd
:dfnd_is_set
IF "%d%"=="4" SET hqq=17
IF "%d%"=="1" SET hqq=19

REM ---------------------------------------------------------------------------
REM  Main procedure - Video properties
REM 
REM  Wouldn't it be great if there was no more interlacing and everything was
REM  progressive? As you can see, if the video is progressive you pretty much
REM  skip the entire section. Anyways..
REM 
REM  The method for getting the field order is to open up an instance of vdub 
REM  with the video, the top half of the screen using Top Field First, and the
REM  bottom half using Bottom Field First. The user then plays it to see which
REM  one looks natural and chooses top or bottom accordingly.
REM  
REM  onepixel simply shifts one of the fields up or down by one pixel.
REM  
REM  TO DO: Describe nes, gba, deflicker.
REM ---------------------------------------------------------------------------

CALL :out_cls_section VIDEO PROPERTIES
IF NOT "%auto%"=="y" (
  CALL :out_info Progressive or interlaced? If you don't know, it's most likely interlaced ^(answer "n" to the question^). However, if your video is a PC screen capture ^(made using e.g. FRAPS or Camtasia^) and never touched a VCR or DVD recorder, then it may be progressive.
  CALL :q_prog
)
IF "%prog%"=="y" GOTO proc_gameproperties_p2
IF NOT "%auto%"=="y" CALL :q_fieldorder
IF NOT "%auto%"=="y" CALL :q_vhs
IF "%d%"=="1" GOTO proc_gameproperties_p2
IF NOT "%f%"=="2" (
    IF NOT "%auto%"=="y" CALL :q_onepixel
)
IF NOT "%auto%"=="y" CALL :q_nes
IF "%nes%"=="y" GOTO proc_gameproperties_p2
IF NOT "%auto%"=="y" CALL :q_gba
IF "%gba%"=="y" (
  SET deflicker=y
  GOTO proc_gameproperties_p2
)
IF NOT "%auto%"=="y" CALL :q_gameboy
IF "%gameboy%"=="y" (
  SET deflicker=y
  GOTO proc_gameproperties_p2
)
IF NOT "%f%"=="2" (
    IF NOT "%auto%"=="y" CALL :q_deflicker
)
    
REM ---------------------------------------------------------------------------
REM  Main procedure - Content properties
REM 
REM  For trimming, we startup another vdub instance and ask the user to input
REM  frame numbers. The frame numbers will go into a single variable separated
REM  by spaces. There is currently no validation for entering a frame range
REM  like 50 to 30... or negative numbers. Users can enter dummy values and edit
REM  project_job.bat later on and it will still work.
REM 
REM  StatID.. not much to it. Three lines, quotations are allowed. Gets appended
REM  at beginning and end of video.
REM ---------------------------------------------------------------------------

:proc_gameproperties_p2
CALL :out_cls_section CONTENT PROPERTIES
IF NOT "%auto%"=="y" CALL :q_trim
IF "%trim%"=="y" (IF NOT "%auto%"=="y" CALL :q_trimming)
IF NOT "%auto%"=="y" CALL :q_widescreen
IF NOT "%auto%"=="y" (CALL :q_statid)
IF "%statid%"=="y" (IF NOT "%auto%"=="y" CALL :q_statid_lines)

REM ---------------------------------------------------------------------------
REM  Main procedure - Check settings
REM 
REM  This is where you get taken when you run project_job.bat. A file compare
REM  is done to check if the user has edited job.bat. If it has been changed,
REM  or if there are missing AviSynth files, the files are rebuilt. So if
REM  someone is tinkering with the AviSynth files, they'd be wise to leave
REM  job.bat alone, else have their work be overwritten.
REM ---------------------------------------------------------------------------

:proc_check_settings
CD /D "%project_parentdir%\%projname%"
SET projdirpath=%CD%
CALL :filecompare "%PROJNAME%_job.bat" "%PROJNAME%_job.bak"
REM Yay batch code...
SET multipleif=false
IF %callresult%==0 IF EXIST "%PROJNAME%_LQ.avs" IF EXIST "%PROJNAME%_LQ_xvid.avs" IF EXIST "%PROJNAME%.avs" IF EXIST "%PROJNAME%_xvid.avs" IF EXIST "%PROJNAME%_HQ.avs" IF EXIST "%PROJNAME%_IQ.avs" SET multipleif=true
IF %multipleif%==false (
  CALL :savesettings
  CALL :script_buildfiles
)

REM ---------------------------------------------------------------------------
REM  Main procedure - Check settings (continued)
REM 
REM  All necessary files are ready for the encoding stage. Show the user the
REM  current settings, then ask if they want to encode now. Saying no will reset
REM  some variables and take the user back to Game Properties (DFnD).
REM ---------------------------------------------------------------------------

IF NOT "%auto%"=="y" (
  CALL :check_settings
) ELSE (
  SET settings_good=y
)
IF NOT "%settings_good%"=="y" GOTO proc_check_settings_p2
CALL :out_cls_section READY TO ENCODE
CALL :out_info Your settings for this project have been saved to "%projname%_job.bat". To resume the project, double-click that file.
IF NOT "%auto%"=="y" (
  CALL :q_encodenow
) ELSE (
  SET start_encode=y
)
IF "%start_encode%"=="y" (GOTO proc_encode) ELSE (GOTO proc_close)
:proc_check_settings_p2
FOR %%A IN (dfnd_set d f twod fieldorder vhs onepixel nes gba gameboy deflicker trimarray) DO (SET %%A=)
SET batch=
DEL "%PROJNAME%_job.bat"
DEL "%PROJNAME%_job.bak"
GOTO proc_gameproperties

REM ---------------------------------------------------------------------------
REM  Main procedure - Encoding options
REM 
REM  Ask for H.264 LQ/MQ/HQ/IQ, and Xvid LQ/MQ.
REM 
REM  IF D1 and the user is encoding HQ/IQ/XQ, he will be asked whether
REM  he wants to encode a New Master File. This is to avoid using the extremely
REM  slow mvbob deinterlacer four times, one for each pass. Instead, it will be
REM  done once and encoded to the lossless Lagarith codec in Yv12 colorspace.
REM  This NMF will then be used to encode HQ/IQ.
REM ---------------------------------------------------------------------------

:proc_encode
CALL :out_cls_section ENCODING OPTIONS
IF NOT "%auto%"=="y" CALL :select_qualities
REM Batch has limited boolean logic. I want an OR between hq/iq/xq.
IF "%d%"=="1" IF "%prog%"=="n" IF "%create_hq%"=="y" (
  CALL :NMF
) ELSE (
  IF "%create_iq%"=="y" (
    CALL :nmf
  ) ELSE (
    IF "%create_xq%"=="y" (
      CALL :nmf
    )
  )
)
REM IF "%not_encoding%"=="y" GOTO proc_close
REM see below comment for more about this
REM CALL :out_cls_info Now encoding.
CALL :encode_movies

MD finished > NUL 2>&1

FOR %%G IN (*.bat) DO (
  ECHO ---------------------------------------- >> .\finished\%log%
  ECHO  Contents of %%G >> finished\%log%
  ECHO ---------------------------------------- >> finished\%log%
  ECHO. >> finished\%log%
  TYPE "%%G" >> finished\%log%
  ECHO. >> finished\%log%
  ECHO. >> finished\%log%
  ECHO. >> finished\%log%
)

ECHO ---------------------------------------- >> finished\%log%
ECHO  Contents of project folder >> finished\%log%
ECHO ---------------------------------------- >> finished\%log%
ECHO. >> finished\%log%
DIR >> finished\%log%
ECHO. >> finished\%log%
ECHO. >> finished\%log%

FOR %%G IN (*.avs) DO (
  ECHO ---------------------------------------- >> finished\%log%
  ECHO  Contents of %%G >> finished\%log%
  ECHO ---------------------------------------- >> finished\%log%
  ECHO. >> finished\%log%
  TYPE "%%G" >> finished\%log%
  ECHO. >> finished\%log%
  ECHO. >> finished\%log%
  ECHO. >> finished\%log%
)

FOR %%G IN (*.log) DO (
  ECHO ---------------------------------------- >> finished\%log%
  ECHO  Contents of %%G >> finished\%log%
  ECHO ---------------------------------------- >> finished\%log%
  ECHO. >> finished\%log%
  TYPE "%%G" >> finished\%log%
  ECHO. >> finished\%log%
  ECHO. >> finished\%log%
  ECHO. >> finished\%log%
)
COPY finished\%log% finished\%log:~0,-4%.bak > NUL
ATTRIB +H finished\%log:~0,-4%.bak

MOVE /Y %PROJNAME%_LQ.avi finished > NUL 2>&1
MOVE /Y %PROJNAME%.avi    finished > NUL 2>&1
MOVE /Y %PROJNAME%_LQ.mp4 finished > NUL 2>&1
MOVE /Y %PROJNAME%.mp4    finished > NUL 2>&1
MOVE /Y %PROJNAME%_HQ.mp4 finished > NUL 2>&1
MOVE /Y %PROJNAME%_IQ.mp4 finished > NUL 2>&1
MOVE /Y %PROJNAME%_XQ.mp4 finished > NUL 2>&1


:proc_close
ECHO.
ECHO.
IF "%IQskipped%"=="true" (
  ECHO HQ reached the quality limit imposed by SDA. IQ/XQ would reach the same limit, therefore it has been skipped. | "%anri_dir%tee.exe" -a finished\read.txt
  ECHO. | "%anri_dir%tee.exe" -a finished\read.txt
)
rem IF "%XQskipped%"=="true" (
CALL :out_info All dun.
ECHO.
GOTO die


REM ------- QUESTIONS ABOUT MOVIE SOURCE -------

:q_projname

CALL :out_info Enter a project name. This name will be used as the basename for your encoded videos (e.g. the high quality video will be called projectname_HQ.mp4, etc.).
ECHO.
%CECHO% "{white on gray}All files associated with this project will appear in {navy on gray}%project_parentdir%\(project name)\{\n}"
%RESET_COLOR%
ECHO.
SET s=
SET /P s=Project name (no spaces allowed): 
CALL :set_var_nospace projname q_projname
ECHO %projname%|findStr /c:"%%">nul
IF %ERRORLEVEL%==0 (
  CALL :out_error Invalid value. You cannot have a percent sign.
  GOTO q_projname
)
GOTO :EOF


:q_dfnd
CALL :out_info The next few questions are about the game played in this video. SDA has a database of games we have seen in the past, which can answer some or all of the questions for you.
SET s=
SET /P s=Do you want to use Anri-chan's games database [Y] or enter the data yourself [N]? [y,n] 
CALL :set_var_bool dfnd q_dfnd
IF "%dfnd%"=="y" CALL :dfnd
GOTO :EOF

:q_dvdsource
SET s=
SET /P s=DVD/MPEG source [y,n]: 
CALL :set_var_bool dvdsource q_dvdsource
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: rip_dvd
REM  
REM  If IFO files are present, rip with Mplayer. Otherwise just a straight copy.
REM ---------------------------------------------------------------------------

:rip_dvd
SETLOCAL ENABLEDELAYEDEXPANSION
CALL :out_cls_section Rip DVD
CALL :q_driveletter
ECHO.
CALL :out_info Anri-chan will extract to the %dvdripto_parentdir% parent directory. Name a folder for your DVD files.
:rip_dvd_dir
SET /P dvdripto=Folder name: 
REM Validate
IF NOT DEFINED dvdripto (
  CALL :out_error You must enter a valid folder name.
  GOTO :rip_dvd_dir
) ELSE (
  MKDIR "%dvdripto_parentdir%\%dvdripto%"
  IF !ERRORLEVEL!==1 (
    CALL :out_error You must enter a valid folder name.
    GOTO :rip_dvd_dir
  )
)
SET dvdripto=%dvdripto_parentdir%\%dvdripto%
ECHO.
CALL :out_info Anri-chan will now extract everything needed from the DVD to %dvdripto%. Make sure you have enough hard drive space (up to 4.3 GB). This may take some time.
ECHO.
PAUSE
PUSHD %dvdripto%

IF EXIST %driveletter%:\VIDEO_TS (
  SET dvdsource=%driveletter%:\VIDEO_TS
  IF EXIST !dvdsource!\*.IFO (
    REM Create pgclist.txt
    SET ifolist=
    FOR %%G IN (!dvdsource!\VTS*.IFO) DO (
      (SET ifolist=!ifolist!%%~fG )
    )    
    "%anri_dir%pgccount.exe" !ifolist!

    IF "%advanced_mode%"=="true" (
      IF NOT "%auto%"=="y" (
        ECHO.
        CALL :out_info -advanced mode- Rip specific title numbers. Separate by spaces, or leave blank to rip all. You can look at pgclist.txt in the DVD file destination directory to see which titles will be ripped by default.
        SET s=
        SET /P s=Title numbers: 
      ) ELSE (
        SET s=%auto_Title_numbers%
      )
      IF DEFINED s (
        REN pgclist.txt pgclist.bak
        FOR %%G IN (!s!) DO (
          TYPE pgclist.bak | FIND "%%G," >> pgclist.txt
        )
      )
    )

    REM Rip the titles with Mplayer using info from pgclist.txt
    FOR /F "tokens=1,2 delims=," %%G IN (pgclist.txt) DO (
      SET str=%%~nH
      SET str=!str:~4,2!
      REM Add leading zeros to avoid sorting problems where 10 comes before 1.
      SET expandpgc=00000000000%%G
      SET expandpgc=!expandpgc:~-3!
      "%anri_dir%mplayer.exe" dvd://%%G -dvd-device !dvdsource! -dumpstream -dumpfile I!str!_!expandpgc!.vob 2>> %log%
    )
  ) ELSE (
    COPY "!dvdsource!\*" "%dvdripto%"
  )
) ELSE (
  IF EXIST %driveletter%:\DVD_RTAV (
    COPY "%driveletter%:\DVD_RTAV\*" "%dvdripto%"
  ) ELSE (
    ECHO Neither VIDEO_TS or DVD_RTAV folder was found on %driveletter%:\. Anri-chan is displeased.
    goto :die
  )
)
POPD
CALL :out_info finished ripping
PAUSE
ENDLOCAL ENABLEDELAYEDEXPANSION
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: driveletter
REM 
REM  Ask for the drive letter.
REM ---------------------------------------------------------------------------

:q_driveletter
IF NOT "%auto%"=="y" (
  CALL :out_info Tip: If you already have your DVD source files on your hard drive, move them into C:\VIDEO_TS\ and select C as your drive letter.
  SET s=
  SET /P s=DVD Drive Letter: 
  CALL :set_var_letter driveletter q_driveletter
)
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: q_avi
REM 
REM  Ask the user if he wants to do manual input of file paths, or automatically
REM  by loading the files in a specified directory alphabetically. After the
REM  calls, this function expects file paths enclosed in quotations. If
REM  automatic, the %avifiles% array will only have the file names, and there 
REM  will be a variable %avifolder%. If manual, %avifolder% will be null and
REM  %avifiles% will have full paths to each file.
REM  
REM ---------------------------------------------------------------------------

:q_avi
SET maxaudiobitrate=320000
CALL :out_cls_section AVI SOURCE
CALL :out_info Enter the path to each avi file [i]ndividually or [a]utomatically. Note that if you choose automatic, anri-chan will load the files in an alphabetical manner. The files must have the same resolution and framerate to be joined together.
ECHO.
REM Avoiding nested IF's because of delayed expansion thing.
IF "%auto%"=="y" GOTO avimethod_skip
:q_avi_p2
SET s=
SET /P s=[i,a]: 
CALL :set_var_in avimethod q_avi_p2 ia
CALL :q_avi_%avimethod%
:avimethod_skip
REM ---------------------------------------------------------------------------
REM AVI files loaded, generate avs source lines.
REM ---------------------------------------------------------------------------
ECHO import^("%anri_dir%nate.avs"^) > "%projname%.avs"
ECHO import^("%projdirpath%\plugins.avs"^) >> "%projname%.avs"
SETLOCAL ENABLEDELAYEDEXPANSION
SET num=1
FOR %%G IN (%avifiles%) DO (
  IF NOT !num!==1 (
    ECHO \++\ >> "%projname%.avs"
  )
  "%anri_dir%cfourcc.exe" "%avifolder%%%~G" | FIND "Use :" > fourcc_temp.txt
  "%anri_dir%cfourcc.exe" "%avifolder%%%~G" >> running_log.txt
  SET useDshow=0
  FOR /F "tokens=1,2 delims=: " %%H IN (fourcc_temp.txt) DO (
    FOR /F %%J IN ('TYPE "%anri_dir%directshowsource_list.txt"') DO (
      IF /I "%%I"=="%%J" (
        SET /A useDshow=!useDshow!+1
      )
    )
  )
  IF !useDshow! GTR 0 (
    ECHO directshowsource^("%avifolder%%%~G"^) >> "%projname%.avs"
  ) ELSE (
    ECHO avisource^("%avifolder%%%~G"^) >> "%projname%.avs"
  )
  DEL fourcc_temp.txt
  SET /A num=!num!+1
)
ENDLOCAL ENABLEDELAYEDEXPANSION
ECHO converttoyuy2^(^) >> "%projname%.avs"
COPY /Y "%projname%.avs" "%projname%.bak" > NUL
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: q_avi_i
REM 
REM  Manually add each file path enclosed in quotations to %avifiles%. Do some
REM  validation; no resolution check yet. Also sets avifolder to null so that
REM  the program will never think that automatic file loading is being used.
REM ---------------------------------------------------------------------------

:q_avi_i
SETLOCAL
ECHO.
CALL :out_info Path to source video file e.g. c:\path to\video.avi without quotes.
CALL :out_info  - Type n to quit -
ECHO.
SET avifiles=
SET counterA=0
SET counterB=1
:q_avi_i_p2
SET file=
SET /P file=avi#%counterB%: 
REM Validate
IF NOT "%file%"=="n" (
  IF NOT DEFINED file (
    CALL :out_error You must enter a path, or type n to quit.
    GOTO :q_avi_i_p2
  )
  IF NOT %file:~-4%==.avi (
    CALL :out_error Must be an avi file, try again.
    GOTO :q_avi_i_p2
  )
  IF NOT EXIST "%file%" (
    CALL :out_error File does not exist, try again.
    GOTO :q_avi_i_p2
  ) ELSE (
    (SET avifiles=%avifiles%"%file%" )
    SET /A counterA=%counterA% + 1
    SET /A counterB=%counterB% + 1
    GOTO :q_avi_i_p2
  )
) ELSE (
  IF %counterA%==0 (
    CALL :out_error You must load at least one avi file.
    GOTO :q_avi_i_p2
  )
)
ENDLOCAL & SET avifiles=%avifiles% & SET avifolder=
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: q_avi_a
REM 
REM  Automatic file loading. User just has to specify a directory and it will
REM  load the files alphabetically. Backslash is added to %avifolder% if not
REM  already there. After the validation part it changes to the specified
REM  directory. I was having trouble doing otherwise because of spaces in the
REM  path and batch's for loops aren't the greatest.. it changes back when it's
REM  done.
REM
REM  This function return a full avifolder path, and avifiles enclosed in quotes.
REM ---------------------------------------------------------------------------

:q_avi_a
ECHO.
CALL :out_info Path to folder e.g. c:\my video folder\ without quotes.
SET avifolder=
SET /P avifolder=: 
REM Validate avifolder. Check for blank, then :\ for full path, then try DIR.
IF NOT DEFINED avifolder (
  CALL :out_error You must enter a path.
  GOTO :q_avi_a
)
IF NOT "%avifolder:~1,2%"==":\" (
  CALL :out_error Must be full path.
  GOTO :q_avi_a
)
dir "%avifolder%" > NUL 2>&1
IF %ERRORLEVEL%==1 (
  CALL :out_error Folder does not exist
  GOTO :q_avi_a
)
REM Add backslash in avifolder if missing.
IF NOT "%avifolder:~-1%"=="\" SET avifolder=%avifolder%\
REM avifolder good, change directory. (Avoid trouble with for loop because of spaces in path)
CD /D %avifolder%
:q_avi_a_p2
REM Make avi file array.
SET avifiles=
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%G IN (*.avi) DO (
  (SET avifiles=!avifiles!"%%G" )
  ECHO %%G
)
SET avifiles=!avifiles:~0,-1!
ENDLOCAL ENABLEDELAYEDEXPANSION & SET avifiles=%avifiles%
REM Ask user if the list is good.
SET s=
SET /P s=Continue [Y] or rescan [N]? [y,n] 
IF NOT DEFINED s GOTO :q_avi_a_p2
IF NOT %s%==y GOTO :q_avi_a_p2
CD /D "%projdirpath%"
GOTO :EOF

:q_isPCGAME
SET s=
SET /P s=[y,n]: 
CALL :set_var_bool isPCGAME q_isPCGAME
GOTO :EOF

:q_d
ECHO.
CALL :out_info "D" and "F" are letters used at SDA to refer to the video dimensions and framerate. D1 is full resolution and D4 is half resolution. F1 is full framerate, F2 is half framerate and F3 is 1/3 framerate.
ECHO.
CALL :out_info   Find D and F for your game at this URL:
CALL :out_info   http://speeddemosarchive.com/kb/index.php/DF
ECHO.
CALL :out_info If you don't see your game listed there, you can use the Extract Sample utility to make a sample video to post in the SDA Tech Support Forum. Someone there will look at the video and let you know what D and F are.
ECHO.
:q_d_p2
SET s=
SET /P s=D [1,4]: 
CALL :set_var_in d q_d_p2 14
GOTO :EOF

:q_f
SET s=
(SET /P s=F [1,2,3]: )
CALL :set_var_in f q_f 12345
GOTO :EOF

:q_prog
SET s=
SET /P s=Progressive scan source? Answer n if you don't know [y,n]: 
CALL :set_var_bool prog q_prog
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: q_fieldorder
REM 
REM  There's no fool proof method to detect field order programmatically. The
REM  next best thing is to show the user both, and let him decide which looks
REM  better.
REM  
REM  The script is simple enough, have a split screen with AssumeTFF and
REM  AssumeBFF. Whichever is chosen will be used in all AviSynth script.
REM ---------------------------------------------------------------------------

:q_fieldorder
ECHO.
CALL :out_info Virtualdub will now open with a split screen of your video. Find a scene with movement and use the slider or play button to play through it to see which looks better. Enter t for top, or b for bottom. If both look good, enter t.
PAUSE
ECHO.
COPY /B "%projname%.bak" "%projname%_fieldordertemp.avs" 1> NUL
ECHO tff=last.AssumeTFF^(^).SeparateFields^(^).bilinearresize^(320,240^).subtitle^("t"^) >> "%projname%_fieldordertemp.avs"
ECHO bff=last.AssumeBFF^(^).SeparateFields^(^).bilinearresize^(320,240^).subtitle^("b"^) >> "%projname%_fieldordertemp.avs"
ECHO StackVertical^(tff,bff^) >> "%projname%_fieldordertemp.avs"
START "determine field order" "%anri_dir%%vdub%\virtualdub.exe" "%projname%_fieldordertemp.avs"
:q_fieldorder_p2
SET s=
SET /P s=[t,b]: 
CALL :set_var_in fieldorder q_fieldorder_p2 tb
CALL :out_info You may now close the VirtualDub window.
DEL "%projname%_fieldordertemp.avs"
ECHO.
GOTO :EOF

:q_vhs
SET s=
SET /P s=Originally VHS [y,n]: 
CALL :set_var_bool vhs q_vhs
GOTO :EOF

:q_onepixel
SET s=
SET /P s=1 pixel bob ... answer y if it's jumping up and down [y,n]: 
CALL :set_var_bool onepixel q_onepixel
GOTO :EOF

:q_nes
SET s=
SET /P s=NES [y,n]: 
CALL :set_var_bool nes q_nes
GOTO :EOF

:q_gba
SET s=
SET /P s=Game Boy Advance [y,n]: 
CALL :set_var_bool gba q_gba
GOTO :EOF

:q_gameboy
SET s=
SET /P s=Game Boy [y,n]: 
CALL :set_var_bool gameboy q_gameboy
GOTO :EOF

:q_deflicker
SET s=
SET /P s=Deflickered (rereleased old game e.g. Mega Man AC, Sonic Mega Collection, Wii Virtual Console) [y,n]: 
CALL :set_var_bool deflicker q_deflicker
GOTO :EOF

:q_2d
SET s=
SET /P s=2D game [y,n]: 
CALL :set_var_bool twod q_2d
GOTO :EOF

:q_trim
CALL :out_info Trimming lets you remove the start and end of the existing movie so you only keep the run itself.
:q_trim_p2
SET s=
SET /P s=Do you want to trim off unwanted content in this video? [y,n]: 
CALL :set_var_bool trim q_trim_p2
GOTO :EOF

:q_widescreen
ECHO.
CALL :out_info Set playback to widescreen. Say n if you don't know.
SET s=
SET /P s=Apply 16/9 widescreen [y,n]: 
CALL :set_var_bool widescreen q_widescreen
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: q_trimming
REM 
REM  Create an array of numbers separated by spaces which will be used later on
REM  when writing to the AviSynth scripts.
REM  
REM  There isn't much validation yet. A modulus of 2 is used to make sure there's
REM  an even number of values. No checking to see if the frame ranges are valid
REM  yet. No checking of negative values either.
REM ---------------------------------------------------------------------------

:q_trimming
ECHO.
CALL :out_info VirtualDub will now open with a low quality temporary version of the source video. Use the slider at the bottom of the VirtualDub window to locate the first and last frame numbers of the part of the video you WANT TO KEEP.
ECHO.
CALL :out_info You can specify multiple ranges of frames. - Type n to quit -
PAUSE
ECHO.
COPY /B "%projname%.bak" "%projname%_trimtemp.avs" 1> NUL
IF "%isPCGAME%"=="y" (
  ECHO Lanczos4Resize^(320,round^(last.height*^(320.000/last.width^)^)^) >> "%projname%_trimtemp.avs"
  ECHO last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP >> "%projname%_trimtemp.avs"
  ECHO last >> "%projname%_trimtemp.avs"
) ELSE (
  ECHO Lanczos4Resize^(320,240^) >> "%projname%_trimtemp.avs"
)
START "trimming vdub" "%anri_dir%%vdub%\virtualdub.exe" "%projname%_trimtemp.avs"
SET trimarray=
SET counterA=0
SET counterB=1
:trimloop
SET /A counterC=%counterA%/2+1
(SET qframe=Range#%counterC%/Frame#%counterB%: )
CALL :q_trimval
IF NOT "%s%"=="n" (
  (SET trimarray=%trimarray%%trimval% )
  SET /A counterA=%counterA%+1
  SET /A counterB=%counterB%+1
  GOTO trimloop
) ELSE (
  IF %counterA%==0 (
    CALL :out_info No values entered, cancelling trim.
    SET trim=n
    PAUSE
  ) ELSE (
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET /A countermodulus="!counterA!%%2"
    IF !countermodulus!==1 (
      CALL :out_error DETECTED ODD NUMBER OF FRAME INPUTS.
      ENDLOCAL ENABLEDELAYEDEXPANSION
      GOTO trimloop
    )
    ENDLOCAL ENABLEDELAYEDEXPANSION
  )
)
DEL "%projname%_trimtemp.avs"
GOTO :EOF

:q_trimval
IF "%qframe%"=="" (SET qframe=Frame#: )
SET s=
SET /P s=%qframe%
IF NOT "%s%"=="n" CALL :set_var_number trimval q_trimval
GOTO :EOF

:q_statid
CALL :out_cls_section Station ID
CALL :out_info Set the info shown on the Station ID (the clip at the start of an SDA movie). Run the Station ID Preview program for a preview.
SET statid1=
SET statid2=
SET statid3=
:q_statid_p2
SET s=
SET /P s=Do you want to append an SDA Station ID to the front and end of this video? [y,n]: 
CALL :set_var_bool statid q_statid_p2
GOTO :EOF

:q_statid_lines
CALL :out_info Line 1 is normally the runner's name. Line 2 (and Line 3 if necessary) normally include the game name, the type of run and the time to completion.
SET /P statid1=Station ID Line 1: 
SET /P statid2=Station ID Line 2: 
SET /P statid3=Station ID Line 3: 
IF NOT DEFINED statid1 (SET statid1= )
IF NOT DEFINED statid2 (SET statid2= )
IF NOT DEFINED statid3 (SET statid3= )
REM Replace quotes from user
SET statid1=%statid1:"="+chr(34)+"%
SET statid2=%statid2:"="+chr(34)+"%
SET statid3=%statid3:"="+chr(34)+"%
GOTO :EOF

:q_encodenow
SET s=
SET /P s="Do you want to start encoding now [Y] or save the job for a later date [N]? "
CALL :set_var_bool start_encode q_encodenow
GOTO :EOF

:q_nmf
SET s=
SET /P s=Create nmf? [y,n]: 
CALL :set_var_bool create_nmf q_nmf
GOTO :EOF

:q_update_anri
SET s=
SET /P s="Do you want to update Anri-chan's games database? [y,n] "
CALL :set_var_bool check_now q_update_anri
GOTO :EOF

:q_submit_dfnd
ECHO.
CALL :out_info You didn't use the Anri-chan DFnD database. Does that mean that it didn't have your game? If so, we'd love it if you posted the "D", "F" and "2D Game" info you just entered here, into our DFnD updates topic on SDA, so we can add it to the next version of the database. You don't need to register to do so and it only takes a few seconds.
ECHO.
SET s=
SET /P s="Submit this game's DFnD data to SDA? [y,n] "
CALL :set_var_bool submit_dfnd q_submit_dfnd
IF "%submit_dfnd%"=="n" GOTO :EOF
START http://speeddemosarchive.com/forum/index.php?action=post;topic=6416.0
CALL :out_info Thanks!
PAUSE
GOTO :EOF


REM ------- DFND SECTION -------

:dfnd
CALL :q_update_anri
IF "%check_now%"=="y" (
IF EXIST "dfnd_data_temp.bat" DEL "dfnd_data_temp.bat"
IF EXIST "dfnd_titles_temp.bat" DEL "dfnd_titles_temp.bat"
"%anri_dir%wget.exe" http://speeddemosarchive.com/anrichan/dfnd_data_temp.bat
"%anri_dir%wget.exe" http://speeddemosarchive.com/anrichan/dfnd_titles_temp.bat
REM can't write to the anri-chan dir in vista...
IF EXIST "dfnd_data_temp.bat" MOVE /Y "dfnd_data_temp.bat" "%appdata%\dfnd_data.bat"
IF EXIST "dfnd_titles_temp.bat" MOVE /Y "dfnd_titles_temp.bat" "%appdata%\dfnd_titles.bat"
CALL :out_info Anri-chan updated.
)

SET nodb=n
IF NOT EXIST "%anri_dir%dfnd_titles.bat" SET nodb=y
IF NOT EXIST "%anri_dir%dfnd_data.bat" SET nodb=y
IF "%nodb%"=="y" (
	CALL :out_error The DFnD database was not found in Anri-chan's data directory.
	GOTO :EOF
)

SET dfnd_titlesfile=dfnd_titles.bat
SET dfnd_titles="%appdata%\%dfnd_titlesfile%"
IF NOT EXIST "%appdata%\%dfnd_titlesfile%" SET dfnd_titles="%anri_dir%%dfnd_titlesfile%"

SET dfnd_datafile=dfnd_data.bat
SET dfnd_data="%appdata%\%dfnd_datafile%"
IF NOT EXIST "%appdata%\%dfnd_datafile%" SET dfnd_data="%anri_dir%%dfnd_datafile%"

CALL :out_info Ignore "The" in a game's title when answering this question: in the case of games from the "The Legend of Zelda" series, enter Z. For .hack games, enter D.
:dfnd_letter
SET s=
SET /P s="Enter the first letter of the game's title: "
CALL :set_var_letter dfnd_letter dfnd_letter
:dfnd_list
CALL %dfnd_titles% | MORE
PAUSE
ECHO.
:dfnd_code
CALL :out_info If your game was not shown, enter L to select another letter or X to enter details manually. Enter R to repeat the list of games.
SET s=
SET /P s="Enter the game's code (shown at the left, not including the colon): "
IF /I "%s%"=="l" GOTO dfnd_letter
IF /I "%s%"=="x" GOTO :EOF
IF /I "%s%"=="r" GOTO dfnd_list
CALL %dfnd_data%
IF NOT "%dfnd_set%"=="y" (
	CALL :out_error A game with code %s% was not found.
	GOTO :dfnd_code
)
CALL :out_info Set data successfully.
PAUSE
GOTO :EOF


REM ------- SUBROUTINES TO VALIDATE/SET VARIABLES -------

:set_var_bool
IF "%s%"=="y" (
	SET %1=y
	GOTO :EOF
)
IF "%s%"=="n" (
	SET %1=n
	GOTO :EOF
)
CALL :out_error Invalid value. Please enter Y (Yes) or N (No).
GOTO :%2

:set_var_letter
ECHO %s%|findStr /i "^[a-z]$">nul
IF %ERRORLEVEL%==0 (
	SET %1=%s%
	GOTO :EOF
) ELSE (
	CALL :out_error Invalid value. Please enter a single letter.
	GOTO :%2
)

:set_var_number
ECHO %s%|findStr "[^0-9]">nul
IF %ERRORLEVEL%==0 (
	CALL :out_error Invalid value. Please enter a number.
	GOTO :%2
)
IF "%3"=="" GOTO :napproved
IF %s% GTR %3% (
	CALL :out_error Invalid value. The maximum value is %3.
	GOTO :%2
)
:napproved
SET %1=%s%
GOTO :EOF

:set_var_nospace
ECHO %s%|findStr /c:" ">nul
IF %ERRORLEVEL%==0 (
	CALL :out_error Invalid value. You cannot have a space.
	GOTO :%2
) ELSE (
	SET %1=%s%
	GOTO :EOF
)

:set_var_notnull
IF NOT DEFINED s (
	CALL :out_error Invalid value. You must enter a value.
	GOTO :%2
) ELSE (
	SET %1=%s%
	GOTO :EOF
)

:set_var_in
ECHO %s%|findStr "^[%3]$">nul
IF %ERRORLEVEL%==0 (
	SET %1=%s%
	GOTO :EOF
) ELSE (
	CALL :out_error Invalid value. Please enter one of the suggested values only.
	GOTO :%2
)

REM ------- FILE HANDLING -------

:make_projdir
CD /D "%project_parentdir%"
IF NOT EXIST "%projname%" MD "%projname%"
CD /D "%projname%"
SET projdirpath=%CD%
SET in_projdir=y
COPY /Y "%anri_dir%silence_stereo_48000.wav" > NUL
COPY /Y "%anri_dir%%dgmpgdec_dir%\infotemplate.avs" > NUL
COPY /Y "%anri_dir%ntsc_d1.png" > NUL
rem CALL :log_anridir_projdir
GOTO :EOF

:wipe_projdir
IF NOT "%in_projdir%"=="y" CALL :make_projdir
IF EXIST "%projname%.avs" DEL *.avs *.d2v *.wav
IF EXIST "%projname%_job.bat" DEL %projname%_job.bat
GOTO :EOF

:wipe_avs
IF EXIST "%projname%.avs" DEL *.avs
COPY /B "%projname%.bak" "%projname%.avs" 1> NUL
COPY /B "plugins.bak" "plugins.avs" 1> NUL
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: load_plugins
REM
REM  All plugins used by anrichan should be contained in its own directory. Scan
REM  the plugins folder and write plugins.avs which will later be used for all
REM  scripts. We should never have to refer to the avisynth folder.
REM ---------------------------------------------------------------------------

:load_plugins
IF EXIST plugins.avs DEL plugins.avs
FOR %%G IN ("%anri_dir%plugins\*") DO (
  IF %%~xG==.dll ECHO loadplugin^("%%~fG"^) >> "plugins.avs"
  IF %%~xG==.avs ECHO import^("%%~fG"^) >> "plugins.avs"
)
COPY /B "plugins.avs" "plugins.bak" 1> NUL
GOTO :EOF

REM ---------------------------------------------------------------------------
REM  function: index_dvd
REM 
REM  Show a list of ripped DVDs. Cycle through the user's choices, indexing
REM  VOB/VRO files one by one. Run a preview as well to get the dgindex log.
REM  The log gets created in the vob folder, so it needs to be moved to the
REM  project folder. Used to determine maxaudiobitrate. Everything that's been
REM  done so far (ripping and indexing) should be transparent with the rest of
REM  the program. All that matters is creating a valid project.avs.
REM ---------------------------------------------------------------------------

:index_dvd
SETLOCAL ENABLEDELAYEDEXPANSION
CALL :out_cls_info Here is the list of DVD/MPEG files in %dvdripto_parentdir%\. Select one or more by typing in the number, or numbers separated by a space. If you select more than one, the files will be joined in the order you specify.
ECHO.
%CECHO% "{navy on gray}Note that joining different DVD/MPEG files is only recommended if it's of the same game.  The settings you choose later in editing will be applied to the whole project which can cause problems since different games will possibly need different settings.{\n}"
%RESET_COLOR%
ECHO.
SET index=0
PUSHD %dvdripto_parentdir%
FOR /D %%G IN (*) DO (
  SET /a index+=1
  SET dvdfolder!index!=%%G
  IF EXIST %%G\*.v* (
    ECHO  !index!. %%G
  ) ELSE (
    IF EXIST %%G\*.mpg (
      ECHO  !index!. %%G
    ) ELSE (
      IF EXIST %%G\*.mpeg (
        ECHO  !index!. %%G
      ) ELSE (
        ECHO  !index!. %%G - no VOB or VRO files found - empty?
      )
    )
  )
)
POPD
ECHO.
:index_dvd_choice
SET /P dvdchoice=[1-%index%]: 
REM Start - Validate
FOR %%G IN (%dvdchoice%) DO (
  IF NOT DEFINED dvdfolder%%G (
    CALL :out_error Folder %%G was not found.
    GOTO :index_dvd_choice
  )
)
REM End - Validate

ECHO.
CALL :out_info Now indexing MPEG-2 ...

REM Start - AVS prep
IF EXIST %projname%.avs DEL %projname%.avs
ECHO loadplugin^("%anri_dir%%dgmpgdec_dir%\DGDecode.dll"^) > %projname%.avs
ECHO import^("%anri_dir%nate.avs"^) >> %projname%.avs
ECHO import^("%projdirpath%\plugins.avs"^) >> %projname%.avs
REM End - AVS prep

SET num=1
SET maxaudiobitrate=0
FOR %%G IN (%dvdchoice%) DO (
  FOR %%H IN ("%dvdripto_parentdir%\!dvdfolder%%G!\*.V*" "%dvdripto_parentdir%\!dvdfolder%%G!\*.MPG" "%dvdripto_parentdir%\!dvdfolder%%G!\*.MPEG" ) DO (
    IF %%~zH GTR 5000 (
      REM Run current vob through dgindex. Set to demux all tracks. Place vid,aud,delay info into temporary avs file.
      "%anri_dir%%dgmpgdec_dir%\dgindex.exe" -IF=[%%H] -OF=[%projname%%%~nH] -PREVIEW -exit
      MOVE /Y "%dvdripto_parentdir%\!dvdfolder%%G!\%%~nH.log" "%projdirpath%\%projname%_!num!_%%~nH.log"
      "%anri_dir%%dgmpgdec_dir%\dgindex.exe" -IF=[%%H] -OM=2 -OF=[%projname%_!num!_%%~nH] -AT=[infotemplate.avs] -exit
      REM If there's more than one file to be joined, they must be appended together.
      IF NOT !num!==1 echo \++\ >> %projname%.avs
      REM Detect audio type, set vid,aud,delay to parameters a, b and c, generate source line.
      IF EXIST "%projname%_!num!_*.ac3" (
        FOR /F "tokens=1,2,3 delims=," %%A IN ('TYPE "%projname%_!num!_%%~nH.avs"') DO (
          ECHO AC3source^(MPEG2source^("%%A"^,upConv=1^),"%%B"^).DelayAudio^(%%C^) >> %projname%.avs
        )
      ) ELSE (
        IF EXIST "%projname%_!num!_*.mp*" (
          FOR /F "tokens=1,2,3 delims=," %%A IN ('TYPE "%projname%_!num!_%%~nH.avs"') DO (
            ECHO AudioDub^(MPEG2source^("%%A"^,upConv=1^),mpasource^("%%B"^)^).DelayAudio^(%%C^) >> %projname%.avs
          )
        ) ELSE (
          IF EXIST "%projname%_!num!_*.wav" (
            FOR /F "tokens=1,2 delims=," %%A IN ('TYPE "%projname%_!num!_%%~nH.avs"') DO (
              ECHO AudioDub^(MPEG2source^("%%A"^,upConv=1^),wavsource^("%%B"^)^) >> %projname%.avs
            )
          )
        )
      )
      REM Find max bitrate, unless PCM which will make it 320000
      FINDSTR /C:PCM "%projname%_!num!_%%~nH.log" > NUL
      IF !ERRORLEVEL!==0 (
        SET maxaudiobitrate=320000
      ) ELSE (
        FOR /F "tokens=*" %%N in ('FINDSTR /C:Audio "%projname%_!num!_%%~nH.log"') DO SET bitrate=%%N
        SET bitrate=!bitrate:~-3!000
        IF !bitrate! GTR !maxaudiobitrate! (
          SET maxaudiobitrate=!bitrate!
        )
      )
      REM Delete infotemplate child
      DEL "%projname%_!num!_%%~nH.avs"
      SET /A num+=1
    )
  )
)
REM Just in case
IF %maxaudiobitrate%==0 SET maxaudiobitrate=320000
ENDLOCAL ENABLEDELAYEDEXPANSION & SET maxaudiobitrate=%maxaudiobitrate%
ECHO. >> "%projname%.avs"
COPY /Y "%projname%.avs" "%projname%.bak" > NUL
IF %maxaudiobitrate% GTR 320000 SET maxaudiobitrate=320000
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: nmf
REM 
REM  
REM ---------------------------------------------------------------------------

:nmf
SETLOCAL ENABLEDELAYEDEXPANSION
CALL :out_cls_section New Master File
CALL :out_info NMF: New Master File refers to an intermediate source video file in the encoding process, usually one saved after deinterlacing (to avoid slow deinterlacing during each pass for each quality of output). 
ECHO.
CALL :out_info You have chosen to encode HQ/IQ/XQ. We can speed up the encoding process by creating a NMF. ^^! BEWARE ^^! The new file can be extremely large, somewhere around 36 to 72 GB per hour. Make sure you have enough hard drive space.
ECHO.
CALL :q_nmf
ECHO.
IF %create_nmf%==n (
  ENDLOCAL ENABLEDELAYEDEXPANSION & SET create_nmf=%create_nmf%
  GOTO :EOF
)
REM SET NUMBER_OF_PROCESSORS=2
SET counterA=1
SET counterB=0
REM Set lagarith to yv12
IF DEFINED LOCALAPPDATA (
  REM Vista
  IF NOT EXIST "%LOCALAPPDATA%\VirtualStore\Windows" MD "%LOCALAPPDATA%\VirtualStore\Windows"
  ECHO [settings] > "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
  ECHO lossy_option=3 >> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
  IF %NUMBER_OF_PROCESSORS% GTR 1 (
    ECHO multithreading=1  >> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
  ) ELSE (
    ECHO multithreading=0  >> "%LOCALAPPDATA%\VirtualStore\Windows\lagarith.ini"
  )
) ELSE (
  ECHO [settings] > %WINDIR%\lagarith.ini
  ECHO lossy_option=3 >> %WINDIR%\lagarith.ini
  IF %NUMBER_OF_PROCESSORS% GTR 1 (
    ECHO multithreading=1  >> %WINDIR%\lagarith.ini
  ) ELSE (
    ECHO multithreading=0  >> %WINDIR%\lagarith.ini
  )
)
DEL "%projname%_HQ_nmf.avs" > NUL 2>&1
:nmf_vdubloop
COPY /Y %projname%_HQ.avs %projname%_HQIQXQ_%counterA%.avs > NUL
ECHO Trim^(floor^(last.framecount/%NUMBER_OF_PROCESSORS%.000*%counterB%.000^), floor^(last.framecount/%NUMBER_OF_PROCESSORS%.000*%counterA%.000^)-1^) >> %projname%_HQIQXQ_%counterA%.avs
ECHO avisource^("%projname%_HQIQXQ_%counterA%.avi"^) >> %projname%_HQ_nmf.avs
DEL "%projname%_HQIQXQ_%counterA%.avi" > NUL 2>&1
START /LOW /B "encoding nmf section %counterA%" "%anri_dir%%vdub%\vdub.exe" "%projname%_HQIQXQ_%counterA%.avs" /i "%anri_dir%nmf.vcf" "%projname%_HQIQXQ_%counterA%.avi" > NUL
SET /A counterA=%counterA% + 1
SET /A counterB=%counterB% + 1
IF %counterA% LEQ %NUMBER_OF_PROCESSORS% (
  ECHO \++\ >> %projname%_HQ_nmf.avs
  GOTO nmf_vdubloop
)
ECHO converttoyv12 >> %projname%_HQ_nmf.avs
ECHO WriteFileStart^("resolution.log","last.width",""" "," """, "last.height"^) >> "%projname%_HQ_nmf.avs"
ECHO changefps(last.framerate) >> "%projname%_HQ_nmf.avs"
COPY /Y %projname%_HQ_nmf.avs %projname%_IQ_nmf.avs > NUL
COPY /Y %projname%_HQ_nmf.avs %projname%_XQ_nmf.avs > NUL
:nmf_waitingloop
ECHO %time%  Encoding nmf...
"%anri_dir%TIMEOUT" 20 > NUL
"%anri_dir%TASKLIST" | find "vdub.exe" > NUL
IF %ERRORLEVEL%==0 GOTO nmf_waitingloop
ECHO.
CALL :out_info NMF successfully created. Continuing with encoding process in 5 seconds...
ECHO.
"%anri_dir%TIMEOUT" 5 > NUL
ENDLOCAL ENABLEDELAYEDEXPANSION & SET create_nmf=%create_nmf%
GOTO :EOF


REM ---------------------------------------------------------------------------
REM  function: script_buildfiles
REM 
REM  
REM ---------------------------------------------------------------------------

:script_buildfiles
REM Delete all avs files and restore base avs which has video source lines.
CALL :wipe_avs

IF "%trim%"=="y" (
  SET trimarraycode=
  SETLOCAL ENABLEDELAYEDEXPANSION
  (SET counter=0)
  FOR %%G IN (!trimarray!) DO (
    SET /A counter=!counter!+1
    SET /A countermodulus="!counter!%%2"
    IF !countermodulus!==1 (
      SET trimarraycode=!trimarraycode!trim^(%%G,
    ) ELSE (
      SET trimarraycode=!trimarraycode!%%G^)++
    )
  )
  SET trimarraycode=!trimarraycode:~0,-2!
  echo !trimarraycode! >> "%projname%.avs"
  ENDLOCAL ENABLEDELAYEDEXPANSION
)
IF "%fieldorder%"=="t" ECHO AssumeTFF^(^) >> "%projname%.avs"
IF "%fieldorder%"=="b" ECHO AssumeBFF^(^) >> "%projname%.avs"
ECHO global pal = ^(last.height==576^) ? true : false >> "%projname%.avs"

IF "%isPCGAME%"=="y" (
  ECHO global f1 = last.framerate >> "%projname%.avs"
  COPY /B "%projname%.avs" "%projname%_HQ.avs" 1> NUL
  COPY /B "%projname%.avs" "%projname%_IQ.avs" 1> NUL
  COPY /B "%projname%.avs" "%projname%_XQ.avs" 1> NUL
  ECHO float^(last.width^) / last.height ^>= 16./9 ? ^(last.width ^> 1280 ? Lanczos4Resize^(1280,round^(last.height*^(1280./last.width^)^)^) : NOP^) : ^(last.height ^> 720 ? Lanczos4Resize^(round^(last.width*^(720./last.height^)^),720^) : NOP^) >> "%projname%_IQ.avs"
  ECHO last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP >> "%projname%_IQ.avs"
  ECHO last.width %% 2 == 1 ? AddBorders^(0,0,1,0^) : NOP >> "%projname%_IQ.avs"
  ECHO last.width ^> 640 ? Lanczos4Resize^(640,round^(last.height*^(640.0000/last.width^)^)^) : NOP >> "%projname%_HQ.avs"
  ECHO last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP >> "%projname%_HQ.avs"
  ECHO last.width %% 2 == 1 ? AddBorders^(0,0,1,0^) : NOP >> "%projname%_HQ.avs"
  ECHO WriteFileStart^("resolution.log","last.width",""" "," """, "last.height"^) >> "%projname%_HQ.avs"
  ECHO last.width ^> 320 ? Lanczos4Resize^(320,round^(last.height*^(320.0000/last.width^)^)^) : NOP >> "%projname%.avs"
  ECHO last.height %% 2 == 1 ? AddBorders^(0,0,0,1^) : NOP >> "%projname%.avs"
  ECHO last.width %% 2 == 1 ? AddBorders^(0,0,1,0^) : NOP >> "%projname%.avs"
) ELSE (
  ECHO global f1 = ^(pal==true^) ? 50 : 59.94 >> "%projname%.avs"
  COPY /B "%projname%.avs" "%projname%_HQ.avs" 1> NUL
  ECHO WriteFileStart^("resolution.log","last.width",""" "," """, "last.height"^) >> "%projname%_HQ.avs"
  REM Set d1 either 352 or 320
  IF NOT "%d%"=="1" ECHO global d1 = false ? ^(^(pal==true^) ? 704 : 640^) : ^(^(pal==true^) ? 352 : 320^) >> "%projname%_HQ.avs"
  REM Set d1 either 704 or 640
  IF "%d%"=="1" ECHO global d1 = true ? ^(^(pal==true^) ? 704 : 640^) : ^(^(pal==true^) ? 352 : 320^) >> "%projname%_HQ.avs"
  COPY "%projname%_HQ.avs" "%projname%_IQ.avs" > NUL
  REM Set d1 either 352 or 320 for LQ/MQ
  ECHO global d1 = false ? ^(^(pal==true^) ? 704 : 640^) : ^(^(pal==true^) ? 352 : 320^) >> "%projname%.avs"
  REM d1 is set, but not yet resized.
  IF "%prog%"=="y" (
    ECHO pal==true ? d1==704 ? lanczos4resize^(704,576^) : lanczos4resize^(352,288^) : d1==640 ? lanczos4resize^(640,480^) : lanczos4resize^(320,240^) >> "%projname%_temp.avs"
    GOTO itsprog
  )
  IF "%vhs%"=="y" ECHO nate_vhs_head_change_erase >> "%projname%_temp.avs"
  ECHO ^(pal==true ? d1==704 : d1==640^) ? mvbob : separatefields >> "%projname%_temp.avs"
  IF "%onepixel%"=="y" ECHO nate_1_pixel_bob_fix >> "%projname%_temp.avs"
  IF "%deflicker%"=="y" ECHO nate_retard_bob_2 >> "%projname%_temp.avs"
  IF "%nes%"=="y" ECHO nate_nes >> "%projname%_temp.avs"
  ECHO lanczos4resize^(d1,last.height^) >> "%projname%_temp.avs"
  IF "%gba%"=="y" ECHO nate_gba >> "%projname%_temp.avs"
  IF "%gameboy%"=="y" ECHO nate_gb >> "%projname%_temp.avs"

  :itsprog
  IF NOT "%prog%"=="y" (
    IF "%f%"=="3" (
	  ECHO changefps^(f1/2^) >> "%projname%_temp.avs"
	  ECHO decimate^(cycle=3^) >> "%projname%_temp.avs"
	) ELSE (
	  ECHO changefps^(f1/%f%^) >> "%projname%_temp.avs"
	)
  )
)

ECHO run=converttoyv12 >> "%projname%_temp.avs"
IF "%gba%"=="y" GOTO gbastatid
IF "%gameboy%"=="y" GOTO gbstatid
ECHO statid=nate_statid_d1(run,"%statid1%","%statid2%","%statid3%").ConvertToRGB >> "%projname%_temp.avs"
GOTO statidrefork
:gbastatid
ECHO statid=nate_statid_gba(run,"%statid1%","%statid2%","%statid3%").ConvertToRGB >> "%projname%_temp.avs"
GOTO statidrefork
:gbstatid
ECHO statid=nate_statid_gb(run,"%statid1%","%statid2%","%statid3%").ConvertToRGB >> "%projname%_temp.avs"
:statidrefork
ECHO statid = float^(run.width^) / run.height ^>= 4./3 ? >> "%projname%_temp.avs"
ECHO \ statid.Lanczos4Resize^(round^(run.height*4./3^),run.height^).AddBorders^(floor^(^(run.width-round^(run.height*4./3^)^)/2.^),0,ceil^(^(run.width-round^(run.height*4./3^)^)/2.^),0^).ConvertToYv12 :  >> "%projname%_temp.avs"
ECHO \ statid.Lanczos4Resize^(run.width,round^(run.width*3./4^)^).AddBorders^(0,floor^(^(run.height-round^(run.width*3./4^)^)/2.^),0,ceil^(^(run.height-round^(run.width*3./4^)^)/2.^)^).ConvertToYv12 >> "%projname%_temp.avs"
REM Pre-shrink the statid so it looks normal after setting 16/9 display aspect ratio.
IF "%widescreen%"=="y" ECHO statid = statid.AddBorders^(int^(^(statid.width * 4./3 - statid.width^) / 2.^), 0, int^(^(statid.width * 4./3 - statid.width^) / 2.^), 0^).Lanczos4Resize^(statid.width,statid.height^) >> "%projname%_temp.avs"
IF "%statid%"=="y" ( ECHO statid++run++statid >> "%projname%_temp.avs" ) ELSE ( ECHO run >> "%projname%_temp.avs" )
ECHO changefps(last.framerate) >> "%projname%_temp.avs"
ECHO converttoyv12 >> "%projname%_temp.avs"
TYPE "%projname%_temp.avs" >> "%projname%.avs"
TYPE "%projname%_temp.avs" >> "%projname%_HQ.avs"
TYPE "%projname%_temp.avs" >> "%projname%_IQ.avs"
IF "%isPCGAME%"=="y" (TYPE "%projname%_temp.avs" >> "%projname%_XQ.avs")
COPY /B "%projname%.avs" "%projname%_LQ.avs" 1> NUL
IF "%twod%"=="y" ECHO ^(last.framerate ^> 31^) ? changefps^(f1/3^) : last >> "%projname%_LQ.avs"
IF "%twod%"=="n" (
  ECHO ^(last.framerate ^> 31^) ? changefps^(f1/2^) : last >> "%projname%.avs"
  ECHO ^(last.framerate ^> 31^) ? changefps^(f1/2^) : last >> "%projname%_LQ.avs"
)
COPY /B "%projname%_LQ.avs" "%projname%_xvid.avs" 1> NUL
COPY /B "%projname%_LQ.avs" "%projname%_LQ_xvid.avs" 1> NUL

DEL "%projname%_temp.avs" "%projname%_trimtemp.avs"
GOTO :EOF



REM ------- SETTINGS MANAGER -------

:find_existing_settings
IF EXIST "%projdirpath%\%projname%_job.bat" (
	CALL "%projdirpath%\%projname%_job.bat"
	SET using_settings=y
)
GOTO :EOF

:check_settings
CALL :show_settings
:check_settings_p2
SET s=
SET /P s=Do you want to encode using these settings? If you choose No you will be prompted to enter them again. [y/n] 
CALL :set_var_bool settings_good check_settings_p2
GOTO :EOF

:show_settings
CALL :out_cls_section REVIEW SETTINGS
IF DEFINED this_anriver IF NOT "%this_anriver%"=="%anri_ver%" CALL :out_info NOTICE: Your settings for this project were created in an outdated version of Anri-chan. They may not work properly in this version. It is recommended that you discard these settings and re-enter them.
IF "%dvdsource%"=="y" ( ECHO DVD Source: Yes ) ELSE ( ECHO DVD Source: No )
IF "%dvdsource%"=="y" ( ECHO DVD Drive Letter: %driveletter% )
ECHO Project Name: %projname%
IF DEFINED avifolder ECHO AVI folder: %avifolder%
IF DEFINED avifiles ECHO Source Video Files: %avifiles%
IF NOT "%twod%"=="y" (SET twodtemp=3D) ELSE (SET twodtemp=2D)
IF DEFINED d IF DEFINED f ECHO Video Format: D%d% F%f% %twodtemp%
IF "%vhs%"=="y" ( ECHO From VHS Source ) ELSE ( ECHO Not From VHS Source )
IF "%prog%"=="y" ( ECHO Progressive ) ELSE ( ECHO Interlaced )
IF "%fieldorder%"=="t" ECHO Top field first
IF "%fieldorder%"=="b" ECHO Bottom field first
IF "%onepixel%"=="y" ECHO One-Pixel Bob
IF "%nes%"=="y" ECHO From NES Console
IF "%gba%"=="y" ECHO From Game Boy Advance
IF "%gameboy%"=="y" ECHO From Game Boy
IF "%deflicker%"=="y" ECHO Deflickered
IF "%trim%"=="y" ECHO Trim frame ranges %trimarray%
IF "%widescreen%"=="y" ECHO Widescreen
IF "%statid%"=="y" ECHO StatID: %statid1:"+chr(34)+"="% / %statid2:"+chr(34)+"="% / %statid3:"+chr(34)+"="%
ECHO.
GOTO :EOF

:savesettings
REM Make sure there's no spaces at the end of each line.
ECHO>  "%projname%_job.bat" @ECHO OFF
ECHO>> "%projname%_job.bat" SET proj_anriver=%anri_ver%
ECHO>> "%projname%_job.bat" SET using_settings=y
ECHO>> "%projname%_job.bat" SET dvdsource=%dvdsource%
ECHO>> "%projname%_job.bat" SET avifolder=%avifolder%
ECHO>> "%projname%_job.bat" SET avifiles=%avifiles%
ECHO>> "%projname%_job.bat" SET fieldorder=%fieldorder%
ECHO>> "%projname%_job.bat" SET d=%d%
ECHO>> "%projname%_job.bat" SET f=%f%
ECHO>> "%projname%_job.bat" SET vhs=%vhs%
ECHO>> "%projname%_job.bat" SET onepixel=%onepixel%
ECHO>> "%projname%_job.bat" SET nes=%nes%
ECHO>> "%projname%_job.bat" SET twod=%twod%
ECHO>> "%projname%_job.bat" SET statid=%statid%
ECHO>> "%projname%_job.bat" SET statid1=%statid1%
ECHO>> "%projname%_job.bat" SET statid2=%statid2%
ECHO>> "%projname%_job.bat" SET statid3=%statid3%
ECHO>> "%projname%_job.bat" SET driveletter=%driveletter%
ECHO>> "%projname%_job.bat" SET projname=%projname%
ECHO>> "%projname%_job.bat" SET gba=%gba%
ECHO>> "%projname%_job.bat" SET gameboy=%gameboy%
ECHO>> "%projname%_job.bat" SET deflicker=%deflicker%
ECHO>> "%projname%_job.bat" SET prog=%prog%
ECHO>> "%projname%_job.bat" SET trim=%trim%
ECHO>> "%projname%_job.bat" SET trimarray=%trimarray%
ECHO>> "%projname%_job.bat" SET widescreen=%widescreen%
ECHO>> "%projname%_job.bat" SET maxaudiobitrate=%maxaudiobitrate%
ECHO>> "%projname%_job.bat" SET hqq=%hqq%
ECHO>> "%projname%_job.bat" SET isPCGAME=%isPCGAME%
ECHO>> "%projname%_job.bat" IF NOT "%%in_anrichan%%"=="y" call "%anri_path%"
COPY /Y "%projname%_job.bat" "%projname%_job.bak" > NUL
GOTO :EOF

:createjob
CALL :savesettings
PAUSE
GOTO die


REM ------- QUALITIES SELECTION -------

:selectquality
SET s=
SET /P s="Create %1 (%2 Kbps) movie? "
IF "%s%"=="y" (
	SET create_%3=y
	GOTO :EOF
)
IF "%s%"=="n" (
	SET create_%3=n
	GOTO :EOF
)
CALL :out_error Invalid value. Please enter Y (Yes) or N (No).
GOTO :selectquality %1 %2 %3

:select_qualities
CALL :savesettings
CALL :selectquality Low-Quality 192 lq
CALL :selectquality Normal-Quality 576 mq
CALL :selectquality High-Quality 2176 hq
IF "%d%"=="1" IF "%f%"=="1" IF NOT "%gba%"=="y" IF NOT "%gameboy%"=="y" (
  CALL :selectquality Insane-Quality 5320 iq
) ELSE (
  SET create_iq=n
)
IF "%dvdsource%"=="n" IF "%d%"=="1" IF "%f%"=="1" IF NOT "%gba%"=="y" IF NOT "%gameboy%"=="y" (
  CALL :selectquality X-TREME-Quality-High-Definition 10320 xq
) ELSE (
  SET create_xq=n
)
ECHO.
CALL :out_info For personal use; non-submittable to SDA:
CALL :selectquality XviD-Low-Quality 192 xl
CALL :selectquality XviD-Normal-Quality 576 xm
GOTO :EOF

REM ------- ENCODING -------

:encode_movies
CALL :out_section encoding %projname%

IF "%create_lq%"=="y" (
  CALL :out_section encoding %projname% LQ MP4
  CALL :2pass %projname%_LQ.avs %projname%_LQ       128  64000  17 1 1
)
IF "%create_mq%"=="y" (
  CALL :out_section encoding %projname% MQ MP4
  CALL :ipod %projname%.avs    %projname%          512  64000  17 1 1
)

IF "%create_hq%"=="y" (
  CALL :out_section encoding %projname% HQ MP4
  IF "%create_nmf%"=="y" (
    CALL :2pass %projname%_HQ_nmf.avs %projname%_HQ      2048 128000 %hqq% 1 1
  ) ELSE (
    CALL :2pass %projname%_HQ.avs %projname%_HQ      2048 128000 %hqq% 1 1
  )
  IF EXIST x264pass2_stdout.txt (
    IF EXIST x264pass2_stdout_HQ.txt DEL x264pass2_stdout_HQ.txt 
    REN x264pass2_stdout.txt x264pass2_stdout_HQ.txt > NUL
  ) > NUL
)

SETLOCAL ENABLEDELAYEDEXPANSION
IF "%create_iq%"=="y" (
  REM Skip IQ if HQ res = native res AND HQ did not reach target bitrate.
  IF EXIST resolution.log (
    FOR /F "tokens=1,2 delims=," %%G IN (resolution.log) DO SET /A hqpixelcount=%%G * %%H
	FOR /F "tokens=2 delims=:" %%G IN ('FIND "Width" mediainfo.txt') DO SET nativewidth=%%G
	FOR /F "tokens=2 delims=:" %%G IN ('FIND "Height" mediainfo.txt') DO SET nativeheight=%%G
	SET /A nativepixelcount=!nativewidth! * !nativeheight!
	IF "!nativepixelcount!"=="!hqpixelcount!" (
      FIND "try reducing target bitrate or reducing qp_min" x264pass2_stdout_HQ.txt > NUL 2>&1
      IF !ERRORLEVEL!==0 SET IQskipped=true
    )
  )
  IF NOT "!IQskipped!"=="true" (
    CALL :out_section encoding %projname% IQ MP4
    IF "%create_nmf%"=="y" (
      CALL :2pass %projname%_IQ_nmf.avs %projname%_IQ   5000 %maxaudiobitrate% 19 1 1
    ) ELSE (
      CALL :2pass %projname%_IQ.avs %projname%_IQ       5000 %maxaudiobitrate% 19 1 1
    )
  )  
  IF EXIST x264pass2_stdout.txt (
    IF EXIST x264pass2_stdout_IQ.txt DEL x264pass2_stdout_IQ.txt > NUL
    REN x264pass2_stdout.txt x264pass2_stdout_IQ.txt > NUL
  )
)
ENDLOCAL ENABLEDELAYEDEXPANSION & (SET IQskipped=%IQskipped%)

SETLOCAL ENABLEDELAYEDEXPANSION
IF "%create_xq%"=="y" (
  IF "%IQskipped%"=="true" (
    XQskipped=true
  ) ELSE (
    CALL :out_section encoding %projname% XQ MP4
    CALL :2pass %projname%_XQ.avs %projname%_XQ     10000 %maxaudiobitrate% 19 1 1
  ) 
)
ENDLOCAL ENABLEDELAYEDEXPANSION & (SET XQskipped=%XQskipped%)

IF "%create_xl%"=="y" (
  CALL :out_section encoding %projname% LQ AVI
  CALL :xvid %projname%_LQ_xvid.avs %projname%_LQ   128     64   1 1
)
IF "%create_xm%"=="y" (
  CALL :out_section encoding %projname% MQ AVI
  CALL :xvid %projname%_xvid.avs %projname%         512     64   1 1
)
GOTO :EOF


:2pass
"%anri_dir%x264.exe" --profile high     --level 4.1 --pass 1 --bitrate %3 --stats "%2.stats" --thread-input            --b-adapt 2 --direct auto         --qpmin %5 --vbv-bufsize 24000 --vbv-maxrate 24000                                                                          --no-mixed-refs --output NUL %1
"%anri_dir%x264.exe" --profile high     --level 4.1 --pass 2 --bitrate %3 --stats "%2.stats" --thread-input            --b-adapt 2 --direct auto         --qpmin %5 --vbv-bufsize 24000 --vbv-maxrate 24000 --me umh                             --weightp 2             --trellis 2                 --output "%2_video.mp4" %1 2>&1 | "%anri_dir%tee.exe" x264pass2_stdout.txt 
"%anri_dir%%vdub%\vdub.exe" %1 /i "%anri_dir%audioout.vcf" "%2_temp.wav"
"%anri_dir%neroAacEnc.exe" -br %4 -lc -if "%2_temp.wav" -of "%2_audio.mp4"
IF "%widescreen%"=="y" (
  "%anri_dir%MP4Box.exe" -tmp . -new -add "%2_video.mp4" -add "%2_audio.mp4" "%2.mp4" -par 1=4:3
) ELSE (
  "%anri_dir%MP4Box.exe" -tmp . -new -add "%2_video.mp4" -add "%2_audio.mp4" "%2.mp4"
)
IF "%6" == "1" del %2.stats
IF "%7" == "1" del %2_video.mp4 | del %2_temp.wav | del %2_audio.mp4
GOTO :EOF

:1pass
"%anri_dir%x264.exe" --profile high --level 4.1 --crf %4 --thread-input --b-adapt 2 --direct auto --vbv-bufsize 24000 --vbv-maxrate 24000 --me umh --trellis 2 --output "%2_video.mp4" %1 
"%anri_dir%%vdub%\vdub.exe" %1 /i "%anri_dir%audioout.vcf" "%2_temp.wav"
"%anri_dir%neroAacEnc.exe" -br %3 -lc -if "%2_temp.wav" -of "%2_audio.mp4"
IF "%widescreen%"=="y" (
  "%anri_dir%MP4Box.exe" -tmp . -new -add "%2_video.mp4" -add "%2_audio.mp4" "%2.mp4" -par 1=4:3
) ELSE (
  "%anri_dir%MP4Box.exe" -tmp . -new -add "%2_video.mp4" -add "%2_audio.mp4" "%2.mp4"
)
IF "%5" == "1" del %2_video.mp4 | del %2_temp.wav | del %2_audio.mp4
GOTO :EOF

:ipod
"%anri_dir%x264.exe" --profile baseline --level 1.3 --pass 1 --bitrate %3 --stats "%2.stats" --thread-input --no-cabac                                   --qpmin %5 --vbv-bufsize 768   --vbv-maxrate 768                                                                            --no-mixed-refs --output NUL %1
"%anri_dir%x264.exe" --profile baseline --level 1.3 --pass 2 --bitrate %3 --stats "%2.stats" --thread-input --no-cabac                           --ref 1 --qpmin %5 --vbv-bufsize 768   --vbv-maxrate 768   --me umh --partitions p8x8,b8x8,i4x4 --weightp 2 --no-8x8dct --trellis 0 --no-mixed-refs --output "%2_video.mp4" %1
"%anri_dir%%vdub%\vdub.exe" %1 /i "%anri_dir%audioout.vcf" "%2_temp.wav"
"%anri_dir%neroAacEnc.exe" -br %4 -lc -if "%2_temp.wav" -of "%2_audio.mp4"
IF "%widescreen%"=="y" (
  "%anri_dir%MP4Box.exe" -tmp . -new -add "%2_video.mp4" -add "%2_audio.mp4" "%2.mp4" -par 1=4:3
) ELSE (
  "%anri_dir%MP4Box.exe" -tmp . -new -add "%2_video.mp4" -add "%2_audio.mp4" "%2.mp4"
)
IF "%6" == "1" del %2.stats
IF "%7" == "1" del %2_video.mp4 | del %2_temp.wav | del %2_audio.mp4
GOTO :EOF

:xvid
"%anri_dir%xvid_encraw.exe" -i %1 -bitrate %3 -pass1 "%2.stats"
"%anri_dir%xvid_encraw.exe" -i %1 -bitrate %3 -pass2 "%2.stats" -avi "%2v.avi"
"%anri_dir%ffmpeg.exe" -b %4 -ac 2 -acodec mp3 -y -i "%2v.avi" -vcodec copy -i %1 "%2.avi"
IF "%5" == "1" del "%2.stats"
IF "%6" == "1" del "%2v.avi"
GOTO :EOF


REM ------- OUTPUT -------

REM ---------- Colorized Output --------------------
REM By: Brett Ables - Psonar
REM %CECHO% is a call to CECHO.exe which is used for colored output
REM Usage should be self-explanatory. Run CECHO.exe /? for help.
REM Also see comment in Initialization section.
REM Sorry about long lines... lines can be shortened with
REM 2 digit color codes (instead of whole words) if needed.
REM ------------------------------------------------------

:out_cls
CLS
%CECHO% "{gray on black}                                                                               {\n}"
%CECHO% "{blue on black}==============================================================================={\n}"
%CECHO% "{white on black}                metroid 2002 speed demos archive anri-chan %anri_ver%                   {\n}"
%CECHO% "{aqua on black}       http://www.metroid2002.com/     http://speeddemosarchive.com/           {\n}"
%CECHO% "{blue on black}==============================================================================={\n}"
ECHO.
%RESET_COLOR%
Goto :EOF

:out_info
%CECHO% "{white on gray}%*{\n}"
%RESET_COLOR%
REM ECHO.
GOTO :EOF

:out_error
%CECHO% "{maroon on gray}[!]{\n}"
%CECHO% "{maroon on gray}[!] {maroon on silver}%*{\n}"
%CECHO% "{maroon on gray}[!]{\n}"
%RESET_COLOR%
ECHO.
GOTO :EOF

:out_section
TITLE Anri-chan %anri_ver% - %*
%CECHO% "{teal on gray}-------------------------{\n}"
%CECHO% "{navy on gray}%*{\n}
%CECHO% "{teal on gray}-------------------------{\n}"
%RESET_COLOR%
ECHO.
GOTO :EOF

:out_cls_section
CALL :out_cls
CALL :out_section %*
GOTO :EOF

:out_cls_info
CALL :out_cls
CALL :out_info %*
GOTO :EOF


REM ------- OTHER -------

:resetvars
FOR %%A IN (%vars_to_use%) DO (SET %%A=)
GOTO :EOF

:filecompare
REM no differences = 0
FC %1 %2 > NUL 2>&1
SET callresult=%ERRORLEVEL%
GOTO :EOF

:die
CALL :resetvars
(SET in_anrichan=)
CD /D "%DESKTOP%"
TITLE Anri-chan dun ^^_^^
PAUSE
EXIT

REM ---------------------------------------------------------------------------
REM  Function: setanribat
REM
REM  The start command, without a /wait in there gets two instances running at
REM  the same time. What happens is we call anri.bat on top of itself at low
REM  priority. The old instance which is running at normal priority, dies.
REM  The /B keeps the new instance in the same window.
REM ---------------------------------------------------------------------------

:setanribat
CD /D %~dp0
IF NOT "%auto%"=="y" (
START /LOW /B anri.bat anrilow
) ELSE (
REM need to change this to call this filename, whatever that may be
START /LOW /B %anri_auto_bat% anrilow
)
EXIT
Personal tools