Attribute VB_Name = "modStart"
' -------------------------------------------------------------------------------
'
'   AVStoDVD - by MrC
'   File: modStart.bas
'   Purpose: Encoding section
'
' -------------------------------------------------------------------------------


Option Explicit
Option Compare Binary
Option Base 0


Private Enum ButType
    Thumbnail
    Label
    ArrowL
    ArrowR
    PlayAll
End Enum

Private sCL As String
Private Err_Message As String
Private OutputPath As String
Private TempPath As String
Private DVDName As String
Private DVD_Label As String
Private sLog As String
Private LogPathname As String
Private NumFile As Integer
Private Str As String
Private bFlag As Boolean


Public Sub Start()

    ' This is the very core of AVStoDVD
    
    Dim OperationSection As String
    Dim FPS As Single
    Dim Str_Settings As String
    Dim VideoEncoderPath As String
    Dim AssetsPath As String
    Dim DC_Precision As String
    Dim Bias As String
    Dim Zone
    Dim sCL2 As String
    Dim AVSPathname(1 To MaxTitles, 1 To MaxAudioTracks) As String
    Dim AVSScript(1 To MaxTitles, 1 To MaxAudioTracks) As String
    Dim VideoPathname(1 To MaxTitles) As String
    Dim AudioExt(1 To MaxTitles, 1 To MaxAudioTracks) As String
    Dim AudioPathname(1 To MaxTitles, 1 To MaxAudioTracks) As String
    Dim SubsExt(1 To MaxTitles, 1 To MaxSubsTracks) As String
    Dim SubsPathname(1 To MaxTitles, 1 To MaxSubsTracks) As String
    Dim ChaptersPathname(1 To MaxTitles) As String
    Dim InputSubsPathName As String
    Dim AudioEncoder As AC3AudioEncoderType
    Dim HCenc_ini As String
    Dim Target_Video_FileSize(1 To MaxTitles) As Single
    Dim Output_Video_FileSize(1 To MaxTitles) As Single
    Dim Output_Audio_FileSize(1 To MaxTitles, 1 To MaxAudioTracks) As Single
    Dim Output_Subs_FileSize(1 To MaxTitles) As Single
    Dim Output_MPEG2_FileSize(1 To MaxTitles) As Single
    Dim Output_Assets_FileSize As Single
    Dim Output_DVD_FileSize As Single
    Dim BatchMux_ini As String
    Dim BatchMux_hcn As String
    Dim TitleName(1 To MaxTitles) As String
    Dim Tj As Integer
    Dim jj As Integer
    Dim kk As Integer
    Dim MInfo As New clsMediaInfo
    Dim OutputVideoInfo As New clsTitleVideoInfo
    Dim OutputAudioInfo As New clsTitleAudioInfo
    Dim Segment As String
    Dim Flag_DeleteAssets As Boolean
    Dim Flag_End As Boolean
    Dim Flag_Menu As Boolean
    Dim Flag_Exec As Boolean
    Dim MBR As VbMsgBoxResult
    Dim Buttons_mnu As String
    Dim Buttons_Pos(1 To MaxTitles) As ButPos
    Dim Buttons_Adj(1 To MaxTitles) As ButAdj
    Dim Buttons_Type(1 To MaxTitles) As ButType
    Dim Button_Pos_Y As Long
    Dim Button_Pos_H As Long
    Dim Chapters_List_Array() As String
    Dim Chapters_List As String
    Dim Chapters_Frame As Long
    Dim MenuVertRes As Integer
    Dim NumButtons(1 To 16) As Integer
    Dim JumpTitle As Integer
    Dim JumpPGC As Integer
    Dim sVideoEncoder As String
    Dim VideoFrameCount As Long
    Dim bSkipVideo(1 To MaxTitles) As Boolean
    Dim bSkipAudio(1 To MaxTitles, 1 To MaxAudioTracks) As Boolean
    Dim bAudioMixer As Boolean
    Dim dSubConvFact As Double
    Dim dSubShiftFact As Double
    Dim HCencMatrix As String
    Dim bWarning As Boolean
        
    On Error GoTo Err_Handling
    
    ' Initialize variables
    OperationSection = "Initialize variables"
    FPS = Title(1).FPS
    
    TempPath = Preferences.TempPath
    OutputPath = frmMain.Txt_Path_Output.Text
    AssetsPath = Preferences.AssetsPath
    If OutputSetup = MPEG2_Streams Then
        AssetsPath = OutputPath
    End If
    
    DVD_Label = frmMain.Txt_DVD_Label.Text
    If DVD_Label = "" Then DVD_Label = "DVD"
    DVDName = DVD_Label
    If modFS.EsisteFile(OutputPath & "\" & DVDName & ".log") = True Then
        jj = 0
        bFlag = False
        Do
            jj = jj + 1
            DVDName = DVD_Label & "_" & jj
            bFlag = Not modFS.EsisteFile(OutputPath & "\" & DVDName & ".log")
        Loop Until bFlag = True
    End If
    
    LogPathname = OutputPath & "\" & DVDName & ".log"
    
    ' Verify working folders existence
    OperationSection = "Verify working folders existence"
    If OutputPath = "" Then
        MsgBox "Cannot find 'DVD Output folder'." & vbCrLf & vbCrLf & "Please select a valid 'DVD Output folder' before to start the project.", vbExclamation, App.Path
        Exit Sub
    ElseIf modFS.CreateDir(OutputPath) = False Then
        MsgBox "Cannot create 'DVD Output folder'." & vbCrLf & vbCrLf & "Please check 'Preferences'/'DVD Output folder' path.", vbExclamation, App.Path
        Exit Sub
    End If
    If AssetsPath = "" Then
        AssetsPath = SysInfo.PathVideos
    ElseIf modFS.CreateDir(AssetsPath) = False Then
        MsgBox "Cannot create 'DVD Assets folder'." & vbCrLf & vbCrLf & "Please check 'Preferences'/'DVD Assets folder' path.", vbExclamation, App.Path
        Exit Sub
    End If
    If TempPath = "" Then
        TempPath = Environ("TEMP")
    ElseIf modFS.CreateDir(TempPath) = False Then
        MsgBox "Cannot create 'Temp folder'." & vbCrLf & vbCrLf & "Please check 'Preferences'/'Temp folder' path.", vbExclamation, App.Path
        Exit Sub
    End If
    
    ' Verify working drives free space
    OperationSection = "Verify working drives free space"
    jj = 0
    Select Case OutputSetup
    Case MPEG2_Streams
        jj = 1
    Case MPEG2_File, DVD_Folder, Burn_DVD
        jj = 1
        If AssetsPath = OutputPath Then jj = jj + 1
    Case ISO_UDF_Image
        jj = 2 - frmMain.intDeleteAssets.value
        If AssetsPath = OutputPath Then jj = jj + 1
    End Select
    If Val(modFS.atDiskFreeSpaceEx(Left(AssetsPath, 1))) < Val(frmMain.Txt_Estimated_Output_Size.Text) Then
        MBR = frmQuestion.Display(frmMain, "Warning!" & vbCrLf & vbCrLf & "Non enough free space in Assets Hard Drive (needed " & frmMain.Txt_Estimated_Output_Size.Text & " MB)!" & vbCrLf & vbCrLf & "Do you want to continue at your risk?", vbNo, 30)
    ElseIf Val(modFS.atDiskFreeSpaceEx(Left(OutputPath, 1))) < jj * Val(frmMain.Txt_Estimated_Output_Size.Text) Then
        MBR = frmQuestion.Display(frmMain, "Warning!" & vbCrLf & vbCrLf & "Non enough free space in Output Hard Drive (needed " & jj * frmMain.Txt_Estimated_Output_Size.Text & " MB)!" & vbCrLf & vbCrLf & "Do you want to continue at your risk?", vbNo, 30)
    End If
    If MBR = vbNo Then
        modMain.Save_Log_Video "Warning! Project aborted due to low disc space.", , True
        Exit Sub
    End If
    
    ' Erase junk stuff
    OperationSection = "Erase junk stuff"
    If Dir(TempPath & "\A2D*.cache") <> "" Then
        Kill TempPath & "\A2D*.cache"
    End If

    ' Verify Menu Titles number
    OperationSection = "Verify Menu Titles number"
    Flag_Menu = DVDMenu.IsInit
    If NumTitles > MaxMenuTitles And DVDMenu.IsInit = True And frmMain.Menu_Options_MPEG2_1.Checked = False And frmMain.Menu_Options_MPEG2_2.Checked = False Then
        If MsgBox("Warning! AVStoDVD can support maximum " & MaxMenuTitles & " DVD Menu Titles." & vbCrLf & vbCrLf & "Press 'Retry' to continue without DVD Menu or 'Cancel' to quit.", vbRetryCancel + vbExclamation, App.Title) = vbRetry Then
            Flag_Menu = False
        Else
            Exit Sub
        End If
    End If

    ' Building MsgBox to check settings before start encoding
    OperationSection = "Building MsgBox to check settings before start encoding"
    With frmMain
        Str_Settings = "PROJECT SETTINGS" & vbCrLf & vbCrLf & _
                       "DVD Video Standard: " & IIf(VideoStandard = PAL, "PAL", "NTSC") & vbCrLf & _
                       "DVD Titles number: " & NumTitles & vbCrLf & _
                       "DVD Size: " & .Txt_Estimated_Output_Size.Text & "/" & .Txt_Output_Size.Text & " MB (" & Format(Val(.Txt_Estimated_Output_Size.Text) / Val(.Txt_Output_Size.Text), "0%") & ")" & vbCrLf & _
                       "DVD Output Setup: " & .StatusBar.Panels("Output_Setup").Text & vbCrLf & _
                       "DVD Label: " & DVD_Label & vbCrLf & _
                       "DVD Menu: " & IIf(Flag_Menu = False, "No Menu", IIf(DVDMenu.Style = 1, "Motion Menu", "Static Menu")) & vbCrLf & _
                       "Output Folder: " & OutputPath & vbCrLf & _
                       "Delete Temp Assets Files: " & IIf(.intDeleteAssets.value = 0, "No", "Yes") & vbCrLf & _
                       "Delete Temp Working Files: " & IIf(.intDeleteWorking.value = 0, "No", "Yes") & vbCrLf & _
                       "Edit Command Parameters: " & IIf(.Int_EditEncoderParams.value = 0, "No", "Yes") & vbCrLf & _
                       "Post Process Task: " & Replace(.Cmb_PostProcess.Text, " (default)", "") & vbCrLf & vbCrLf
    End With
    
    ' Start Operations
    OperationSection = "Start Operations"
    If InStr(1, frmJobsList.Caption, "/") <> 0 Then MBR = vbOK
    If MBR <> vbOK Then
        MBR = MsgBox(Str_Settings & vbCrLf & "Do you want to start?" & vbCrLf, vbQuestion + vbOKCancel + vbMsgBoxHelpButton, App.Title, App.HelpFile, 17)
    End If
    If MBR = vbOK Then
        frmMain.Hide
        frmJobsList.Hide
        Load frmProgress
        Flag_DeleteAssets = CBool(frmMain.intDeleteAssets.value)
        modMain.Save_Log_Video IIf(InStr(1, frmProgress.Caption, "/") = 0, "AVStoDVD Project started.", "AVStoDVD Job" & modStr.StrTrimRight(modStr.StrTrimLeft(frmProgress.Caption, "-"), "-") & "started.")
        Str_Settings = Str_Settings & _
                       LogPreferencesBuildOps
        modMain.Save_Log LogPathname, "START PROCESS", False
        modMain.Save_Log LogPathname, Str_Settings, True
                
        ' Generate filename used throuhgout the process
        OperationSection = "Generate filename used throuhgout the process"
        For Tj = 1 To NumTitles
            TitleName(Tj) = DVDName & "_Title_" & IIf(Tj < 10, "0", "") & Tj & "_" & Title(Tj).TitleName
        Next Tj
        If NumTitles = 1 Then TitleName(1) = DVDName & "_" & Title(1).TitleName
        
        ' Start encoding processes
        For Tj = 1 To NumTitles
            OperationSection = "Title " & Tj & " encoding setup"
            CurrentTitle = Tj
            With Title(Tj)
                frmProgress.Update_Progress 0, True
                
                ' Verify Source Files
                OperationSection = "Title " & Tj & " source files verification"
                bFlag = False
                If .InputVideoPathName <> "" Then
                    If modFS.EsisteFile(.InputVideoPathName) = False Then bFlag = True
                End If
                For jj = 1 To Val(.AudioTracksCount)
                    If modFS.EsisteFile(.InputAudioPathName(jj)) = False Then bFlag = True
                Next jj
                For jj = 1 To Val(.SubsTracksCount)
                    If modFS.EsisteFile(.InputSubsPathName(jj)) = False Then bFlag = True
                Next jj
                If bFlag = True Then
                    modMain.Save_Log_Video "Error! Cannot locate Title " & Tj & " source files. Process aborted.", , True
                    Flag_End = True
                    Exit For
                End If
                
                ' Generate AviSynth script file(s)
                OperationSection = "Title " & Tj & " AviSynth script file generation"
                kk = Val(.AudioTracksCount)
                If kk = 0 Then kk = 1
                For jj = 1 To kk
                    AVSPathname(Tj, jj) = TempPath & "\" & TitleName(Tj) & "_" & jj & ".avs"
                    If jj = 1 Then
                        AVSScript(Tj, jj) = .AVSScript
                    Else
                        AVSScript(Tj, jj) = modAVS.Create_AVSScript(Title(Tj), jj)
                    End If
                    modStr.STRtoANSIFile AVSScript(Tj, jj), AVSPathname(Tj, jj)
                Next jj
                
                ' Misc stuff for Title Tj
                OperationSection = "Title " & Tj & " misc starting stuff"
                
                ' Log source files info
                OperationSection = "Title " & Tj & " source file info log"
                sLog = "TITLE " & Tj & " SOURCE FILES" & vbCrLf & _
                       "Video: " & .InputVideoPathName & vbCrLf & _
                       "Info: " & .InputVideoInfo.Summary
                For jj = 1 To Val(.AudioTracksCount)
                    sLog = sLog & vbCrLf & _
                          "Audio " & jj & ": " & .InputAudioPathName(jj) & vbCrLf & _
                          "Info: " & .InputAudioInfo(jj).Summary
                Next jj
                For jj = 1 To Val(.SubsTracksCount)
                    sLog = sLog & vbCrLf & _
                           "Subs " & jj & ": " & .InputSubsPathName(jj) & vbCrLf & _
                           "Info: " & .InputSubsInfo(jj).Summary
                Next jj
                sLog = sLog & vbCrLf & "[" & .InputGeneralInfo.MediaInfoVersion & "]"
                modMain.Save_Log LogPathname, sLog, True
                modMain.Save_Log LogPathname, "AVISYNTH SCRIPT" & vbCrLf & AVSScript(Tj, 1), True
                If Val(.AudioTracksCount) > 1 Then
                    For jj = 2 To Val(.AudioTracksCount)
                        modMain.Save_Log LogPathname, "AVISYNTH SCRIPT (Audio Track " & jj & ")" & vbCrLf & AVSScript(Tj, jj), True
                    Next jj
                End If
                
                ' Adjust audio mixer
                OperationSection = "Title " & Tj & " Adjust audio mixer"
                If Preferences.DSFiltersRuntime = True Then
                    Select Case Preferences.AVSAudioInput
                    Case "A2DSource", "DirectShowSource"
                        bAudioMixer = True
                        modExtSW.AudioMixerChange Val(.InputAudioInfo(1).Channels), Val(Left(.AudioChannelsMode(1), 1)) + Val(Right(.AudioChannelsMode(1), 1)), True, LogPathname
                    End Select
                End If
                
                ' AviSynth FrameServing capability check
                OperationSection = "Title " & Tj & " AviSynth FrameServing check"
                If frmMain.Int_FrameServingCheck.value = 1 Then
                    OperationSection = "Title " & Tj & " AviSynth FrameServing check"
                    If .VideoIsToBeKept = False Then
                        sLog = UCase(OperationSection) & vbCrLf
                        bFlag = modExtSW.AviSynth_FrameServing_Check(.AVSScript, OperationSection & "." & vbCrLf & "Please wait ...", CBool(frmMain.intDeleteWorking.value))
                        If bFlag = False Then
                            Str = "Error! Title " & Tj & " cannot be frameserved by AviSynth."
                            sLog = sLog & Str
                            MBR = frmQuestion.Display(frmMain, Str & vbCrLf & vbCrLf & "For more info and troubleshooting, see Help/FAQ/Video/Q3.1" & vbCrLf & vbCrLf & "Do you want to continue anyway? Default 'No'", vbNo, 60)
                            If MBR = vbYes Then
                                sLog = sLog & vbCrLf & "Warning message skipped."
                            Else
                                modMain.Save_Log LogPathname, sLog & " Process aborted.", True, True
                                Flag_End = True
                                Exit For
                            End If
                        Else
                            sLog = sLog & "Check passed successfully."
                        End If
                        modMain.Save_Log LogPathname, sLog, True
                    End If
                End If
                
                ' Start VIDEO encoding operations
                OperationSection = "Title " & Tj & " VIDEO encoding operations start"
                modMain.Save_Log_Video "Title " & Tj & " video encoding operations started."
                Target_Video_FileSize(Tj) = Val(.VideoBitRate) * 1000 / 8 / 1024 / 1024 * Val(.TimeTrimmed)
                ' Define video file pathname
                VideoPathname(Tj) = AssetsPath & "\" & TitleName(Tj) & ".m2v"
                sLog = ""
                MBR = vbYes
                If modFS.EsisteFile(VideoPathname(Tj)) = True Then
                    MBR = frmQuestion.Display(frmMain, Msgs.FileExistsOverwrite & vbCrLf & vbCrLf & "'" & VideoPathname(Tj) & "'" & vbCrLf & vbCrLf & "Default 'Yes'", , 60)
                End If
                If MBR <> vbYes Then
                    ' Use already found MPEG-2 video file and skip demux
                    sLog = "SKIP VIDEO ENCODING OPERATIONS" & vbCrLf & "Video file: '" & VideoPathname(Tj) & "' already found."
                    Output_Video_FileSize(Tj) = modUtil.GetFileSize(VideoPathname(Tj)) / 1024 / 1024
                    modMain.Save_Log LogPathname, sLog, True
                    bSkipVideo(Tj) = True
                Else
                    If .VideoIsToBeKept = True And InStr(1, .InputVideoInfo.Compression, "MPEG-2") <> 0 And Val(.InputGeneralInfo.AudioTracksCount) = 0 And OutputSetup <> MPEG2_Streams And .AVSTrim = False Then
                        ' Use source MPEG-2 video pathname and skip demux
                        VideoPathname(Tj) = .InputVideoPathName
                        sLog = "SKIP VIDEO ENCODING OPERATIONS" & vbCrLf & "Source video file '" & VideoPathname(Tj) & "' is already DVD compliant."
                        Output_Video_FileSize(Tj) = modUtil.GetFileSize(VideoPathname(Tj)) / 1024 / 1024
                        modMain.Save_Log LogPathname, sLog, True
                        bSkipVideo(Tj) = True
                    End If
                    If bSkipVideo(Tj) = False Then
                        If .VideoIsToBeKept = True Then
                            ' Video demux
                            OperationSection = "Title " & Tj & " FFmpeg command line generation (video demux)"
                            sVideoEncoder = "Direct Copy (FFmpeg Demux)"
                            VideoEncoderPath = App.Path & "\FFmpeg\ffmpeg.exe"
                            sCL = "-i """ & .InputVideoPathName & """ -c:v copy -an -sn"
                            ' Handle Trim for Video Direct Stream Copy
                            If .AVSTrim = True Then
                                sCL = sCL & " -ss " & modStr.VisualTime(.AVS.FrameStart / .FPSAVS, True, True) & " -vframes " & (.AVS.FrameEnd - .AVS.FrameStart)
                            End If
                            sCL = sCL & " -y """ & VideoPathname(Tj) & """"
                            sLog = "START VIDEO DEMUXING OPERATIONS" & vbCrLf & _
                                   "Video Encoding Profile: " & sVideoEncoder & vbCrLf & _
                                   "Target Video FileSize: " & Round(Target_Video_FileSize(Tj), 1) & " MB" & vbCrLf & _
                                   "Demuxing Parameters: " & sCL
                            modMain.Save_Log LogPathname, sLog, True
                            ' Execute VIDEO demuxing
                            OperationSection = "Title " & Tj & " VIDEO demuxing execution"
                            Execute VideoEncoderPath, sCL, Preferences.EncodingWindowStyle, True
                            sLog = "END VIDEO DEMUXING OPERATIONS" & vbCrLf
                        Else
                            ' Defining variable MPEG2 settings
                            OperationSection = "Title " & Tj & " Defining variable MPEG2 settings"
                            If .VideoHCenc.Bias = "AUTO" Then
                                Bias = CStr(CInt(.VideoBitRate / 1000)) & "0"
                            Else
                                Bias = .VideoHCenc.Bias
                            End If
                            If .VideoHCenc.DCPrec = "AUTO" Then
                                Select Case .VideoBitRate
                                Case Is > 6000
                                    DC_Precision = "10"
                                Case Is > 4000
                                    DC_Precision = "9"
                                Case Else
                                    DC_Precision = "8"
                                End Select
                            Else
                                DC_Precision = .VideoHCenc.DCPrec
                            End If
                            ' Generate command line
                            Select Case .VideoEncoder
                            Case FFMpegCBR1pass
                                OperationSection = "Title " & Tj & " FFmpeg command line generation"
                                sVideoEncoder = "FFmpeg CBR 1-pass"
                                VideoEncoderPath = App.Path & "\FFmpeg\ffmpeg.exe"
                                sCL = "-i """ & AVSPathname(Tj, 1) & """ -threads " & SysInfo.ProcessorNumber & " -aspect "
                                Select Case .VideoAspectRatio
                                Case Standard
                                    Str = "4:3"
                                Case Widescreen
                                    Str = "16:9"
                                End Select
                                sCL = sCL & Str & " -c:v mpeg2video -b:v " & .VideoBitRate & "k -minrate " & .VideoBitRate & "k -maxrate " & .VideoBitRate & "k -bufsize 2000k -dc " & DC_Precision & " "
                                If Preferences.VideoFFmpegHQ = True Then
                                    sCL = sCL & Preferences.VideoFFmpegHQCmd & " "
                                End If
                                If .VideoCloseAllGOPs = True Then
                                    sCL = sCL & "-sc_threshold 1000000000 -flags +cgop "
                                End If
                                If .VideoInterlacedEncoding = True Then
                                    sCL = sCL & "-flags +ilme+ildct -alternate_scan 1 "
                                    Select Case .VideoFieldOrder
                                    Case "BFF"
                                        sCL = sCL & "-top 0 "
                                    Case "TFF"
                                        sCL = sCL & "-top 1 "
                                    End Select
                                End If
                                sCL = sCL & "-y """ & VideoPathname(Tj) & """"
                                ' Let user to modify sCL
                                If frmMain.Int_EditEncoderParams.value = 1 Then
                                    sCL = frmTextBox.Display(frmProgress, "AVStoDVD - Edit Command Parameter", "FFmpeg Command Parameters:" & vbCrLf & "(when finished press X)", sCL)
                                End If
                            Case HCencVBR1pass, HCencVBR2pass
                                OperationSection = "Title " & Tj & " HCenc command line generation"
                                If .VideoEncoder = HCencVBR1pass Then
                                    sVideoEncoder = "HCenc VBR 1-pass"
                                Else
                                    sVideoEncoder = "HCenc VBR 2-pass"
                                End If
                                VideoEncoderPath = App.Path & "\HCenc\HCenc.exe"
                                HCenc_ini = "*INFILE " & AVSPathname(Tj, 1) & vbCrLf & _
                                            "*AVSRELOAD" & vbCrLf & _
                                            "*OUTFILE " & VideoPathname(Tj) & vbCrLf & _
                                            "*LOGFILE " & TempPath & "\" & TitleName(Tj) & ".HCenc.log" & vbCrLf & _
                                            "*MAXBITRATE " & .VideoMaxBitRate & vbCrLf
                                If .VideoEncoder = HCencVBR1pass Then
                                    HCenc_ini = HCenc_ini & _
                                            "*1PASS" & vbCrLf
                                End If
                                HCenc_ini = HCenc_ini & _
                                            "*BITRATE " & .VideoBitRate & vbCrLf & _
                                            "*PROFILE " & .VideoHCenc.Profile & vbCrLf & _
                                            "*ASPECT " & IIf(.VideoAspectRatio = Standard, "4:3", "16:9") & vbCrLf & _
                                            IIf(.VideoInterlacedEncoding = True, "*INTERLACED", "*PROGRESSIVE") & vbCrLf & _
                                            "*" & .VideoFieldOrder & vbCrLf
                                bFlag = False
                                If .InputVideoInfo.Interlaced = False And VideoStandard = NTSC Then
                                    Select Case Val(.InputVideoInfo.FPS)
                                    Case 23.976
                                        bFlag = True
                                    Case 25
                                        bFlag = Preferences.NTSCSlowDown
                                    End Select
                                End If
                                If bFlag = True Then
                                    HCenc_ini = HCenc_ini & "*PULLDOWN" & vbCrLf
                                End If
                                HCenc_ini = HCenc_ini & _
                                            "*BIAS " & Bias & vbCrLf & _
                                            "*DC_PREC " & DC_Precision & vbCrLf & _
                                            IIf(.VideoCloseAllGOPs = True, "*CLOSEDGOPS" & vbCrLf, "")
                                If .VideoHCenc.Matrix = "AUTO" Then
                                    If .VideoBitRate < 2500 Then
                                        HCencMatrix = "AVAMAT7"
                                    Else
                                        HCencMatrix = "MPEG"
                                    End If
                                Else
                                    HCencMatrix = .VideoHCenc.Matrix
                                End If
                                HCenc_ini = HCenc_ini & _
                                            "*MATRIX " & HCencMatrix & vbCrLf & _
                                            "*AQ " & .VideoHCenc.AQ & vbCrLf & _
                                            "*LUMGAIN " & .VideoHCenc.Lumgain & vbCrLf
                                If .VideoHCenc.Zone <> "" Then
                                    Zone = Split(.VideoHCenc.Zone)
                                    VideoFrameCount = .AVS.FrameEnd - .AVS.FrameStart
                                    If Val(Zone(1)) + 1 >= VideoFrameCount Then
                                        HCenc_ini = HCenc_ini & _
                                            "*ZONE 1" & vbCrLf & _
                                            " " & Zone(0) & " " & Zone(2) & vbCrLf
                                    Else
                                        HCenc_ini = HCenc_ini & _
                                            "*ZONE 2" & vbCrLf & _
                                            " " & Zone(0) & " " & Zone(2) & vbCrLf & _
                                            " " & Int(Val(Zone(1))) + 1 & " 1" & vbCrLf
                                    End If
                                End If
                                HCenc_ini = HCenc_ini & _
                                            IIf(Preferences.MultiThread = True, "*SMP", "*NOSMP") & vbCrLf
                                Select Case Preferences.EncodingPriority
                                Case 0
                                    Str = "IDLE"
                                Case 1
                                    Str = "LOW"
                                Case 2, 3
                                    Str = "NORMAL"
                                Case 4, 5
                                    Str = "HIGH"
                                End Select
                                HCenc_ini = HCenc_ini & _
                                            "*PRIORITY " & Str & vbCrLf & _
                                            "*DBPATH  " & Preferences.TempPath & vbCrLf & _
                                            "*WAIT 2"
                                ' Let user to modify sCL
                                If frmMain.Int_EditEncoderParams.value = 1 Then
                                    HCenc_ini = frmTextBox.Display(frmProgress, "AVStoDVD - Edit Command Parameter", "HCenc Command INI file:" & vbCrLf & "(when finished press X)", HCenc_ini)
                                End If
                                modStr.STRtoANSIFile HCenc_ini, TempPath & "\" & TitleName(Tj) & ".HCenc.ini"
                                sCL = "-ini """ & TempPath & "\" & TitleName(Tj) & ".HCenc.ini"""
                            Case FFMpegSafeMode
                                OperationSection = "Title " & Tj & " FFmpeg (Safe Mode) command line generation"
                                sVideoEncoder = "FFmpeg Safe Mode"
                                VideoEncoderPath = App.Path & "\FFmpeg\ffmpeg.exe"
                                sCL = "-i """ & .InputVideoPathName & """ -threads " & SysInfo.ProcessorNumber & " "
                                bFlag = False
                                If Val(.InputVideoInfo.FPS) <= FPS Then
                                    Select Case Val(.InputVideoInfo.FPS)
                                    Case 23.976, 24, 25, 29.97, 30, 50, 59.94, 60    'only these fps are mpeg2 compliant
                                        bFlag = True   ' do nothing, DGPulldown will upsize framerate
                                    End Select
                                End If
                                If bFlag = False Then
                                    sCL = sCL & "-r " & Replace(CStr(FPS), ",", ".") & " "
                                End If
                                Str = ""
                                Select Case .VideoAspectRatio
                                Case Standard
                                    If Val(.InputVideoInfo.Width) / Val(.InputVideoInfo.Height) > 1.34 Then
                                        Str = CStr(Round(Val(.InputVideoInfo.Width) / 1.333, 0))
                                        Str = "-vf pad=" & .InputVideoInfo.Width & ":" & Str & ":0:" & CStr(Round((Val(Str) - Val(.InputVideoInfo.Height)) / 2, 0))
                                    ElseIf Val(.InputVideoInfo.Width) / Val(.InputVideoInfo.Height) < 1.33 Then
                                        Str = CStr(Round(Val(.InputVideoInfo.Height) * 1.333, 0))
                                        Str = "-vf pad=" & Str & ":" & .InputVideoInfo.Height & ":" & CStr(Round((Val(Str) - Val(.InputVideoInfo.Width)) / 2, 0)) & ":0"
                                    End If
                                Case Widescreen
                                    If Val(.InputVideoInfo.Width) / Val(.InputVideoInfo.Height) > 1.78 Then
                                        Str = CStr(Round(Val(.InputVideoInfo.Width) / 1.778, 0))
                                        Str = "-vf pad=" & .InputVideoInfo.Width & ":" & Str & ":0:" & CStr(Round((Val(Str) - Val(.InputVideoInfo.Height)) / 2, 0))
                                    ElseIf Val(.InputVideoInfo.Width) / Val(.InputVideoInfo.Height) < 1.77 Then
                                        Str = CStr(Round(Val(.InputVideoInfo.Height) * 1.778, 0))
                                        Str = "-vf pad=" & Str & ":" & .InputVideoInfo.Height & ":" & CStr(Round((Val(Str) - Val(.InputVideoInfo.Width)) / 2, 0)) & ":0"
                                    End If
                                End Select
                                If Str <> "" Then sCL = sCL & Str & " "
                                sCL = sCL & "-s "
                                Select Case VideoStandard
                                Case PAL
                                    Select Case .VideoResolution
                                    Case Full_D1
                                        Str = "720x576"
                                    Case Half_D1
                                        Str = "352x576"
                                    Case VCD
                                        Str = "352x288"
                                    End Select
                                Case NTSC
                                    Select Case .VideoResolution
                                    Case Full_D1
                                        Str = "720x480"
                                    Case Half_D1
                                        Str = "352x480"
                                    Case VCD
                                        Str = "352x240"
                                    End Select
                                End Select
                                sCL = sCL & Str & " -aspect "
                                Select Case .VideoAspectRatio
                                Case Standard
                                    Str = "4:3"
                                Case Widescreen
                                    Str = "16:9"
                                End Select
                                sCL = sCL & Str & " -c:v mpeg2video -b:v " & .VideoBitRate & "k -minrate " & .VideoBitRate & "k -maxrate " & .VideoBitRate & "k -bufsize 2000k -dc " & DC_Precision & " "
                                If Preferences.VideoFFmpegHQ = True Then
                                    sCL = sCL & Preferences.VideoFFmpegHQCmd & " "
                                End If
                                If .VideoCloseAllGOPs = True Then
                                    sCL = sCL & "-sc_threshold 1000000000 -flags +cgop "
                                End If
                                If .VideoInterlacedEncoding = True Then
                                    sCL = sCL & "-flags +ilme " '+ildct
                                    Select Case .VideoFieldOrder
                                    Case "BFF"
                                        sCL = sCL & "-top 0 "
                                    Case "TFF"
                                        sCL = sCL & "-top 1 "
                                    End Select
                                End If
                                sCL = sCL & "-an -y """ & VideoPathname(Tj) & """"
                                ' Let user to modify sCL
                                If frmMain.Int_EditEncoderParams.value = 1 Then
                                    sCL = frmTextBox.Display(frmProgress, "AVStoDVD - Edit Command Parameter", "FFmpeg (Safe Mode) Command Parameters:" & vbCrLf & "(when finished press X)", sCL)
                                End If
                            End Select
                            sLog = "START VIDEO ENCODING OPERATIONS" & vbCrLf & _
                                   "Video Encoding Profile: " & sVideoEncoder & vbCrLf & _
                                   "Target Video FileSize: " & Round(Target_Video_FileSize(Tj), 1) & " MB" & vbCrLf & _
                                   "Encoding Parameters: " & sCL & IIf(HCenc_ini <> "", vbCrLf & "HCenc ini file:" & vbCrLf & HCenc_ini, "")
                            modMain.Save_Log LogPathname, sLog, True
                            ' Execute VIDEO encoding
                            OperationSection = "Title " & Tj & " VIDEO encoding execution"
                            Execute VideoEncoderPath, sCL, Preferences.EncodingWindowStyle, True
                            sLog = ""
                            ' Read A2DVideoInfo.cache file, if it exists
                            If modFS.EsisteFile(TempPath & "\A2DVideoInfo.cache") = True Then
                                If InStr(1, AVSScript(Tj, 1), "A2DVideoSource(") <> 0 Then
                                    Str = ""
                                    NumFile = FreeFile
                                    Open TempPath & "\A2DVideoInfo.cache" For Input As NumFile
                                        Do Until EOF(NumFile)
                                            Str = Str & Input(1, #NumFile)
                                        Loop
                                    Close NumFile
                                    If InStr(1, Str, .InputVideoPathName) <> 0 Then
                                        sLog = Right(Str, Len(Str) - InStr(1, Str, .InputVideoPathName))
                                        sLog = modMain.Load_Str_Object(sLog, "A2DVideoSource", "")
                                        sLog = "Video Source Filter: A2DSource (" & sLog & ")"
                                    End If
                                ElseIf InStr(1, AVSScript(Tj, 1), "DirectShowSource(") <> 0 Then
                                    sLog = "Video Source Filter: DirectShowSource"
                                ElseIf InStr(1, AVSScript(Tj, 1), "FFVideoSource") <> 0 Then
                                    sLog = "Video Source Filter: FFMpegSource"
                                End If
                            End If
                            sLog = "END VIDEO ENCODING OPERATIONS" & vbCrLf & _
                                   IIf(sLog <> "", sLog & vbCrLf, "")
                        End If
                        ' Check output video filesize
                        Output_Video_FileSize(Tj) = modUtil.GetFileSize(VideoPathname(Tj)) / 1024 / 1024
                        If Output_Video_FileSize(Tj) > 0 Then
                            sLog = sLog & "Created File: " & VideoPathname(Tj) & " (" & Round(Output_Video_FileSize(Tj), 1) & " MB)"
                            ' Read video output media info
                            If MInfo.ReadMediaInfo(VideoPathname(Tj), , False, True, False, False, False, False) = True Then
                                OutputVideoInfo.Initialize MInfo
                                sLog = sLog & vbCrLf & "OUTPUT VIDEO INFO: " & OutputVideoInfo.Summary
                            End If
                            MInfo.Clear
                            modMain.Save_Log LogPathname, sLog, True
                            If .VideoIsToBeKept = False Then
                                ' Execute DG Pulldown if necessary
                                OperationSection = "Title " & Tj & " DG Pulldown execution (if necessary)"
                                With OutputVideoInfo
                                    If .Compression <> "" Then
                                        If Val(.FPS) > 0 And FPS > Val(.FPS) Then
                                            bFlag = True
                                            If VideoStandard = PAL Then
                                                Select Case Val(.FPS)
                                                Case 25
                                                    bFlag = False
                                                Case 23.976, 24
                                                    If LCase(.ScanOrder) = "2:2:2:2:2:2:2:2:2:2:2:3 pulldown" Then bFlag = False
                                                End Select
                                            End If
                                            If VideoStandard = NTSC Then
                                                Select Case Val(.FPS)
                                                Case 29.97
                                                    bFlag = False
                                                Case 23.976
                                                    If LCase(.ScanOrder) = "2:3 pulldown" Then bFlag = False
                                                End Select
                                            End If
                                        End If
                                    End If
                                End With
                                If bFlag = True Then
                                    sCL = """" & VideoPathname(Tj) & """ -srcfps " & OutputVideoInfo.FPS & " -destfps " & Replace(CStr(FPS), ",", ".") & " -inplace -" & LCase(.VideoFieldOrder)
                                    sLog = "START PULLDOWN OPERATIONS" & vbCrLf & "DGPulldown Parameters: " & sCL
                                    modMain.Save_Log LogPathname, sLog, True
                                    Execute App.Path & "\DGPulldown\DGPulldown.exe", sCL, Preferences.EncodingWindowStyle, True
                                    Output_Video_FileSize(Tj) = modUtil.GetFileSize(VideoPathname(Tj)) / 1024 / 1024
                                    sLog = "END PULLDOWN OPERATIONS" & vbCrLf & "DGPulldown executed on File: " & VideoPathname(Tj) & " (" & Round(Output_Video_FileSize(Tj), 1) & " MB)"
                                    If MInfo.ReadMediaInfo(VideoPathname(Tj), , False, True, False, False, False, False) = True Then
                                        OutputVideoInfo.Initialize MInfo
                                        sLog = sLog & vbCrLf & "OUTPUT VIDEO INFO: " & OutputVideoInfo.Summary
                                    End If
                                    MInfo.Clear
                                    modMain.Save_Log LogPathname, sLog, True
                                End If
                            End If
                        End If
                        ' Check Video errors messages
                        Err_Message = ""
                        If Val(OutputVideoInfo.Time) < 0.9 * Val(.TimeTrimmed) * 1000 Then
                            Err_Message = "Warning! Title " & Tj & " output Video duration (" & modStr.VisualTime(Val(OutputVideoInfo.Time) / 1000, True) & ") is shorter than expected duration (" & modStr.VisualTime(Val(.TimeTrimmed), True) & ")."
                            ' Erase error message for some demuxed m2v which does not have the time info into the header
                            If OutputVideoInfo.Time = "" And .VideoIsToBeKept = True And Output_Video_FileSize(Tj) > 0 Then Err_Message = ""
                        End If
                        If Err_Message <> "" Then
                            MBR = frmQuestion.Display(frmMain, Err_Message & vbCrLf & vbCrLf & "Do you want to continue anyway? Default 'No'", , 60)
                            If MBR = vbYes Then
                                sLog = "Process halted during Title " & Tj & " VIDEO " & IIf(.VideoIsToBeKept = True, "demuxing", "encoding") & " operations." & vbCrLf & vbCrLf & _
                                       "Error Message: '" & Err_Message & "'" & vbCrLf & vbCrLf & _
                                       "Video errors warning message skipped."
                                modMain.Save_Log LogPathname, sLog, True
                                bWarning = True
                            Else
                                sLog = "Process aborted during Title " & Tj & " VIDEO " & IIf(.VideoIsToBeKept = True, "demuxing", "encoding") & " operations." & vbCrLf & vbCrLf & _
                                       "Error Message: " & Err_Message & vbCrLf & vbCrLf & _
                                       "For Video issues troubleshooting see Help/FAQ/Video section."
                                modMain.Save_Log LogPathname, sLog, True
                                sLog = sLog & vbCrLf & vbCrLf & _
                                       "For more info on current project check log file <" & OutputPath & "\" & DVDName & ".log>."
                                modMain.Save_Log_Video Err_Message
                                Flag_End = True
                            End If
                        End If
                        ' if any error is encountered exit loop
                        If Flag_End = True Then Exit For
                    End If
                End If
                
                If Flag_End = False Then
                    Output_Assets_FileSize = Output_Assets_FileSize + Output_Video_FileSize(Tj)
                    frmProgress.Update_Progress 0, False
                    modMain.Save_Log_Video "Title " & Tj & " video encoding operations have been completed."
                End If
                
                ' AUDIO encoding operations
                If Flag_End = False And Val(.AudioTracksCount) > 0 Then
                    OperationSection = "Title " & Tj & " AUDIO encoding operations start"
                    modMain.Save_Log_Video "Title " & Tj & " audio encoding operations started."
                    frmProgress.Update_Progress 1, True
                    For jj = 1 To Val(.AudioTracksCount)
                        ' Define audio file extension
                        Select Case .AudioFormat(jj)
                        Case AC3
                            AudioExt(Tj, jj) = "ac3"
                        Case MP2
                            AudioExt(Tj, jj) = "mp2"
                        Case WAV
                            AudioExt(Tj, jj) = "wav"
                        Case DTS
                            AudioExt(Tj, jj) = "dts"
                        End Select
                        ' Define audio file pathname
                        AudioPathname(Tj, jj) = AssetsPath & "\" & TitleName(Tj) & "_" & jj & "." & AudioExt(Tj, jj)
                        MBR = vbYes
                        If modFS.EsisteFile(AudioPathname(Tj, jj)) = True Then
                            MBR = frmQuestion.Display(frmMain, Msgs.FileExistsOverwrite & vbCrLf & vbCrLf & "'" & AudioPathname(Tj, jj) & "'" & vbCrLf & vbCrLf & "Default 'Yes'", , 60)
                        End If
                        If MBR = vbYes Then
                            If .AudioIsToBeKept(jj) = True And LCase(modFS.ExtOf(.InputAudioPathName(jj))) = AudioExt(Tj, jj) And OutputSetup <> MPEG2_Streams Then
                                ' Use source audio pathname and skip demux
                                AudioPathname(Tj, jj) = .InputAudioPathName(jj)
                                sLog = "SKIP AUDIO ENCODING OPERATIONS" & vbCrLf & "Source audio file '" & AudioPathname(Tj, jj) & "' is already DVD compliant."
                                bSkipAudio(Tj, jj) = True
                            End If
                            If bSkipAudio(Tj, jj) = False Then
                                If .AudioIsToBeKept(jj) = True Then
                                    ' Audio demux
                                    sCL = "-i """ & .InputAudioPathName(jj) & """ -c:a copy -vn -sn -y"
                                    sCL = sCL & modExtSW.FFmpegAudioTracksMapping(.InputAudioPathName(jj), Val(.InputAudioInfo(jj).StreamOrder))
                                    ' Handle Trim for Audio Direct Stream Copy
                                    If .AVSTrim = True Then
                                        sCL = sCL & " -ss " & modStr.VisualTime(.AVS.FrameStart / .FPSAVS, True) & " -aframes " & Round((.AVS.FrameEnd - .AVS.FrameStart) / .FPSAVS * IIf(.AudioFormat(jj) = AC3, 31.25, IIf(.AudioFormat(jj) = MP2, 125 / 3, IIf(.AudioFormat(jj) = WAV, 46.875, IIf(.AudioFormat(jj) = DTS, 93.75, .FPSAVS)))))
                                    End If
                                    sCL = sCL & " """ & AssetsPath & "\" & TitleName(Tj) & "_" & jj & ".ToFix." & AudioExt(Tj, jj) & """"
                                    sLog = "START AUDIO DEMUXING OPERATIONS (Track " & jj & ")" & vbCrLf & "FFmpeg Parameters: " & sCL
                                    modMain.Save_Log LogPathname, sLog, True
                                    ' Demux with FFmpeg
                                    modShellEx.Execute App.Path & "\FFmpeg\ffmpeg.exe", sCL, Preferences.EncodingWindowStyle, True
                                    If modUtil.GetFileSize(AssetsPath & "\" & TitleName(Tj) & "_" & jj & ".ToFix." & AudioExt(Tj, jj)) = 0 Then
                                        ' Generate FFmpeg.bat file to redirect FFmpeg echo
                                        Str = "Title " & Tj & " AUDIO DEMUXING (Track " & jj & "). Please wait ..."
                                        Str = "@echo " & Str & vbCrLf & _
                                              "@echo " & String(Len(Str), "-") & vbCrLf & _
                                              "@CHCP " & modStr.GetCodePage & vbCrLf & _
                                              """" & App.Path & "\FFmpeg\ffmpeg.exe""" & " " & sCL & " 2>""" & TempPath & "\" & TitleName(Tj) & ".FFmpeg.log"""
                                        modStr.STRtoANSIFile Str, TempPath & "\" & TitleName(Tj) & ".FFmpeg.bat"
                                        ' Demux with FFmpeg
                                        modShellEx.Execute TempPath & "\" & TitleName(Tj) & ".FFmpeg.bat", "", Preferences.EncodingWindowStyle, True
                                    End If
                                    ' Check demuxing errors
                                    bFlag = modFS.EsisteFile(AssetsPath & "\" & TitleName(Tj) & "_" & jj & ".ToFix." & AudioExt(Tj, jj))
                                    If modFS.EsisteFile(TempPath & "\" & TitleName(Tj) & ".FFmpeg.log") = True Then
                                        sLog = ""
                                        NumFile = FreeFile
                                        Open TempPath & "\" & TitleName(Tj) & ".FFmpeg.log" For Input As #NumFile
                                            Do Until EOF(NumFile) = True
                                                Line Input #NumFile, Str
                                                If InStr(1, Str, "Press [q] to stop") <> 0 Then
                                                    sLog = ""
                                                Else
                                                    sLog = sLog & Str & vbCrLf
                                                End If
                                            Loop
                                        Close NumFile
                                        If InStr(1, LCase(sLog), "error") <> 0 Then bFlag = False
                                    End If
                                    If bFlag = True Then
                                        If .AudioFormat(jj) = AC3 And .AudioFixAC3(jj) = True Then
                                            sCL = """" & AssetsPath & "\" & TitleName(Tj) & "_" & jj & ".ToFix." & AudioExt(Tj, jj) & """ """ & AudioPathname(Tj, jj) & """"
                                            sLog = "START AC3 FIXING OPERATIONS (Track " & jj & ")" & vbCrLf & "ac3fix Parameters: " & sCL
                                            modMain.Save_Log LogPathname, sLog, True
                                            modShellEx.Execute App.Path & "\ac3fix\ac3fix.exe", sCL, Preferences.EncodingWindowStyle, True
                                        Else
                                            modFS.ReName AssetsPath & "\" & TitleName(Tj) & "_" & jj & ".ToFix." & AudioExt(Tj, jj), AudioPathname(Tj, jj)
                                        End If
                                        modFS.DeleteIfExist AssetsPath & "\" & TitleName(Tj) & "_" & jj & ".ToFix." & AudioExt(Tj, jj)
                                    End If
                                Else
                                    sLog = "START AUDIO ENCODING OPERATIONS (Track " & jj & ")" & vbCrLf
                                    Select Case .AudioFormat(jj)
                                    Case AC3
                                        AudioEncoder = Preferences.AC3AudioEncoder
                                        If Preferences.ForceFFmpeg4GB = True And .TimeTrimmed > 7200 Then   '7200 seconds = 2 hours
                                            Select Case .AudioChannelsMode(jj)
                                            Case "5.0", "5.1"
                                                AudioEncoder = FFmpeg_Avisynth
                                            End Select
                                        End If
                                        bFlag = False
                                        ' Insert -readtoeof 1 to avoid Aften hanging for potentially big wave over 16 bit depth
                                        If .TimeTrimmed > 3600 Then
                                            Select Case .AudioChannelsMode(jj)
                                            Case "5.0", "5.1"
                                                bFlag = True
                                            End Select
                                        End If
                                        Flag_Exec = False
                                        Select Case AudioEncoder
                                        Case Wavi_Aften
                                            sCL = """" & AVSPathname(Tj, jj) & """ - | """ & App.Path & "\Aften\aften.exe""" & " -b " & .AudioBitRate(jj) & " -pad " & .AudioAften(jj).Pad & " -dynrng " & .AudioAften(jj).DRC & " -bwfilter " & .AudioAften(jj).BWFilter
                                            If bFlag = True Then
                                                sCL = sCL & " -readtoeof 1"
                                            End If
                                            sCL = sCL & " - """ & AudioPathname(Tj, jj) & """"
                                            sLog = sLog & "Wavi+Aften Parameters: " & sCL
                                            modMain.Save_Log LogPathname, sLog, True
                                            Str = "Title " & Tj & " AUDIO ENCODING (Track " & jj & "). Please wait ..."
                                            Str = "@echo " & Str & vbCrLf & _
                                                  "@echo " & String(Len(Str), "-") & vbCrLf
                                            If modStr.HasExtendedChars(sCL) = True Then
                                                Str = Str & "@CHCP " & modStr.GetCodePage & vbCrLf
                                            End If
                                            Str = Str & """" & App.Path & "\Wavi\Wavi.exe""" & " " & sCL    ' & " 2> """ & AssetsPath & "\" & TitleName(Tj) & "_" & jj & ".txt"""

                                            modStr.STRtoANSIFile Str, TempPath & "\" & TitleName(Tj) & ".Aften.bat"
                                            Flag_Exec = modShellEx.Execute(TempPath & "\" & TitleName(Tj) & ".Aften.bat", "", Preferences.EncodingWindowStyle, True, , 7200)     ' 2h
                                            If Flag_Exec = False Then
                                                modUtil.KillRunningProcess App.Path & "\Wavi\wavi.exe"
                                            End If
                                        Case FFmpeg_Aften
                                            sCL = "-i """ & AVSPathname(Tj, jj) & """ -c:a copy """ & TempPath & "\" & TitleName(Tj) & "_" & jj & ".wav"""
                                            sCL2 = "-b " & .AudioBitRate(jj) & " -pad " & .AudioAften(jj).Pad & " -dynrng " & .AudioAften(jj).DRC & " -bwfilter " & .AudioAften(jj).BWFilter
                                            If bFlag = True Then
                                                sCL2 = sCL2 & " -readtoeof 1"
                                            End If
                                            sCL2 = sCL2 & " """ & TempPath & "\" & TitleName(Tj) & "_" & jj & ".wav""" & " """ & AudioPathname(Tj, jj) & """"
                                            sLog = sLog & "FFmpeg (WAV) Parameters: " & sCL & vbCrLf & "Aften (AC3) Parameters: " & sCL2
                                            modMain.Save_Log LogPathname, sLog, True
                                            modShellEx.Execute App.Path & "\FFmpeg\ffmpeg.exe", sCL, Preferences.EncodingWindowStyle, True
                                            modShellEx.Execute App.Path & "\Aften\aften.exe", sCL2, Preferences.EncodingWindowStyle, True
                                        Case FFmpeg_Avisynth
                                            sCL = "-i """ & AVSPathname(Tj, jj) & """" & _
                                                        IIf(Preferences.MultiThread = True, " -threads " & SysInfo.ProcessorNumber, "") & _
                                                        " -y -vn -c:a ac3"
                                            ' Change channels configuration only if necessary
                                            Str = ""
                                            Select Case .AudioChannelsMode(jj)
                                            Case "1.0", "2.0", "5.0"
                                                Str = Left(.AudioChannelsMode(jj), 1)
                                            Case "5.1"
                                                Str = "6"
                                            End Select
                                            If Str <> "" Then
                                                If .InputAudioInfo(jj).Channels <> Str Then
                                                    sCL = sCL & " -ac " & Str
                                                End If
                                            End If
                                            sCL = sCL & " -ab " & .AudioBitRate(jj) & "k """ & AudioPathname(Tj, jj) & """"
                                            sLog = sLog & "FFmpeg Parameters: " & sCL
                                            modMain.Save_Log LogPathname, sLog, True
                                            modShellEx.Execute App.Path & "\FFmpeg\ffmpeg.exe", sCL, Preferences.EncodingWindowStyle, True
                                        Case Else
                                            ' FFmpeg Safe Mode
                                        End Select
                                    Case MP2
                                        sCL = "-i """ & AVSPathname(Tj, jj) & """" & _
                                              IIf(Preferences.MultiThread = True, " -threads " & SysInfo.ProcessorNumber, "") & _
                                              " -vn -c:a mp2" & _
                                              " -ab " & .AudioBitRate(jj) & "k -y" & _
                                              " """ & AudioPathname(Tj, jj) & """"
                                        sLog = sLog & "FFmpeg (MP2) Parameters: " & sCL
                                        modMain.Save_Log LogPathname, sLog, True
                                        modShellEx.Execute App.Path & "\FFmpeg\ffmpeg.exe", sCL, Preferences.EncodingWindowStyle, True
                                    Case WAV
                                        sCL = IIf(Preferences.MultiThread = True, "-threads " & SysInfo.ProcessorNumber, "") & " -i """ & AVSPathname(Tj, jj) & """ """ & AudioPathname(Tj, jj) & """"
                                        sLog = sLog & "FFmpeg (WAV) Parameters: " & sCL
                                        modMain.Save_Log LogPathname, sLog, True
                                        modShellEx.Execute App.Path & "\FFmpeg\ffmpeg.exe", sCL, Preferences.EncodingWindowStyle, True
                                    End Select
                                    
                                End If
                            End If
                        Else
                            sLog = "SKIP AUDIO ENCODING OPERATIONS (Track " & jj & ")" & vbCrLf & "Audio file: '" & AssetsPath & "\" & TitleName(Tj) & "." & AudioExt(Tj, jj) & "' already found."
                            'If MInfo.ReadMediaInfo(AudioPathname(Tj, jj), , False, False, True, False) = True Then
                            '    OutputAudioInfo.Initialize MInfo, 0
                            '    sLog = sLog & vbCrLf & "OUTPUT AUDIO INFO: " & OutputAudioInfo.Summary
                            'End If
                            'MInfo.Clear
                            bSkipAudio(Tj, jj) = True
                        End If
                        If bSkipAudio(Tj, jj) = False Then
                            If MBR = vbYes Then
                                MBR = vbNo
                                Str = ""
                                If .AudioFormat(jj) = AC3 And AudioEncoder = FFmpeg_Safe Then
                                    MBR = vbYes
                                Else
                                    Output_Audio_FileSize(Tj, jj) = modUtil.GetFileSize(AudioPathname(Tj, jj)) / 1024 / 1024
                                    ' Check audio filesize
                                    If Output_Audio_FileSize(Tj, jj) < 0.01 Then
                                        Str = "Audio filesize is too low (" & Round(Output_Audio_FileSize(Tj, jj), 1) & " MB)"
                                    Else
                                        ' Check audio samplerate, channels and bitrate
                                        If MInfo.ReadMediaInfo(AudioPathname(Tj, jj), , False, False, True, False) = True Then
                                            OutputAudioInfo.Initialize MInfo, 0
                                            If Val(OutputAudioInfo.SampleRate) <> 48000 Then
                                                Str = "Audio SampleRate is incorrect (" & OutputAudioInfo.SampleRate & " vs 48000 Hz)"
                                            Else
                                                If Val(OutputAudioInfo.Channels) <> Val(Left(.AudioChannelsMode(jj), 1)) + Val(Right(.AudioChannelsMode(jj), 1)) Then
                                                    Str = "Audio Channels are incorrect (" & Int(Val(OutputAudioInfo.Channels)) & " vs " & Int(Val(Left(.AudioChannelsMode(jj), 1))) + Int(Val(Right(.AudioChannelsMode(jj), 1))) & ")"
                                                Else
                                                    If Val(OutputAudioInfo.AvgBitRate) / 1000 <> Val(.AudioBitRate(jj)) Then
                                                        Str = "Audio BitRate is incorrect (" & Val(OutputAudioInfo.AvgBitRate) / 1000 & " vs " & Val(.AudioBitRate(jj)) & " kbps)"
                                                    End If
                                                End If
                                            End If
                                        End If
                                        MInfo.Clear
                                    End If
                                    If Str <> "" And AudioExt(Tj, jj) <> "dts" Then
                                        If .AVSAutoScript = .AVSScript Or jj > 1 Then
                                            sLog = "WARNING! Errors found during Title " & Tj & " Audio Track " & jj & " " & IIf(.AudioIsToBeKept(jj) = True, "demuxing", "encoding") & ". " & vbCrLf & Str
                                            MBR = frmQuestion.Display(frmMain, sLog & vbCrLf & vbCrLf & "Do you want to start Backup Audio encoding routine (FFmpeg Safe Mode)?" & vbCrLf & "Default 'Yes'", , 60)
                                            If MBR = vbYes Then
                                                sLog = sLog & vbCrLf & "Backup Audio encoding routine (FFmpeg Safe Mode) is starting ..."
                                                modMain.Save_Log LogPathname, sLog, True
                                            End If
                                        End If
                                    End If
                                End If
                                If MBR = vbYes Then
                                    ' FFmpeg safe mode
                                    For kk = 1 To 2
                                        sCL = IIf(Preferences.MultiThread = True, "-threads " & SysInfo.ProcessorNumber, "") & " -i """ & .InputAudioPathName(jj) & """"
                                        If kk = 1 Then
                                            sCL = sCL & modExtSW.FFmpegAudioTracksMapping(.InputAudioPathName(jj), Val(.InputAudioInfo(jj).StreamOrder))
                                        End If
                                        sCL = sCL & " -vn"
                                        Str = ""
                                        Select Case .AudioFormat(jj)
                                        Case AC3
                                            Str = "ac3"
                                        Case MP2
                                            Str = "mp2"
                                        Case WAV
                                            Str = "pcm_s16le"
                                        End Select
                                        If Str <> "" Then
                                            sCL = sCL & " -c:a " & Str
                                        End If
                                        ' Handle Trim
                                        If .AVSTrim = True Then
                                            sCL = sCL & " -ss " & modStr.VisualTime(.AVS.FrameStart / .FPSAVS, True) & " -t " & modStr.VisualTime((.AVS.FrameEnd - .AVS.FrameStart) / .FPSAVS, True)
                                        End If
                                        ' Change channels configuration only if necessary
                                        Str = ""
                                        Select Case .AudioChannelsMode(jj)
                                        Case "1.0", "2.0", "5.0"
                                            Str = Left(.AudioChannelsMode(jj), 1)
                                        Case "5.1"
                                            Str = "6"
                                        End Select
                                        If Str <> "" Then
                                            If .InputAudioInfo(jj).Channels <> Str Then
                                                sCL = sCL & " -ac " & Str
                                            End If
                                        End If
                                        sCL = sCL & " -ar 48000 -ab " & .AudioBitRate(jj) & "k -y """ & AudioPathname(Tj, jj) & """"
                                        sLog = "START FFMPEG (SAFE MODE) AUDIO ENCODING OPERATIONS (Track " & jj & ") - Trial " & kk & "/2" & vbCrLf & "FFmpeg Parameters: " & sCL
                                        modMain.Save_Log LogPathname, sLog, True
                                        modShellEx.Execute App.Path & "\FFmpeg\ffmpeg.exe", sCL, Preferences.EncodingWindowStyle, True
                                        Output_Audio_FileSize(Tj, jj) = modUtil.GetFileSize(AudioPathname(Tj, jj)) / 1024 / 1024
                                        If Output_Audio_FileSize(Tj, jj) > 0 Then Exit For
                                    Next kk
                                End If
                                Flag_End = False
                                If Output_Audio_FileSize(Tj, jj) > 0 Then
                                    sLog = ""
                                    ' Read A2DAudioInfo.cache file, if it exists
                                    If .AudioIsToBeKept(jj) = False And AudioEncoder <> FFmpeg_Safe And modFS.EsisteFile(TempPath & "\A2DAudioInfo.cache") = True Then
                                        If InStr(1, AVSScript(Tj, jj), "A2DAudioSource") <> 0 Then
                                            Str = ""
                                            NumFile = FreeFile
                                            Open TempPath & "\A2DAudioInfo.cache" For Input As NumFile
                                                Do Until EOF(NumFile)
                                                    Str = Str & Input(1, #NumFile)
                                                Loop
                                            Close NumFile
                                            If InStr(1, Str, .InputAudioPathName(jj)) <> 0 Then
                                                sLog = Right(Str, Len(Str) - InStr(1, Str, .InputAudioPathName(jj)))
                                                sLog = modMain.Load_Str_Object(sLog, "A2DAudioSource", "")
                                                sLog = "Audio Source Filter: A2DSource (" & sLog & ")"
                                            End If
                                        ElseIf InStr(1, AVSScript(Tj, jj), "DirectShowSource(") <> 0 Then
                                            sLog = "Audio Source Filter: DirectShowSource"
                                        ElseIf InStr(1, AVSScript(Tj, jj), "FFAudioSource(") <> 0 Then
                                            sLog = "Audio Source Filter: FFMpegSource"
                                        End If
                                    End If
                                    sLog = "END AUDIO " & _
                                           IIf(.AudioIsToBeKept(jj) = True, "DEMUXING ", "ENCODING ") & _
                                           "OPERATIONS (Track " & jj & ")" & vbCrLf & _
                                           IIf(sLog <> "", sLog & vbCrLf, "") & _
                                           "Created File: " & AudioPathname(Tj, jj) & " (" & Round(Output_Audio_FileSize(Tj, jj), 1) & " MB)"
                                    If MInfo.ReadMediaInfo(AudioPathname(Tj, jj), , False, False, True, False) = True Then
                                        OutputAudioInfo.Initialize MInfo, 0
                                        sLog = sLog & vbCrLf & "OUTPUT AUDIO INFO: " & OutputAudioInfo.Summary
                                    End If
                                    MInfo.Clear
                                    modMain.Save_Log LogPathname, sLog, True
                                    
                                    ' Check Audio errors messages
                                    Err_Message = ""
                                    If Val(OutputAudioInfo.Time) < 0.9 * Val(.TimeTrimmed) * 1000 Then
                                        Err_Message = "Warning! Title " & Tj & " Audio Track " & jj & " output Audio duration (" & modStr.VisualTime(Val(OutputAudioInfo.Time) / 1000, True) & ") is shorter than expected duration (" & modStr.VisualTime(Val(.TimeTrimmed), True) & ")."
                                    End If
                                    If Err_Message <> "" Then
                                        MBR = frmQuestion.Display(frmMain, Err_Message & vbCrLf & vbCrLf & "Do you want to continue anyway? Default 'No'", , 60)
                                        If MBR = vbYes Then
                                            sLog = "Process halted during Title " & Tj & " AUDIO (Track " & jj & ") " & IIf(.AudioIsToBeKept(jj) = True, "demuxing", "encoding") & " operations." & vbCrLf & vbCrLf & _
                                                   "Error Message: '" & Err_Message & "'" & vbCrLf & vbCrLf & _
                                                   "Audio (Track " & jj & ") errors warning message skipped."
                                            modMain.Save_Log LogPathname, sLog, True
                                            bWarning = True
                                        Else
                                            sLog = "Process aborted during Title " & Tj & " AUDIO (Track " & jj & ") " & IIf(.AudioIsToBeKept(jj) = True, "demuxing", "encoding") & " operations." & vbCrLf & vbCrLf & _
                                                   "Error Message: " & Err_Message & vbCrLf & vbCrLf & _
                                                   "For Audio issues troubleshooting see Help/FAQ/Audio section."
                                            modMain.Save_Log LogPathname, sLog, True
                                            sLog = sLog & vbCrLf & vbCrLf & _
                                                   "For more info on current project check log file <" & OutputPath & "\" & DVDName & ".log>."
                                            modMain.Save_Log_Video Err_Message
                                            Flag_End = True
                                        End If
                                    End If
                                Else
                                    Flag_End = True
                                End If
                            End If
                            ' Clean up
                            If Flag_DeleteAssets = True Then
                                modFS.DeleteIfExist AssetsPath & "\" & TitleName(Tj) & "_" & jj & ".ToFix.ac3"
                            End If
                        Else
                            ' Log skip audio
                            modMain.Save_Log LogPathname, sLog, True
                        End If
                        If Flag_End = True Then
                            Exit For
                        Else
                            Output_Audio_FileSize(Tj, jj) = modUtil.GetFileSize(AudioPathname(Tj, jj)) / 1024 / 1024
                            Output_Assets_FileSize = Output_Assets_FileSize + Output_Audio_FileSize(Tj, jj)
                            modMain.Save_Log_Video "Title " & Tj & " Audio Track " & jj & " encoding operations have been completed."
                        End If
                    Next jj
                    If Flag_End = False Then
                        frmProgress.Update_Progress 1, False
                    End If
                End If
                    
                ' Muxing operations
                If Flag_End = False And OutputSetup = MPEG2_File Then
                    OperationSection = "Title " & Tj & " Video and Audio Muxing operations"
                    modMain.Save_Log_Video "Title " & Tj & " muxing operations started."
                    frmProgress.Update_Progress 2, True
                    sLog = "START MUXING OPERATIONS" & vbCrLf
                    Err_Message = ""
                    If modFS.EsisteFile(VideoPathname(Tj)) = False Or modFS.EsisteFile(AudioPathname(Tj, 1)) = False Then
                        Err_Message = "Warning! Video/Audio elementary files missing!"
                    Else
                        Str = ""
                        bFlag = False
                        If bFlag = False Then
                            For jj = 1 To Val(.AudioTracksCount)
                                If modFS.ExtOf(AudioPathname(Tj, jj)) = "wav" Then
                                    sCL = "-i """ & AudioPathname(Tj, jj) & """ -f s16be -ar 48000 -c:a pcm_s16be """ & Left(AudioPathname(Tj, jj), Len(AudioPathname(Tj, jj)) - 4) & ".lpcm"""
                                    sLog = sLog & "FFmpeg Parameters for intermediate WAV to LPCM conversion: " & sCL & vbCrLf
                                    modShellEx.Execute App.Path & "\FFmpeg\ffmpeg.exe", sCL, Preferences.EncodingWindowStyle, True
                                    Str = Str & """" & Left(AudioPathname(Tj, jj), Len(AudioPathname(Tj, jj)) - 4) & ".lpcm"" "
                                Else
                                    Str = Str & """" & AudioPathname(Tj, jj) & """ "
                                End If
                            Next jj
                            sCL = "-f 3 -L 48000:" & Left(.AudioChannelsMode(1), 1) & ":16 -o """ & OutputPath & "\" & TitleName(Tj) & ".mpg""" & " """ & VideoPathname(Tj) & """ " & Str
                            sLog = sLog & "Mplex Parameters: " & sCL
                            modMain.Save_Log LogPathname, sLog, True
                            modShellEx.Execute App.Path & "\Mplex\mplex.exe", sCL, Preferences.EncodingWindowStyle, True
                            
                        Else
                            For jj = 1 To Val(.AudioTracksCount)
                                Str = Str & "-i """ & AudioPathname(Tj, jj) & """ "
                            Next jj
                            If Val(.AudioTracksCount) > 1 Then
                                Str = Str & "-map 0:0 "
                                For jj = 1 To Val(.AudioTracksCount)
                                    Str = Str & "-map " & jj & ":0 "
                                Next jj
                            End If
                            sCL = "-fflags +genpts -i """ & VideoPathname(Tj) & """ " & Str & "-c:v copy -c:a copy -sn -y -f vob """ & OutputPath & "\" & TitleName(Tj) & ".mpg"""
                            ' Let user to modify sCL
                            If frmMain.Int_EditEncoderParams.value = 1 Then
                                sCL = frmTextBox.Display(frmProgress, "AVStoDVD - Edit Command Parameter", "FFmpeg Muxing Command Parameters:" & vbCrLf & "(when finished press X)", sCL)
                            End If
                            sLog = sLog & "FFmpeg Parameters: " & sCL
                            modMain.Save_Log LogPathname, sLog, True
                            modShellEx.Execute App.Path & "\FFmpeg\ffmpeg.exe", sCL, Preferences.EncodingWindowStyle, True
                        End If
                        Output_MPEG2_FileSize(Tj) = modUtil.GetFileSize(OutputPath & "\" & TitleName(Tj) & ".mpg") / 1024 / 1024
                    End If
                    If Err_Message = "" Then
                        If Output_MPEG2_FileSize(Tj) < Output_Video_FileSize(Tj) Then
                            Err_Message = "Warning! Output MPEG2 file is smaller than input Video elementary file!"
                        End If
                    End If
                    ' Check Muxing errors messages
                    If Err_Message <> "" Then
                        MBR = frmQuestion.Display(frmMain, Err_Message & vbCrLf & vbCrLf & "Do you want to continue anyway? Default 'No'", , 60)
                        If MBR = vbYes Then
                            sLog = "Process halted during Title " & Tj & " muxing operations." & vbCrLf & _
                                   "Error Message: '" & Err_Message & "'" & vbCrLf & _
                                   "Muxing errors warning message skipped."
                            modMain.Save_Log LogPathname, sLog, True
                            bWarning = True
                        Else
                            sLog = "Process aborted during Title " & Tj & " muxing operations." & vbCrLf & _
                                   "Error Message: " & Err_Message & vbCrLf & _
                                   "For more info on current project check log file <" & OutputPath & "\" & DVDName & ".log>."
                            modMain.Save_Log LogPathname, sLog, True
                            Flag_End = True
                            If Flag_DeleteAssets = True Then
                                MBR = frmQuestion.Display(frmMain, "Do you want to keep the Video/Audio elementary files?" & vbCrLf & vbCrLf & "Default 'Yes'", , 30)
                                If MBR = vbYes Then Flag_DeleteAssets = False
                            End If
                        End If
                    End If
                    If Flag_DeleteAssets = True Then
                        If VideoPathname(Tj) <> .InputVideoPathName Then
                            modFS.DeleteIfExist VideoPathname(Tj)
                        End If
                        For jj = 1 To Val(.AudioTracksCount)
                            If AudioPathname(Tj, jj) <> .InputAudioPathName(jj) Then
                                modFS.DeleteIfExist AudioPathname(Tj, jj)
                            End If
                        Next jj
                    End If
                    If Flag_End = False Then
                        modMain.Save_Log_Video "Title " & Tj & " muxing operations have been completed."
                        sLog = "END MUXING OPERATIONS" & vbCrLf & "Created File: " & OutputPath & "\" & TitleName(Tj) & ".mpg (" & Round(Output_MPEG2_FileSize(Tj), 1) & " MB)"
                        modMain.Save_Log LogPathname, sLog, True
                        frmProgress.Update_Progress 2, False
                    End If
                End If
                
                ' SUBS encoding operations
                If Flag_End = False And Val(.SubsTracksCount) > 0 Then
                    OperationSection = "Title " & Tj & " SUBS encoding operations start"
                    modMain.Save_Log_Video "Title " & Tj & " subs encoding operations started."
                    frmProgress.Update_Progress 3, True
                    For jj = 1 To Val(.SubsTracksCount)
                        sLog = ""
                        If .SubsHardEncode(jj) = True Then
                            sLog = "SKIP SUBS ENCODING OPERATIONS (Track " & jj & ")" & vbCrLf & "Hard Encoded Subs"
                            modMain.Save_Log LogPathname, sLog, True
                        Else
                            ' Define input subs file pathname
                            If .InputSubsPathName(jj) = .InputVideoPathName Then
                                InputSubsPathName = TempPath & "\" & TitleName(Tj) & "." & .InputSubsInfo(jj).Extension
                                ' Extract Subtitles track from Matroska
                                If .InputSubsPathName(jj) = .InputVideoPathName Then
                                    sCL = "tracks """ & .InputSubsPathName(jj) & """ " & .InputSubsInfo(jj).StreamOrder & ":""" & InputSubsPathName & """"
                                    sLog = "START SUBS EXTRACTING OPERATIONS (Track " & jj & ")" & vbCrLf & "MKVExtract Parameters: " & sCL
                                    modMain.Save_Log LogPathname, sLog, True
                                    modShellEx.Execute App.Path & "\MKVtoolNix\mkvextract.exe", sCL, SW_DEFAULT, True, False
                                    If modUtil.GetFileSize(InputSubsPathName) > 0 Then
                                        sLog = "END SUBS EXTRACTING OPERATIONS (Track " & jj & ")" & vbCrLf & "Created File: " & InputSubsPathName & " (" & modUtil.GetFileSizeStr(InputSubsPathName) & ")"
                                        modMain.Save_Log LogPathname, sLog, True
                                    Else
                                        Flag_End = True
                                    End If
                                End If
                            Else
                                InputSubsPathName = .InputSubsPathName(jj)
                            End If
                            If Flag_End = False Then
                                sLog = "START SUBS ENCODING OPERATIONS (Track " & jj & ")" & vbCrLf
                                ' Define output subs file extension
                                Select Case UCase(.InputSubsInfo(jj).Extension)
                                Case "SRT", "SUP", "IDX", "SSA", "ASS", "SUB", "TXT"
                                    SubsExt(Tj, jj) = ".sup"
                                Case "SST"
                                    SubsExt(Tj, jj) = ".sst"
                                End Select
                                ' Define output subs file pathname
                                SubsPathname(Tj, jj) = AssetsPath & "\" & TitleName(Tj) & "_" & jj & SubsExt(Tj, jj)
                                If OutputSetup = MPEG2_File Then
                                    SubsPathname(Tj, jj) = OutputPath & "\" & TitleName(Tj) & "_" & jj & SubsExt(Tj, jj)
                                End If
                                ' Create SUP/SST file
                                Select Case UCase(.InputSubsInfo(jj).Extension)
                                Case "SRT", "SSA", "ASS", "SUB", "TXT"
                                    Select Case UCase(.InputSubsInfo(jj).Extension)
                                    Case "SRT"
                                        ' Check if SRT is in ANSI format, if not UTF-8, UTF-8 is assumed and converted to ANSI
                                        If modSubs.Check_SRT_ANSI(InputSubsPathName) = True Then
                                            FileCopy InputSubsPathName, TempPath & "\" & TitleName(Tj) & ".ToFix.srt"
                                        Else
                                            If modStr.UTF8FiletoANSIFile(InputSubsPathName, TempPath & "\" & TitleName(Tj) & ".ToFix.srt", True) = True Then
                                                sLog = sLog & "ANSI format conversion routine applied" & vbCrLf
                                            Else
                                                sLog = sLog & "ANSI format conversion routine failed" & vbCrLf
                                            End If
                                        End If
                                    Case "SSA", "ASS"
                                        kk = modSubs.Convert_ASS_to_SRT(InputSubsPathName, TempPath & "\" & TitleName(Tj) & ".ToFix.srt")
                                        If kk > -1 And modFS.EsisteFile(TempPath & "\" & TitleName(Tj) & ".ToFix.srt") = True Then
                                            sLog = sLog & "SSA/ASS to SRT conversion routine applied (" & kk & " subtitles converted)" & vbCrLf
                                        Else
                                            sLog = sLog & "SSA/ASS to SRT conversion routine failed" & vbCrLf
                                        End If
                                    Case "SUB", "TXT"
                                        kk = modSubs.Convert_SUB_to_SRT(InputSubsPathName, TempPath & "\" & TitleName(Tj) & ".ToFix.srt", FPS)
                                        If kk > -1 And modFS.EsisteFile(TempPath & "\" & TitleName(Tj) & ".ToFix.srt") = True Then
                                            sLog = sLog & "SUB (MicroDVD) to SRT conversion routine applied (" & kk & " subtitles converted)" & vbCrLf
                                        Else
                                            sLog = sLog & "SUB (MicroDVD) to SRT conversion routine failed" & vbCrLf
                                        End If
                                    End Select
                                    If modFS.EsisteFile(TempPath & "\" & TitleName(Tj) & ".ToFix.srt") = True Then
                                        ' Fix Subs Errors / Shift Times
                                        If .SubsFix(jj) = True Then
                                            ' Fix Errors
                                            kk = modSubs.Fix_SRT(TempPath & "\" & TitleName(Tj) & ".ToFix.srt", TempPath & "\" & TitleName(Tj) & ".ToSync.srt")
                                            If kk > -1 And modFS.EsisteFile(TempPath & "\" & TitleName(Tj) & ".ToSync.srt") = True Then
                                                sLog = sLog & "SRT errors fixing routine applied (" & kk & " lines fixed)" & vbCrLf
                                            Else
                                                sLog = sLog & "SRT errors fixing routine failed" & vbCrLf
                                            End If
                                            ' ReSync SRT timecodes
                                            dSubConvFact = 1
                                            If .VideoFPSAdjust = PALSpeedUp Then
                                                dSubConvFact = Val(.InputVideoInfo.FPS) / 25
                                            ElseIf .VideoFPSAdjust = NTSCSlowDown Then
                                                dSubConvFact = 25 / 23.976
                                            End If
                                            dSubShiftFact = 0
                                            If .AVS.FrameStart > 0 Then
                                                dSubShiftFact = -.AVS.FrameStart / FPS
                                            End If
                                            If dSubConvFact <> 1 Or dSubShiftFact <> 0 Then
                                                If modSubs.ReSync_SRT(TempPath & "\" & TitleName(Tj) & ".ToSync.srt", TempPath & "\" & TitleName(Tj) & ".srt", dSubConvFact, dSubShiftFact) = True And modFS.EsisteFile(TempPath & "\" & TitleName(Tj) & ".srt") = True Then
                                                    DoEvents
                                                    modUtil.Sleep 2000
                                                    sLog = sLog & "SRT ReSync routine applied (conversion factor: " & Round(dSubConvFact, 3) & ", shift factor: " & Round(dSubShiftFact, 3) & ")" & vbCrLf
                                                Else
                                                    sLog = sLog & "SRT ReSync routine failed" & vbCrLf
                                                End If
                                            Else
                                                modFS.ReName TempPath & "\" & TitleName(Tj) & ".ToSync.srt", TempPath & "\" & TitleName(Tj) & ".srt"
                                            End If
                                        Else
                                            modFS.ReName TempPath & "\" & TitleName(Tj) & ".ToSync.srt", TempPath & "\" & TitleName(Tj) & ".srt"
                                            sLog = sLog & "SRT fixing/adjusting routines skipped by project settings" & vbCrLf
                                        End If
                                    End If
                                    Flag_End = Not modFS.EsisteFile(TempPath & "\" & TitleName(Tj) & ".srt")
                                    If Flag_End = False Then
                                        ' Build new Profile.xml
                                        kk = 1
                                        If .VideoAspectRatio = Widescreen Then kk = kk + 1
                                        If VideoStandard = NTSC Then kk = kk + 2
                                        modExtSW.Build_SC_Profile_xml Title(CurrentTitle), Preferences.SubsFont, Preferences.SubsPos, True
                                        ' Build command line
                                        sCL = """" & TempPath & "\" & TitleName(Tj) & ".srt"" -p" & kk & " -i""" & App.Path & "\SubtitleCreator\Examples\VTS_01_1.IFO"""
                                        sLog = sLog & "SubtitleCreator Parameters: " & sCL
                                        modMain.Save_Log LogPathname, sLog, True
                                        ' Run SubtitleCreator
                                        modShellEx.Execute App.Path & "\SubtitleCreator\SubtitleCreator.exe", sCL, Preferences.EncodingWindowStyle, True
                                        If TempPath <> AssetsPath Then
                                            FileCopy TempPath & "\" & TitleName(Tj) & ".sup", SubsPathname(Tj, jj)
                                            modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".sup"
                                        Else
                                            modFS.ReName TempPath & "\" & TitleName(Tj) & ".sup", SubsPathname(Tj, jj)
                                        End If
                                    End If
                                Case "IDX"
                                    ' Fix Subs Errors
                                    If .SubsFix(jj) = True Then
                                        FileCopy InputSubsPathName, TempPath & "\" & TitleName(Tj) & ".ToFix.idx"
                                        FileCopy modFS.PathOf(InputSubsPathName) & modFS.NameOf(InputSubsPathName) & ".sub", TempPath & "\" & TitleName(Tj) & ".sub"
                                        kk = modSubs.Fix_IDX(TempPath & "\" & TitleName(Tj) & ".ToFix.idx", TempPath & "\" & TitleName(Tj) & ".idx")
                                        If kk > -1 Then
                                            sLog = sLog & "IDX errors fixing routine applied (" & kk & " errors fixed)." & vbCrLf
                                        Else
                                            sLog = sLog & "IDX errors fixing routine failed." & vbCrLf
                                            MBR = frmQuestion.Display(frmMain, sLog & "Do you want to continue anyway?" & vbCrLf & vbCrLf & "Default 'Yes'", , 30)
                                            If MBR = vbYes Then
                                                modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".idx"
                                                FileCopy TempPath & "\" & TitleName(Tj) & ".ToFix.idx", TempPath & "\" & TitleName(Tj) & ".idx"
                                            End If
                                        End If
                                    Else
                                        sLog = sLog & "IDX fixing routine skipped by project settings" & vbCrLf
                                    End If
                                    If modFS.EsisteFile(TempPath & "\" & TitleName(Tj) & ".idx") = True Then
                                        sCL = "-f sup -i """ & TempPath & "\" & TitleName(Tj) & ".idx" & """ -o """ & modFS.PathOf(SubsPathname(Tj, jj)) & modFS.NameOf(SubsPathname(Tj, jj)) & """" & " -id 0"
                                        sLog = sLog & "VSConv Parameters: " & sCL
                                        modMain.Save_Log LogPathname, sLog, True
                                        modShellEx.Execute App.Path & "\VobSub\VSConv.exe", sCL, Preferences.EncodingWindowStyle, True, False
                                    End If
                                Case Else
                                    sLog = sLog & "Copy Source SUP file"
                                    modMain.Save_Log LogPathname, sLog, True
                                    FileCopy InputSubsPathName, SubsPathname(Tj, jj)
                                End Select
                                If Flag_End = False Then
                                    Output_Subs_FileSize(Tj) = modUtil.GetFileSize(SubsPathname(Tj, jj)) / 1024 / 1024
                                    If Output_Subs_FileSize(Tj) > 0 Then
                                        sLog = "END SUBS ENCODING OPERATIONS (Track " & jj & ")" & vbCrLf & "Created File: " & SubsPathname(Tj, jj) & " (" & modUtil.GetFileSizeStr(SubsPathname(Tj, jj)) & ")"
                                        modMain.Save_Log LogPathname, sLog, True
                                    Else
                                        Flag_End = True
                                    End If
                                End If
                            End If
                        End If
                        Err_Message = ""
                        If Flag_End = False Then
                            Output_Assets_FileSize = Output_Assets_FileSize + Output_Subs_FileSize(Tj)
                            modMain.Save_Log_Video "Title " & Tj & " Subs Track " & jj & " encoding operations have been completed."
                        Else
                            ' Check Subs errors messages
                            Err_Message = "Process aborted during Title " & Tj & " SUBS (Track " & jj & ") encoding operations."
                            MBR = frmQuestion.Display(frmMain, Err_Message & vbCrLf & vbCrLf & "Do you want to continue anyway? Default 'No'", , 60)
                            If MBR = vbYes Then
                                Flag_End = False
                                Err_Message = Err_Message & vbCrLf & vbCrLf & _
                                              "Subs (Track " & jj & ") errors warning message skipped."
                                modMain.Save_Log LogPathname, Err_Message, True
                                modMain.Save_Log_Video Err_Message
                                bWarning = True
                            Else
                                Err_Message = Err_Message & vbCrLf & vbCrLf & _
                                              "For Subtitles issues troubleshooting see Help/FAQ/Subtitles section."
                                modMain.Save_Log LogPathname, Err_Message, True
                                Err_Message = Err_Message & vbCrLf & vbCrLf & _
                                              "For more info on current project check log file <" & OutputPath & "\" & DVDName & ".log>."
                                modMain.Save_Log_Video Err_Message
                            End If
                        End If
                        If Flag_End = True Then Exit For
                    Next jj
                    If Flag_End = False Then
                        frmProgress.Update_Progress 3, False
                    End If
                End If
                    
                ' CHAPTERS encoding operations
                If Flag_End = False And .ChaptersList <> "" And OutputSetup <> MPEG2_File Then
                    OperationSection = "Title " & Tj & " CHAPTERS encoding operations start"
                    modMain.Save_Log_Video "Title " & Tj & " Chapters encoding operations started."
                    sLog = "Title " & Tj & " Input Chapters List: " & .ChaptersList
                    Chapters_List = ""
                    Chapters_List_Array = Split(.ChaptersList, " ")
                    If VideoPathname(Tj) = .InputVideoPathName Then
                        VideoFrameCount = Int(Val(.InputVideoInfo.FrameCount))
                    Else
                        VideoFrameCount = Int(Val(OutputVideoInfo.FrameCount))
                    End If
                    For jj = 0 To UBound(Chapters_List_Array)
                        Select Case .VideoFPSAdjust
                        Case PullDown, NTSCSlowDown
                            Chapters_Frame = Int(Val(Chapters_List_Array(jj)) * FPS / .FPSAVS)
                        Case Else
                            Chapters_Frame = Int(Val(Chapters_List_Array(jj)))
                        End Select
                        If Chapters_Frame > 0 And Chapters_Frame < (VideoFrameCount - 5 * FPS) Then    ' 5 seconds guardband
                            Chapters_List = Chapters_List & Chapters_Frame & vbCrLf
                        End If
                    Next jj
                    sLog = sLog & vbCrLf & "Title " & Tj & " Output Chapters List: " & Replace(Chapters_List, vbCrLf, " ")
                    If Chapters_List <> "" Then
                        ChaptersPathname(Tj) = AssetsPath & "\" & TitleName(Tj) & "_Chapters.txt"
                        If modStr.STRtoANSIFile(Chapters_List, ChaptersPathname(Tj)) = True Then
                            sLog = sLog & vbCrLf & "Created File: " & ChaptersPathname(Tj) & " (" & modUtil.GetFileSizeStr(ChaptersPathname(Tj)) & ")"
                        Else
                            Flag_End = True
                        End If
                    Else
                        sLog = sLog & vbCrLf & "No Chapters List created for Title " & Tj
                    End If
                    Err_Message = ""
                    If Flag_End = False Then
                        modMain.Save_Log_Video "Title " & Tj & " Chapters encoding operations have been completed."
                        sLog = "DVD CHAPTERS CREATION OPERATIONS" & vbCrLf & sLog
                        modMain.Save_Log LogPathname, sLog, True
                    Else
                        ' Check Chapters errors messages
                        Err_Message = "Process aborted during Title " & Tj & " Chapters encoding operations."
                        MBR = frmQuestion.Display(frmMain, Err_Message & vbCrLf & vbCrLf & "Do you want to continue anyway? Default 'No'", , 60)
                        If MBR = vbYes Then
                            Flag_End = False
                            Err_Message = Err_Message & vbCrLf & vbCrLf & _
                                          "Chapters errors warning message skipped."
                            modMain.Save_Log LogPathname, Err_Message, True
                            modMain.Save_Log_Video Err_Message
                            bWarning = True
                        Else
                            modMain.Save_Log LogPathname, Err_Message, True
                            Err_Message = Err_Message & vbCrLf & vbCrLf & _
                                          "For more info on current project check log file <" & OutputPath & "\" & DVDName & ".log>."
                            modMain.Save_Log_Video Err_Message
                        End If
                    End If
                    If Flag_End = True Then Exit For
                End If
                    
                ' Restore audio mixer
                OperationSection = "Title " & Tj & " restore audio mixer"
                If bAudioMixer = True Then
                    modExtSW.AudioMixerRestore True, LogPathname
                End If
                
                ' Cleanup encoding working files
                OperationSection = "Title " & Tj & " cleanup encoding working files"
                If frmMain.intDeleteWorking.value = 1 Then
                    For jj = 1 To Val(.AudioTracksCount)
                        modFS.DeleteIfExist AVSPathname(Tj, jj)
                        modFS.DeleteIfExist AVSPathname(Tj, jj) & ".bat"
                        modFS.DeleteIfExist AVSPathname(Tj, jj) & ".log"
                        If TempPath <> OutputPath Then
                            modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & "_" & jj & ".wav"
                        End If
                        modFS.DeleteIfExist Left(AudioPathname(Tj, jj), Len(AudioPathname(Tj, jj)) - 4) & ".lpcm"
                    Next jj
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".FFmpeg.bat"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".FFmpeg.log"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".Aften.bat"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".HCenc.ini"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".HCenc.log"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".vcf"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".srt"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".ToFix.srt"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".ToSync.srt"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".ssa"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".ass"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".sub"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".idx"
                    modFS.DeleteIfExist TempPath & "\" & TitleName(Tj) & ".ToFix.idx"
                End If
                If Dir(TempPath & "\A2D*.cache") <> "" Then
                    Kill TempPath & "\A2D*.cache"
                End If
                modFS.DeleteIfExist .InputVideoPathName & ".ffindex"
                
            End With
            
            ' Erase variables
            Set OutputVideoInfo = Nothing
            Set OutputAudioInfo = Nothing
            
            ' Verify Progress Status combo box
            If frmProgress.Cmb_PostProcess.ListIndex = 3 Then
                Err_Message = "Process aborted by user after Title " & Tj & "."
                modMain.Save_Log_Video Err_Message & vbCrLf & vbCrLf & _
                                       "For more info on current project check log file <" & OutputPath & "\" & DVDName & ".log>.", False, True
                modMain.Save_Log LogPathname, Err_Message, True
                Flag_End = True
            End If
            
            ' If any error is encountered, abort encoding loop
            If Flag_End = True Then Exit For
        Next Tj
        
        If OutputSetup < DVD_Folder Then Flag_End = True
        
        ' Start AUTHORING operations
        If Flag_End = False Then
            OperationSection = "Start AUTHORING operations"
            modMain.Save_Log_Video "DVD authoring operations started."
            frmProgress.Update_Progress 4, True
            If EsisteFile(OutputPath & "\" & DVDName & "\VIDEO_TS\VIDEO_TS.IFO") = True Then
                Kill OutputPath & "\" & DVDName & "\VIDEO_TS\*.*"
            End If
            modFS.CreateDir OutputPath & "\" & DVDName & "\VIDEO_TS"
            modFS.CreateDir OutputPath & "\" & DVDName & "\AUDIO_TS"
            NumFile = FreeFile
            ' Building ini file for BatchMux
            OperationSection = "Building ini file for BatchMux"
            ' General
            BatchMux_ini = "-bmlog """ & TempPath & "\" & DVDName & "_BatchMux.log""" & vbCrLf & _
                           "-d """ & OutputPath & "\" & DVDName & "\VIDEO_TS""" & vbCrLf & _
                           "-mxp """ & TempPath & "\" & DVDName & "_MuxMan.mxp""" & vbCrLf & _
                           "-l """ & TempPath & "\" & DVDName & "_MuxMan.log""" & vbCrLf & _
                           "-muxman """ & App.Path & "\MuxMan""" & vbCrLf
            ' Priority
            Select Case Preferences.EncodingPriority
            Case 0
                Str = "LOW"
            Case 1
                Str = "BELOWNORMAL"
            Case 2
                Str = "NORMAL"
            Case 3
                Str = "ABOVENORMAL"
            Case 4
                Str = "HIGH"
            Case 5
                Str = "REALTIME"
            End Select
            BatchMux_ini = BatchMux_ini & "-prio " & Str & vbCrLf
            ' Subtitles Palette
            Str = Chr(9) & Chr(9) & "Color 0=0, 0, 255" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 1=255, 0, 0" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 2=0, 0, 0" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 3=" & Replace(modStr.LongtoRGB(Preferences.SubsFont.Color), ",", ", ") & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 4=0, 255, 0" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 5=255, 0, 255" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 6=255, 255, 0" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 7=0, 125, 125" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 8=125, 125, 125" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 9=225, 225, 225" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 10=125, 0, 0" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 11=0, 125, 0" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 12=0, 0, 125" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 13=222, 0, 255" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 14=222, 125, 0" & vbCrLf & _
                  Chr(9) & Chr(9) & "Color 15=125, 0, 125"
                  ' Color 2: Outline (Black)
                  ' Color 3: Text (default -> White)
                  ' Color 8: Anti-Alias (Grey)
                  ' Color 9: Background (Light Grey)
            modStr.STRtoANSIFile Str, TempPath & "\" & DVDName & "_Palette.txt"
            BatchMux_ini = BatchMux_ini & "-palette """ & TempPath & "\" & DVDName & "_Palette.txt""" & vbCrLf
            For Tj = 1 To NumTitles
                With Title(Tj)
                    Segment = ""
                    If Tj > 1 Then Segment = "SEG" & Tj
                    ' Video
                    BatchMux_ini = BatchMux_ini & "-" & Segment & "v """ & VideoPathname(Tj) & """" & vbCrLf & _
                                                  "-" & Segment & "vidmode " & IIf(.VideoAspectRatio = Widescreen, "LB", "4:3") & vbCrLf
                    ' Audio
                    For jj = 1 To Val(.AudioTracksCount)
                        BatchMux_ini = BatchMux_ini & "-" & Segment & "a" & jj & " """ & AudioPathname(Tj, jj) & """" & vbCrLf & _
                                                      "-" & Segment & "a" & jj & "lang " & Left(LCase(.AudioLanguage(jj)), 2) & vbCrLf
                    Next jj
                    ' Subs
                    For jj = 1 To Val(.SubsTracksCount)
                        If .SubsHardEncode(jj) = False Then
                            BatchMux_ini = BatchMux_ini & "-" & Segment & "s" & jj & " """ & SubsPathname(Tj, jj) & """" & vbCrLf & _
                                                          "-" & Segment & "s" & jj & "lang " & Left(LCase(.SubsLanguage(jj)), 2) & vbCrLf & _
                                                          "-" & Segment & "s" & jj & "ext " & .SubsExtension(jj) & vbCrLf
                        End If
                    Next jj
                    ' Chapters
                    If modFS.EsisteFile(ChaptersPathname(Tj)) = True Then
                        BatchMux_ini = BatchMux_ini & "-" & Segment & "cellfr """ & ChaptersPathname(Tj) & """" & vbCrLf
                        BatchMux_ini = BatchMux_ini & "-" & Segment & "progfr """ & ChaptersPathname(Tj) & """" & vbCrLf
                        BatchMux_ini = BatchMux_ini & "-" & Segment & "chapfr """ & ChaptersPathname(Tj) & """" & vbCrLf
                    End If
                End With
            Next Tj
            ' Building DVD Menu
            OperationSection = "Building DVD Menu"
            If Flag_Menu = True Then
                ' Generate DVD Menu Items parameters if they do not exist
                With DVDMenu
                    ' Generate Menu bmp/m2v/ac3 files
                    sLog = "START DVD MENU BUILDING OPERATIONS" & vbCrLf & _
                           "DVD Menu settings:" & vbCrLf & _
                           "Style: " & .Style & vbCrLf & _
                           "Aspect Ratio: " & .AR & vbCrLf & _
                           "Titles Format: " & .TitlesFormat & vbCrLf & _
                           "Template: " & .Template & vbCrLf & _
                           "Max Titles Page: " & .MaxTitlesPage & vbCrLf & _
                           "Enable Play All: " & -CInt(.PlayAllButton) & vbCrLf & _
                           "Force Play All: " & -CInt(.ForcePlayAllSelection) & vbCrLf & _
                           "Background Audio: " & -CInt(.BackgroundAudio) & vbCrLf & _
                           "Max Thumbs Row: " & .MaxThumbsRow & vbCrLf & _
                           "Thumb Image Source: " & .ThumbImageSource & vbCrLf & _
                           "Thumb Frame Position: " & .ThumbFramePos & vbCrLf & _
                           "HL Frame Format: " & .HLFormat & vbCrLf & _
                           "HL Selection Color: " & .HLColorsSel & vbCrLf & _
                           "HL Play Color: " & .HLColorsPlay & vbCrLf & _
                           "Menu Video BitRate: " & .VideoBitRate & " kbps" & vbCrLf & _
                           "Motion Menu Duration: " & .MotionMenuDuration & " seconds" & vbCrLf & _
                           "Thumb Drop Shadow: " & .ThumbShadow & vbCrLf & _
                           "Play All Shadow: " & .PlayAllShadow & vbCrLf & _
                           "Arrows Shadow: " & .ArrowsShadow
                    modMain.Save_Log LogPathname, sLog, True
                    If NumTitles <> .NumMenuTitles Then
                        Load frmDVDMenu
                        Unload frmDVDMenu
                    End If
                    modDVDMenu.Generate_DVD_Menu DVDName, , True
                    sLog = "END DVD MENU BUILDING OPERATIONS"
                    For jj = 1 To .NumMenuPages
                        Output_Assets_FileSize = Output_Assets_FileSize + GetFileSize(AssetsPath & "\" & DVDName & "_MenuPage" & jj & "." & IIf(.Style = MotionMenu, "m2v", "bmp")) / 1024 / 1024
                        sLog = sLog & vbCrLf & "Created File (Menu Page " & jj & "): " & AssetsPath & "\" & DVDName & "_MenuPage" & jj & "." & IIf(.Style = MotionMenu, "m2v", "bmp") & " (" & modUtil.GetFileSizeStr(AssetsPath & "\" & DVDName & "_MenuPage" & jj & "." & IIf(.Style = MotionMenu, "m2v", "bmp")) & ")"
                    Next jj
                    If modFS.EsisteFile(AssetsPath & "\" & DVDName & "_Menu.ac3") = True Then
                        Output_Assets_FileSize = Output_Assets_FileSize + GetFileSize(AssetsPath & "\" & DVDName & "_Menu.ac3") / 1024 / 1024
                        sLog = sLog & vbCrLf & "Created File: " & AssetsPath & "\" & DVDName & "_Menu.ac3 (" & modUtil.GetFileSizeStr(AssetsPath & "\" & DVDName & "_Menu.ac3") & ")"
                    End If
                    modMain.Save_Log LogPathname, sLog, True
                    If .AR = Standard Then
                        MenuVertRes = 540
                    Else
                        MenuVertRes = 406
                    End If
                    ' Generate HighlightScheme.csm
                    Str = "# Color scheme 1:" & vbCrLf & _
                          "set ::menued::color(1,sel_color_3) " & .HLColorsSel & vbCrLf & _
                          "set ::menued::color(1,sel_color_2) " & .HLColorsSel & vbCrLf & _
                          "set ::menued::color(1,sel_color_1) " & .HLColorsSel & vbCrLf & _
                          "set ::menued::color(1,sel_color_0) " & .HLColorsSel & vbCrLf & _
                          vbCrLf & vbCrLf & _
                          "set ::menued::color(1,sel_opacity_3) 8" & vbCrLf & _
                          "set ::menued::color(1,sel_opacity_2) 4" & vbCrLf & _
                          "set ::menued::color(1,sel_opacity_1) 2" & vbCrLf & _
                          "set ::menued::color(1,sel_opacity_0) 0" & vbCrLf & _
                          vbCrLf & vbCrLf & _
                          "set ::menued::color(1,act_color_3) " & .HLColorsPlay & vbCrLf & _
                          "set ::menued::color(1,act_color_2) " & .HLColorsPlay & vbCrLf & _
                          "set ::menued::color(1,act_color_1) " & .HLColorsPlay & vbCrLf & _
                          "set ::menued::color(1,act_color_0) " & .HLColorsPlay & vbCrLf & _
                          vbCrLf & vbCrLf & _
                          "set ::menued::color(1,act_opacity_3) 12" & vbCrLf & _
                          "set ::menued::color(1,act_opacity_2) 6" & vbCrLf & _
                          "set ::menued::color(1,act_opacity_1) 3" & vbCrLf & _
                          "set ::menued::color(1,act_opacity_0) 0" & vbCrLf & _
                          ""
                    modStr.STRtoANSIFile Str, TempPath & "\" & DVDName & "_HighlightScheme.csm"
                    ' Generate Menu.sst file
                    Str = "st_format" & Chr(9) & "2" & vbCrLf & _
                          "TV_Type" & Chr(9) & Chr(9) & IIf(VideoStandard = PAL, "PAL", "NTSC") & vbCrLf & _
                          "Tape_Type" & Chr(9) & "NON_DROP" & vbCrLf & _
                          "Display_Start" & Chr(9) & "forced" & vbCrLf & _
                          "Pixel_Area" & Chr(9) & "(2 " & IIf(VideoStandard = NTSC, "478", "574") & ")" & vbCrLf & _
                          "Display_Area" & Chr(9) & "(0 2 719 " & IIf(VideoStandard = NTSC, "478", "574") & ")" & vbCrLf & _
                          "BG" & Chr(9) & Chr(9) & "(0 0 0 = = =)" & vbCrLf & _
                          "PA" & Chr(9) & Chr(9) & "(100 100 100 = = =)" & vbCrLf & _
                          "E1" & Chr(9) & Chr(9) & "(180 180 180 = = =)" & vbCrLf & _
                          "E2" & Chr(9) & Chr(9) & "(255 255 255 = = =)" & vbCrLf & _
                          "Directory" & Chr(9) & App.Path & "\Menu" & vbCrLf & _
                          "Color" & Chr(9) & Chr(9) & "(1 1 1 1)" & vbCrLf & _
                          "Contrast" & Chr(9) & "(0 0 0 0)" & vbCrLf & _
                          "1" & Chr(9) & Chr(9) & "00:00:00:00" & Chr(9) & "00:00:00:00" & Chr(9) & "Highlights_" & IIf(VideoStandard = PAL, "PAL", "NTSC") & ".bmp"
                    modStr.STRtoANSIFile Str, AssetsPath & "\" & DVDName & "_Menu.sst"
                    ' Define BatchMux Hard Code Navigation file
                    BatchMux_hcn = "# Number of VMG menu pages" & vbCrLf & _
                                   "set ::vmg::menupages " & .NumMenuPages & vbCrLf & vbCrLf
                    ' Define Buttons assets
                    For jj = 1 To .NumMenuPages
                        ' Define Buttons highlight movements
                        For Tj = (jj - 1) * .MaxTitlesPage + 1 To jj * .MaxTitlesPage
                            If Tj <= .NumMenuTitles Then
                                NumButtons(jj) = NumButtons(jj) + 1
                                If .TitlesFormat = Thumbs Then
                                    Buttons_Type(NumButtons(jj)) = Thumbnail
                                    Buttons_Pos(NumButtons(jj)).X = .ThumbLeft(Tj)
                                    Buttons_Pos(NumButtons(jj)).w = .ThumbWidth(Tj)
                                    Buttons_Pos(NumButtons(jj)).Y = .ThumbTop(Tj)
                                    Buttons_Pos(NumButtons(jj)).h = .ThumbHeight(Tj)
                                Else
                                    Buttons_Type(NumButtons(jj)) = Label
                                    Buttons_Pos(NumButtons(jj)).X = .ThumbLabelLeft(Tj)
                                    Buttons_Pos(NumButtons(jj)).w = .ThumbLabelWidth(Tj)
                                    Buttons_Pos(NumButtons(jj)).Y = .ThumbLabelTop(Tj)
                                    Buttons_Pos(NumButtons(jj)).h = .ThumbLabelHeight(Tj)
                                End If
                            End If
                        Next Tj
                        If jj > 1 Then
                            NumButtons(jj) = NumButtons(jj) + 1
                            Buttons_Type(NumButtons(jj)) = ArrowL
                            Buttons_Pos(NumButtons(jj)).X = .ArrowLButtonLeft
                            Buttons_Pos(NumButtons(jj)).w = .ArrowLButtonWidth
                            Buttons_Pos(NumButtons(jj)).Y = .ArrowLButtonTop
                            Buttons_Pos(NumButtons(jj)).h = .ArrowLButtonHeight
                        End If
                        If jj < .NumMenuPages Then
                            NumButtons(jj) = NumButtons(jj) + 1
                            Buttons_Type(NumButtons(jj)) = ArrowR
                            Buttons_Pos(NumButtons(jj)).X = .ArrowRButtonLeft
                            Buttons_Pos(NumButtons(jj)).w = .ArrowRButtonWidth
                            Buttons_Pos(NumButtons(jj)).Y = .ArrowRButtonTop
                            Buttons_Pos(NumButtons(jj)).h = .ArrowRButtonHeight
                        End If
                        If .PlayAllButton = True Then
                            NumButtons(jj) = NumButtons(jj) + 1
                            Buttons_Type(NumButtons(jj)) = PlayAll
                            Buttons_Pos(NumButtons(jj)).X = .PlayAllButtonLeft
                            Buttons_Pos(NumButtons(jj)).w = .PlayAllButtonWidth
                            Buttons_Pos(NumButtons(jj)).Y = .PlayAllButtonTop
                            Buttons_Pos(NumButtons(jj)).h = .PlayAllButtonHeight
                        End If
                        modDVDMenu.DVD_Adj_But NumButtons(jj), Buttons_Pos, Buttons_Adj, , MenuVertRes
                        ' Generate Buttons.mnu file
                        Buttons_mnu = "# Page " & jj & " Buttons" & vbCrLf & vbCrLf & _
                                      "# Number of buttons and groups:" & vbCrLf & _
                                      "set ::menued::numbuts " & NumButtons(jj) & vbCrLf & _
                                      "set ::menued::numgroups " & IIf(.AR = Standard, "1", "2") & vbCrLf & vbCrLf & _
                                      "# Group types (0=undefined, 1=normal, 2=letterbox, 4=pan&scan):" & vbCrLf & _
                                      "set ::menued::grouptype(1) 1" & vbCrLf
                        If .AR = Standard Then
                            Buttons_mnu = Buttons_mnu & vbCrLf
                        Else
                            Buttons_mnu = Buttons_mnu & _
                                      "set ::menued::grouptype(2) 2" & vbCrLf & vbCrLf
                        End If
                        For Tj = 1 To NumButtons(jj)
                            Button_Pos_Y = Round(Buttons_Pos(Tj).Y * IIf(VideoStandard = NTSC, 480, 576) / MenuVertRes, 0)
                            Button_Pos_H = Round(Buttons_Pos(Tj).h * IIf(VideoStandard = NTSC, 480, 576) / MenuVertRes, 0)
                            If .HLFormat = Underline Then
                                Button_Pos_Y = Button_Pos_Y + Button_Pos_H - 3
                                Button_Pos_H = 6
                            End If
                            Buttons_mnu = Buttons_mnu & _
                                          "# Button " & Tj & ":" & vbCrLf & _
                                          "# Group 1" & vbCrLf & _
                                          "set ::menued::but(posx,1," & Tj & ") " & Buttons_Pos(Tj).X & vbCrLf & _
                                          "set ::menued::but(posw,1," & Tj & ") " & Buttons_Pos(Tj).w & vbCrLf & _
                                          "set ::menued::but(posy,1," & Tj & ") " & Button_Pos_Y & vbCrLf & _
                                          "set ::menued::but(posh,1," & Tj & ") " & Button_Pos_H & vbCrLf & _
                                          "set ::menued::but(adj_but_up,1," & Tj & ") " & Buttons_Adj(Tj).Up & vbCrLf & _
                                          "set ::menued::but(adj_but_left,1," & Tj & ") " & Buttons_Adj(Tj).Left & vbCrLf & _
                                          "set ::menued::but(adj_but_right,1," & Tj & ") " & Buttons_Adj(Tj).Right & vbCrLf & _
                                          "set ::menued::but(adj_but_down,1," & Tj & ") " & Buttons_Adj(Tj).Down & vbCrLf & _
                                          "set ::menued::but(color_scheme,1," & Tj & ") 1" & vbCrLf & _
                                          "set ::menued::but(auto_activate,1," & Tj & ") 0" & vbCrLf
                            Select Case Buttons_Type(Tj)
                            Case Thumbnail, Label
                                JumpTitle = (jj - 1) * .MaxTitlesPage + Tj
                                JumpPGC = .NumMenuPages + jj
                            Case ArrowL
                                JumpTitle = (jj - 2) * .MaxTitlesPage + 1
                                JumpPGC = jj - 1
                            Case ArrowR
                                JumpTitle = jj * .MaxTitlesPage + 1
                                JumpPGC = jj + 1
                            Case PlayAll
                                JumpTitle = (jj - 1) * .MaxTitlesPage + 1
                                JumpPGC = .NumMenuPages + jj
                            End Select
                            Buttons_mnu = Buttons_mnu & _
                                          "set ::menued::but(command,1," & Tj & ") {[71 04 00 00 00 " & modStr.PadLeft(Hex(JumpTitle), "0", 2) & " 00 " & modStr.PadLeft(Hex(JumpPGC), "0", 2) & "]}" & vbCrLf & _
                                          "# Set gprm(0) =(mov) " & JumpTitle & " ; LinkPGCN PGC " & JumpPGC & vbCrLf & vbCrLf
                            
                            If .AR = Widescreen Then
                                Button_Pos_Y = Round((67 + Buttons_Pos(Tj).Y) * IIf(VideoStandard = NTSC, 480, 576) / 540, 0)
                                Button_Pos_H = Round(Buttons_Pos(Tj).h * IIf(VideoStandard = NTSC, 480, 576) / 540, 0)
                                If .HLFormat = Underline Then
                                    Button_Pos_Y = Button_Pos_Y + Button_Pos_H - 3
                                    Button_Pos_H = 6
                                End If
                                Buttons_mnu = Buttons_mnu & _
                                          "# Group 2" & vbCrLf & _
                                          "set ::menued::but(posx,2," & Tj & ") " & Buttons_Pos(Tj).X & vbCrLf & _
                                          "set ::menued::but(posw,2," & Tj & ") " & Buttons_Pos(Tj).w & vbCrLf & _
                                          "set ::menued::but(posy,2," & Tj & ") " & Button_Pos_Y & vbCrLf & _
                                          "set ::menued::but(posh,2," & Tj & ") " & Button_Pos_H & vbCrLf & _
                                          "set ::menued::but(adj_but_up,2," & Tj & ") " & Buttons_Adj(Tj).Up & vbCrLf & _
                                          "set ::menued::but(adj_but_left,2," & Tj & ") " & Buttons_Adj(Tj).Left & vbCrLf & _
                                          "set ::menued::but(adj_but_right,2," & Tj & ") " & Buttons_Adj(Tj).Right & vbCrLf & _
                                          "set ::menued::but(adj_but_down,2," & Tj & ") " & Buttons_Adj(Tj).Down & vbCrLf & _
                                          "set ::menued::but(color_scheme,2," & Tj & ") 1" & vbCrLf & _
                                          "set ::menued::but(auto_activate,2," & Tj & ") 0" & vbCrLf
                                Buttons_mnu = Buttons_mnu & _
                                          "set ::menued::but(command,1," & Tj & ") {[71 04 00 00 00 " & modStr.PadLeft(Hex(JumpTitle), "0", 2) & " 00 " & modStr.PadLeft(Hex(JumpPGC), "0", 2) & "]}" & vbCrLf & _
                                          "# Set gprm(0) =(mov) " & JumpTitle & " ; LinkPGCN PGC " & JumpPGC & vbCrLf & vbCrLf
                            End If
                        Next Tj
                        Buttons_mnu = Buttons_mnu & vbCrLf & _
                                      "# Global parameters:" & vbCrLf & _
                                      "set ::menued::force_select_but " & -CInt(.ForcePlayAllSelection) * NumButtons(jj) & vbCrLf & _
                                      "set ::menued::force_action_but 0" & vbCrLf & _
                                      "set ::menued::selendtime -1" & vbCrLf & _
                                      "set ::menued::numselectablebuts " & NumButtons(jj)
                        modStr.STRtoANSIFile Buttons_mnu, TempPath & "\" & DVDName & "_MenuPage" & jj & "_Buttons.mnu"
                        BatchMux_hcn = BatchMux_hcn & _
                                       "# Page" & jj & ":" & vbCrLf & _
                                       "set ::vmg::menutype(" & jj & ") " & .Style & vbCrLf & vbCrLf & _
                                       "# Number of buttons leading to 'Titles'" & vbCrLf & _
                                       "set ::vmg::titlebut(" & jj & ") " & NumButtons(jj) - IIf(.PlayAllButton = True, 1, 0) - IIf(.NumMenuPages = 1, 0, IIf(jj = 1, 1, IIf(jj = .NumMenuPages, 1, 2))) & vbCrLf & vbCrLf & _
                                       "'Play All' button number (0 --> 'Play All' button not present)" & vbCrLf & _
                                       "set ::vmg::playallbut(" & jj & ") " & IIf(.PlayAllButton = True, NumButtons(jj), "0")
                        BatchMux_ini = BatchMux_ini & _
                                       "-SEG" & .NumMenuTitles + jj & "v """ & AssetsPath & "\" & DVDName & "_MenuPage" & jj & IIf(.Style = MotionMenu, ".m2v""", ".bmp""") & vbCrLf & _
                                       "-SEG" & .NumMenuTitles + jj & "vidmode " & IIf(.AR = Standard, "4:3", "LB") & vbCrLf
                        If modFS.EsisteFile(AssetsPath & "\" & DVDName & "_Menu.ac3") = True Then
                            BatchMux_ini = BatchMux_ini & "-SEG" & .NumMenuTitles + jj & "a1 """ & AssetsPath & "\" & DVDName & "_Menu.ac3""" & vbCrLf
                        End If
                        BatchMux_ini = BatchMux_ini & _
                                       "-SEG" & .NumMenuTitles + jj & "s1 """ & AssetsPath & "\" & DVDName & "_Menu.sst""" & vbCrLf & _
                                       "-SEG" & .NumMenuTitles + jj & "s1dmode " & IIf(.AR = Standard, "LB", "WIDE_LB") & vbCrLf & _
                                       "-SEG" & .NumMenuTitles + jj & "hlmnu """ & TempPath & "\" & DVDName & "_MenuPage" & jj & "_Buttons.mnu""" & vbCrLf & _
                                       "-SEG" & .NumMenuTitles + jj & "hlcsm """ & TempPath & "\" & DVDName & "_HighlightScheme.csm" & vbCrLf  ' App.Path & "\Menu\Highlight_Scheme.csm""" & vbCrLf
                    Next jj
                    ' Output BatchMux hcn (Navigation configuration) file
                    modStr.STRtoANSIFile BatchMux_hcn, TempPath & "\" & DVDName & "_BatchMux.hcn"
                    BatchMux_ini = BatchMux_ini & "-hcn """ & TempPath & "\" & DVDName & "_BatchMux.hcn"""
                End With
            End If
            ' Let user to modify Batchmux.ini
            If frmMain.Int_EditEncoderParams.value = 1 Then
                BatchMux_ini = frmTextBox.Display(frmProgress, "AVStoDVD - Edit Command Parameter", "BatchMux Command INI file:" & vbCrLf & "(when finished press X)", BatchMux_ini)
            End If
            ' Write Batchmux.ini file
            modStr.STRtoANSIFile BatchMux_ini, TempPath & "\" & DVDName & "_BatchMux.ini"
            ' Building cli parameters for BatchMux
            OperationSection = "Building cli parameters for BatchMux"
            sCL = "-arglist """ & TempPath & "\" & DVDName & "_BatchMux.ini"""
            sLog = "START DVD AUTHORING OPERATIONS" & vbCrLf & "BatchMux Parameters: " & sCL & vbCrLf & "BatchMux ini file:" & vbCrLf & BatchMux_ini
            modMain.Save_Log LogPathname, sLog, True
            ' Start Authoring
            OperationSection = "DVD Authoring operations"
            Err_Message = ""
            With frmMessage
                .Initialize "AVStoDVD - DVD Authoring", "MuxMan is starting ...", , , , 0, Int(frmMain.Txt_Estimated_Output_Size.Text)
                .Show 0, Screen.ActiveForm
                DoEvents
                modUtil.Sleep 1000
                modShellEx.Execute App.Path & "\BatchMux\BatchMux.exe", sCL, SW_HIDE, False
                modUtil.Sleep 10000
                Do
                    If .FormIsClosedByUser = True Then
                        modUtil.KillRunningProcess App.Path & "\MuxMan\MuxMan.exe"
                    Else
                        .Update "MuxMan is running ..." & vbCrLf, Round(GetDirSize(OutputPath & "\" & DVDName & "\VIDEO_TS") / 1024 / 1024, 0)
                        If .ProgressBar.value / .ProgressBar.Max > 0.98 Then
                            .Update "MuxMan is finalizing DVD." & vbCrLf & "Please wait ..."
                        End If
                        .Update .lblMessage.Caption & vbCrLf & .ProgressBar.value & " / " & .ProgressBar.Max & " MB completed."
                    End If
                    modUtil.Sleep 200
                Loop Until modUtil.FindRunningProcess(App.Path & "\BatchMux\BatchMux.exe") = 0
                If .FormIsClosedByUser = True Then
                    Err_Message = "DVD AUTHORING operations aborted by user."
                Else
                    .ProgressBar.value = .ProgressBar.Max
                    .Update vbCrLf & "MuxMan has finished!", .ProgressBar.Max
                    DoEvents
                    modUtil.Sleep 1000
                    modUtil.WaitForFile OutputPath & "\" & DVDName & "\VIDEO_TS\VIDEO_TS.IFO", 5
                End If
            End With
            Unload frmMessage
            If Err_Message = "" Then
                Debug.Print GetFileSize(OutputPath & "\" & DVDName & "\VIDEO_TS\VTS_" & Format(NumTitles, "00") & "_0.IFO")
                If GetFileSize(OutputPath & "\" & DVDName & "\VIDEO_TS\VTS_" & Format(NumTitles, "00") & "_0.IFO") > 0 Then
                    If GetFileSize(OutputPath & "\" & DVDName & "\VIDEO_TS\VIDEO_TS.IFO") > 0 Then
                        Err_Message = ""
                    Else
                        Err_Message = "Process aborted during DVD AUTHORING finalization! " & vbCrLf & vbCrLf
                    End If
                Else
                    Err_Message = "Process aborted during DVD AUTHORING operations! " & vbCrLf & vbCrLf
                End If
            End If
            If Err_Message <> "" Then Flag_End = True
            If Flag_End = True Then
                If InStr(1, Err_Message, "aborted by user") = 0 Then
                    Str = ""
                    NumFile = FreeFile
                    Open TempPath & "\" & DVDName & "_BatchMux.log" For Input As #NumFile
                        Do Until EOF(NumFile) = True
                            Line Input #NumFile, Str
                            If InStr(1, LCase(Str), "excessive bitrate") <> 0 Or InStr(1, LCase(Str), "video decoder buffer underflowed") <> 0 Then
                                Err_Message = Err_Message & "DVD Authoring operation failed, probably caused by excessive bitrate." & vbCrLf & _
                                                            "Decrease video and/or audio bitrates and then retry the project." & vbCrLf & vbCrLf
                                Exit Do
                            End If
                        Loop
                    Close NumFile
                    Err_Message = Err_Message & _
                                  "Check following files for more details: " & vbCrLf & vbCrLf & _
                                  "AVStoDVD log file <" & OutputPath & "\" & DVDName & ".log> " & vbCrLf & _
                                  "BatchMux log file <" & OutputPath & "\" & DVDName & "_BatchMux.log>" & vbCrLf & vbCrLf & _
                                  "For more troubleshooting on Authoring issues, see Help/FAQ/Authoring."
                    If OutputPath <> TempPath Then
                        modFS.DeleteIfExist OutputPath & "\" & DVDName & "_BatchMux.log"
                        modUtil.Sleep 1000
                        FileCopy TempPath & "\" & DVDName & "_BatchMux.log", OutputPath & "\" & DVDName & "_BatchMux.log"
                    End If
                End If
                modMain.Save_Log LogPathname, Err_Message, True
                modMain.Save_Log_Video Err_Message
                MBR = frmQuestion.Display(frmMain, Err_Message & vbCrLf & vbCrLf & "Before exiting, do you want to keep the temporary DVD assets files?" & vbCrLf & vbCrLf & "Default 'Yes'", , 60, True)
                If MBR = vbYes Then Flag_DeleteAssets = False
            Else
                ' Calculate DVD Size
                Output_DVD_FileSize = Round(modUtil.GetDirSize(OutputPath & "\" & DVDName & "\VIDEO_TS") / 1024 / 1024, 1)
                sLog = "END DVD AUTHORING OPERATIONS" & vbCrLf & "Created Folder: " & OutputPath & "\" & DVDName & " (" & Output_DVD_FileSize & " MB)" & vbCrLf & vbCrLf & _
                       "CHECK DVD SIZE" & vbCrLf & _
                       "DVD Folder (actual) Size: " & Output_DVD_FileSize & " MB" & vbCrLf
                ' Check DVD Size vs Assets
                Output_Assets_FileSize = Round(Output_Assets_FileSize, 1)
                Str = ""
                If Output_DVD_FileSize < 0.9 * Output_Assets_FileSize Then
                    Str = "smaller"
                ElseIf Output_DVD_FileSize > 1.1 * Output_Assets_FileSize Then
                    Str = "greater"
                End If
                If Str <> "" Then
                    Str = "Warning! DVD Folder filesize (" & Output_DVD_FileSize & " MB) is much " & Str & " than the total Assets filesize (" & Output_Assets_FileSize & " MB)."
                    modMain.Save_Log_Video Str, , True
                    bWarning = True
                End If
                sLog = sLog & "vs Assets Size: " & Output_Assets_FileSize & " MB -> " & IIf(Str <> "", "Warning!", "OK") & vbCrLf
                ' Check DVD Size vs Estimated
                If Output_DVD_FileSize > 1.05 * Val(frmMain.Txt_Estimated_Output_Size.Text) And Output_DVD_FileSize > 10 Then
                    Str = "Warning! DVD Folder filesize (" & Output_DVD_FileSize & " MB) is greater than the estimated filesize (" & Val(frmMain.Txt_Estimated_Output_Size.Text) & " MB)."
                    modMain.Save_Log_Video Str, , True
                    bWarning = True
                End If
                sLog = sLog & "vs Estimated Size: " & frmMain.Txt_Estimated_Output_Size.Text & " MB -> " & Format(Abs((Output_DVD_FileSize - Val(frmMain.Txt_Estimated_Output_Size.Text))) / Val(frmMain.Txt_Estimated_Output_Size.Text), "0.0%") & IIf(Val(frmMain.Txt_Estimated_Output_Size.Text) > Output_DVD_FileSize, " undersize", " oversize")
                ' Log Authoring
                modMain.Save_Log_Video "DVD authoring operations have been completed."
                modMain.Save_Log LogPathname, sLog, True
                frmProgress.Update_Progress 4, False
            End If
            ' Delete temporary assets files
            If Flag_DeleteAssets = True Then
                For Tj = 1 To NumTitles
                    If VideoPathname(Tj) <> Title(Tj).InputVideoPathName Then
                        modFS.DeleteIfExist VideoPathname(Tj)
                    End If
                    For jj = 1 To Val(Title(Tj).AudioTracksCount)
                        If AudioPathname(Tj, jj) <> Title(Tj).InputAudioPathName(jj) Then
                            modFS.DeleteIfExist AudioPathname(Tj, jj)
                        End If
                    Next jj
                    For jj = 1 To Val(Title(Tj).SubsTracksCount)
                        modFS.DeleteIfExist SubsPathname(Tj, jj)
                    Next jj
                    modFS.DeleteIfExist ChaptersPathname(Tj)
                Next Tj
                For jj = 1 To DVDMenu.NumMenuPages
                    modFS.DeleteIfExist AssetsPath & "\" & DVDName & "_MenuPage" & jj & ".m2v"
                    modFS.DeleteIfExist AssetsPath & "\" & DVDName & "_MenuPage" & jj & ".bmp"
                Next jj
                modFS.DeleteIfExist AssetsPath & "\" & DVDName & "_Menu.ac3"
                modFS.DeleteIfExist AssetsPath & "\" & DVDName & "_Menu.sst"
            End If
        End If
        If OutputSetup = DVD_Folder Then Flag_End = True
        
        ' ISO building operations
        If Flag_End = False And OutputSetup = ISO_UDF_Image Then
            OperationSection = "ISO building operations"
            If ISOBuildingOps = False Then
                Flag_End = True
                If Flag_DeleteAssets = True Then
                    MBR = frmQuestion.Display(frmMain, "Do you want to keep the temporary DVD Assets files?" & vbCrLf & vbCrLf & "Default 'Yes'", , 30)
                    If MBR = vbYes Then Flag_DeleteAssets = False
                End If
            End If
            If Flag_DeleteAssets = True Then
                Kill OutputPath & "\" & DVDName & "\VIDEO_TS\*.*"
                DeleteIfExist OutputPath & "\" & DVDName & "\VIDEO_TS", True
                DeleteIfExist OutputPath & "\" & DVDName & "\AUDIO_TS", True
                DeleteIfExist OutputPath & "\" & DVDName, True
            End If
        End If
        If OutputSetup = ISO_UDF_Image Then Flag_End = True
        
        ' DVD burning operations
        If Flag_End = False Then
            OperationSection = "DVD burning operations"
            Flag_End = DVDBurningOps
        End If
        
        ' Clean up
        OperationSection = "Clean up"
        If frmMain.intDeleteWorking.value = 1 Then
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_HighlightScheme.csm"
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_TitleText.ass"
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_BatchMux.ini"
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_BatchMux.hcn"
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_BatchMux.bat"
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_BatchMux.log"
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_MuxMan.mxp"
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_MuxMan.log"
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_Palette.txt"
            modFS.DeleteIfExist TempPath & "\" & DVDName & "_ImgBurn.log"
            modFS.DeleteIfExist TempPath & "\Picture.avs"
            modFS.DeleteIfExist TempPath & "\Picture.bmp"
            For jj = 1 To DVDMenu.NumMenuPages
                modFS.DeleteIfExist TempPath & "\" & DVDName & "_MenuPage" & jj & ".avs"
                modFS.DeleteIfExist TempPath & "\" & DVDName & "_MenuPage" & jj & "_Buttons.mnu"
            Next jj
            For Tj = 1 To NumTitles
                modFS.DeleteIfExist TempPath & "\" & DVDName & "_Thumb_" & Tj & "_AviSynthT.avs"
                modFS.DeleteIfExist TempPath & "\" & DVDName & "_Thumb_" & Tj & ".bmp"
                modFS.DeleteIfExist TempPath & "\" & DVDName & "_Thumb_" & Tj & "_Video.avs"
                modFS.DeleteIfExist TempPath & "\" & DVDName & "_ThumbLabelText" & Tj & ".ass"
            Next Tj
        End If
        sLog = ""
        If InStr(1, frmProgress.Caption, "/") <> 0 Then   ' Check Jobs Batch
            Str = "Job" & StrTrimRight(StrTrimLeft(frmProgress.Caption, "-"), "-")
        Else
            Str = "Project"
        End If
        If frmMain.lViewOper.ListItems.Item(frmMain.lViewOper.ListItems.Count).SmallIcon = 7 Then   ' 7 -> error icon
            sLog = "Warning! AVStoDVD " & Str & " ended with errors."
        ElseIf bWarning = True Then
            sLog = "AVStoDVD " & Str & " ended with warnings."
        Else
            sLog = "AVStoDVD " & Str & " ended successfully."
        End If
        modMain.Save_Log LogPathname, sLog, True, True
        modMain.Save_Log_Video "For more Project details, see: '" & LogPathname & "'"
        frmMain.lViewOper.Tag = LogPathname
        frmProgress.Finish
    End If
    
    GoTo Exit_Handling
    

Err_Handling:
Select Case Err.Number
Case 70 'Autorizzazione negata
    Resume Next
Case Else
    If Preferences.DSFiltersRuntime = True Then modExtSW.AudioMixerRestore
    ' Save error log
    sLog = "WARNING! Process aborted during '" & OperationSection & "' Section."
    If Err.Number <> 0 Then
        sLog = sLog & vbCrLf & "Error Code: " & Err.Number & " - " & Err.Description
    End If
    modMain.Save_Log LogPathname, sLog, True, True
    ' Unload forms
    Unload frmMessage
    Unload frmTextBox
    If modUtil.FormIsLoad("frmProgress") = True Then frmProgress.Finish
End Select


Exit_Handling:
Set MInfo = Nothing
Set OutputVideoInfo = Nothing
Set OutputAudioInfo = Nothing
If modFS.EsisteFile(LogPathname) = True Then
    modMain.Save_Log LogPathname, "Log file created by " & frmMain.StatusBar.Panels("Release").Text, True
End If
Screen.MousePointer = vbDefault

End Sub


Private Function LogPreferencesBuildOps()

    Dim sStr As String

    With Preferences
        sStr = sStr & _
               "PREFERENCES" & vbCrLf & vbCrLf
        sStr = sStr & _
               "MultiThread: " & -CInt(.MultiThread) & vbCrLf & _
               "AVS Video Source Filter: " & .AVSVideoInput & vbCrLf & _
               "AVS Audio Source Filter: " & .AVSAudioInput & vbCrLf & _
               "AVS UpSize/DownSize Filter: " & .AVSUpSize & "/" & .AVSDownSize & vbCrLf & _
               "Frame Adjust Strategy: " & .FrameAdjust & vbCrLf & _
               "FPS Hard Conversion: " & .FPSHardConversion & vbCrLf & _
               "PAL SpeedUp: " & -CInt(.PALSpeedUp) & vbCrLf & _
               "NTSC SlowDown: " & -CInt(.NTSCSlowDown) & vbCrLf & _
               "Video Resolution: " & .VideoResolution & vbCrLf & _
               "Video Encoder: " & .VideoEncoder & vbCrLf & _
               "Video BitRate Min: " & .VideoMinAvgBitRate & vbCrLf & _
               "Video BitRate Max: " & .VideoMaxAvgBitRate & vbCrLf & _
               "Keep DVD Compliant Video: " & -CInt(.KeepOrigVideo) & vbCrLf & _
               "AC3 Audio Encoder: " & .AC3AudioEncoder & vbCrLf & _
               "Force FFmpeg for Long Audio: " & -CInt(.ForceFFmpeg4GB) & vbCrLf & _
               "DVD Audio Format: " & .AudioFormat & vbCrLf & _
               "DVD Audio BitRate: " & .AudioBitRate & vbCrLf & _
               "Keep DVD Compliant Audio: " & -CInt(.KeepOrigAudio) & vbCrLf & _
               "Normalize Audio: " & -CInt(.AudioNormalize) & IIf(.AudioNormalize = True, " (@ " & .AudioNormalizeVal & ")", "") & vbCrLf & _
               "Auto Delay Audio: " & -CInt(.AudioDelayAuto) & vbCrLf
        sStr = sStr & _
               "DVD Audio Language (Primary): " & .AudioLanguage & vbCrLf & _
               "DVD Audio Language (Secondary): " & .AudioLanguage2 & vbCrLf & _
               "DVD Subs Language (Primary): " & .SubsLanguage & vbCrLf & _
               "DVD Subs Language (Secondary): " & .SubsLanguage2 & vbCrLf & _
               "DVD Subs Font: " & .SubsFont.Name & " " & .SubsFont.Height & "pt" & IIf(.SubsFont.Bold = True, " Bold", "") & IIf(.SubsFont.Italic = True, " Italic", "") & " (" & modStr.LongtoRGB(.SubsFont.Color) & ")" & vbCrLf & _
               "Chapters Interval: " & .ChaptersInterval & vbCrLf & _
               "Use Source Chapters: " & -CInt(.ChaptersUseSource) & vbCrLf & _
               "DVD Burning Drive: " & .DVDBurningDrive & vbCrLf & _
               "DVD Burning Speed: " & .DVDBurningSpeed & vbCrLf & _
               "Auto Erase DVD RW: " & -CInt(.DVDAutoErase) & vbCrLf & _
               "Execute with Elevated Privileges: " & -CInt(.ForceRunAsAdmin) & vbCrLf & _
               "Unload ActiveMovie Library: " & -CInt(.UnloadDShow) & vbCrLf & _
               "Adjust DirectShow Filters at runtime: " & -CInt(.DSFiltersRuntime) & vbCrLf & _
               "Save General Settings: " & -CInt(.SaveSettings) & vbCrLf & vbCrLf
    End With
    With SysInfo
        sStr = sStr & _
               "SYSTEM INFO" & vbCrLf & vbCrLf & _
               "Processor Name: " & .ProcessorName & vbCrLf & _
               "Operating System: " & .WinVerStr(True) & vbCrLf & _
               "User has Admin Rights: " & IIf(CBool(.IsAdmin) = True, "YES", "NO") & vbCrLf & _
               "Running with Elevated Privileges: " & IIf(.ElevatedPrivileges = 2, "YES", "NO (" & .ElevatedPrivileges & ")") & vbCrLf & _
               "Available Output Disc Space: " & Int(Val(modFS.atDiskFreeSpaceEx(Left(OutputPath, 1))) / 1024) & " GB" & vbCrLf & _
               "AviSynth is installed: " & IIf(AviSynth.PathName <> "", "YES (release " & AviSynth.Version & ")", "NO") & vbCrLf & _
               "LAV Filters is installed: " & IIf(LAVFilters.PathName <> "", "YES (release " & LAVFilters.Version & ")", "NO") & vbCrLf & _
               "ffdshow is installed: " & IIf(ffdshow.PathName <> "", "YES (release " & ffdshow.Version & ")", "NO")
    End With
    If SysInfo.WinVerMajor * 10 + SysInfo.WinVerMinor >= 61 Then   ' Windows 7 -> ...
        sStr = sStr & vbCrLf & vbCrLf & _
               "CODECS REPORT" & vbCrLf & vbCrLf & _
               frmCodecsCheck.CodecsReport
    End If

    LogPreferencesBuildOps = sStr
    
End Function


' ISO building operations Core
Private Function ISOBuildingOps() As Boolean

    modMain.Save_Log_Video "ISO Image building operations started."
    frmProgress.Update_Progress 5, True
    Err_Message = ""
    sCL = "/mode isobuild /buildmode imagefile /src """ & OutputPath & "\" & DVDName & "\VIDEO_TS""" & " /dest """ & OutputPath & "\" & DVDName & ".iso""" & " /volumelabel """ & DVD_Label & """ /filesystem ""ISO9660 + UDF"" /udfrevision ""1.02"" /overwrite yes /noimagedetails /start /close"
    sLog = "START ISO IMAGE BUILDING OPERATIONS" & vbCrLf & "ImgBurn (ISO) Parameters: " & sCL
    modMain.Save_Log LogPathname, sLog, True
    modShellEx.Execute PathNames.ImgBurn, sCL, SW_DEFAULT, True
    If modUtil.GetFileSize(OutputPath & "\" & DVDName & ".iso") > 0 Then
        sLog = "END ISO IMAGE BUILDING OPERATIONS" & vbCrLf & "Created File: " & OutputPath & "\" & DVDName & ".iso (" & modUtil.GetFileSizeStr(OutputPath & "\" & DVDName & ".iso") & ")"
        modMain.Save_Log LogPathname, sLog, True
        modMain.Save_Log_Video "ISO Image building operations have been completed."
        frmProgress.Update_Progress 5, False
    Else
        Err_Message = "Process aborted during ISO Image building operations."
        modMain.Save_Log_Video Err_Message & vbCrLf & vbCrLf & _
                               "For more info on current project check log file <" & OutputPath & "\" & DVDName & ".log>.", False, True
        modMain.Save_Log LogPathname, Err_Message, True
    End If
    ISOBuildingOps = Not CBool(Len(Err_Message))

End Function


' DVD burning operations Core
Private Function DVDBurningOps() As Boolean

    modMain.Save_Log_Video "DVD burning operations started."
    frmProgress.Update_Progress 6, True
    Err_Message = ""
    sCL = "/mode isobuild /buildmode device /src """ & OutputPath & "\" & DVDName & "\VIDEO_TS""" & " /dest " & Left(Preferences.DVDBurningDrive, 2) & " /volumelabel """ & DVD_Label & """ /speed " & Preferences.DVDBurningSpeed & " " & IIf(Preferences.DVDAutoErase = True, "/erase", "") & " /filesystem ""ISO9660 + UDF"" /udfrevision ""1.02"" /testmode no /verify no /noimagedetails /start /waitformedia /close /log """ & TempPath & "\" & DVDName & "_ImgBurn.log"""
    sLog = "START DVD BURNING OPERATIONS" & vbCrLf & "ImgBurn (DVD) Parameters: " & sCL
    modMain.Save_Log LogPathname, sLog, True
    modShellEx.Execute PathNames.ImgBurn, sCL, SW_DEFAULT, True
    ' Read ImgBurn log
    NumFile = FreeFile
    bFlag = False
    Str = ""
    sLog = ""
    Open TempPath & "\" & DVDName & "_ImgBurn.log" For Input As #NumFile
    Do Until EOF(NumFile) = True
        Line Input #NumFile, Str
        If InStr(1, Str, "Operation Started!") <> 0 Then
            bFlag = True
            Exit Do
        End If
    Loop
    If bFlag = True Then
        bFlag = False
        Do Until EOF(NumFile) = True
            Line Input #NumFile, Str
            If InStr(1, Str, "Operation Successfully Completed!") <> 0 Then
                bFlag = True
            End If
            If InStr(1, Str, "Average Write Rate:") <> 0 Then
                sLog = "A" & modStr.StrTrimRight(Str, "A")
            End If
        Loop
    End If
    Close #NumFile
    If bFlag = True Then
        modMain.Save_Log_Video "DVD burning operations have been completed."
        frmProgress.Update_Progress 6, False
        sLog = "END DVD BURNING OPERATIONS" & vbCrLf & _
               "Created DVD: '" & DVD_Label & "' in drive " & Preferences.DVDBurningDrive & vbCrLf & _
               sLog
    Else
        sLog = "Process aborted during DVD BURNING operations." & vbCrLf & vbCrLf & _
               "For more info on current project check log file <" & OutputPath & "\" & DVDName & ".log>."
        modMain.Save_Log_Video sLog, False, True
    End If
    modMain.Save_Log LogPathname, sLog, True
    
    DVDBurningOps = bFlag

End Function

