Attribute VB_Name = "modAVS"
' -------------------------------------------------------------------------------
'
'   AVStoDVD - by MrC
'   File: modAVS.bas
'   Purpose: Create AviSynth script
'   Requires: modFS.bas, modNum.bas
'
' -------------------------------------------------------------------------------


Option Explicit
Option Compare Binary
Option Base 0


Public Function Create_AVSScript(Title As TitleSettings, Optional AudioNum As Integer = 1) As String

    Dim X As Single
    Dim Y As Single
    Dim dX As Single
    Dim dY As Single
    Dim FPS As Single
    Dim sFPS As String
    Dim aFPS
    Dim InputDAR As Single
    Dim OutputDAR As Double
    Dim DVD_V As Integer
    Dim DVD_H As Integer
    Dim AVSAudioInput As String
    Dim Str As String
    Dim VideoStr As String
    Dim AudioStr As String
    Dim ResizeStr As String
    Dim ResizeStrLast As String
    Dim ResizeFilter As String
    Dim bFlag As Boolean
    Dim sPlugin As String
    Dim TrackNum As Integer
    Dim sInputSubsPathname As String
    Dim sAVS As String
    Dim bInterlaced As Boolean

    On Error GoTo Err_Handling
    
    With Title
        ' Initialize variables
        DVD_H = 352
        If .VideoResolution = Full_D1 Then DVD_H = 720
        FPS = 25
        DVD_V = 576
        If VideoStandard = NTSC Then
            FPS = 2997 / 100
            DVD_V = 480
        End If
        If .VideoResolution = VCD Then DVD_V = DVD_V / 2
        InputDAR = Val(.InputVideoInfo.DAR)
        If InputDAR = 0 Then InputDAR = 1
        If .VideoAspectRatio = Standard Then
            OutputDAR = 4 / 3
        Else
            OutputDAR = 16 / 9
        End If
        If Val(.InputVideoInfo.Height) / DVD_H * Val(.InputVideoInfo.Width) / DVD_V < 1 Then
            ResizeFilter = Preferences.AVSUpSize
        Else
            ResizeFilter = Preferences.AVSDownSize
        End If
        
        ' Set Video Source
        If .VideoIsToBeKept = True Then
            VideoStr = VideoStr & "# Video is frameserved by AviSynth just for Preview and Edit purposes." & vbCrLf
        End If
        Select Case .InputVideoInfo.Compression
        Case "AviSynth"
            VideoStr = VideoStr & "Video = Import(""" & .InputVideoPathName & """)" & vbCrLf
        Case "DGIndex"
            VideoStr = VideoStr & "Video = MPEG2Source(""" & .InputVideoPathName & """)" & vbCrLf
        Case Else
            aFPS = Split(modNum.GetFraction(.InputVideoInfo.FPS), "/")
            Select Case Preferences.AVSVideoInput
            Case "AVISource"
                VideoStr = VideoStr & "Video = AVISource(""" & .InputVideoPathName & """, audio=false)" & vbCrLf
            Case "DirectShowSource"
                VideoStr = VideoStr & "Video = DirectShowSource(""" & .InputVideoPathName & """, fps=" & .InputVideoInfo.FPS & ", "
                If .InputVideoInfo.FrameRateMode <> "CFR" Then
                    VideoStr = VideoStr & "convertfps=true, "
                End If
                VideoStr = VideoStr & "audio=false)" & vbCrLf
            Case "FFMpegSource"
                VideoStr = VideoStr & "Video = FFVideoSource(""" & .InputVideoPathName & """, track=-1"
                If .InputVideoInfo.FrameRateMode <> "CFR" Then
                    VideoStr = VideoStr & ", fpsnum=" & aFPS(0) & ", fpsden=" & aFPS(1)
                End If
                VideoStr = VideoStr & ", seekmode=0)" & vbCrLf
            Case Else
                VideoStr = VideoStr & "Video = A2DVideoSource(""" & .InputVideoPathName & """, CacheFolder=""" & Preferences.TempPath & """"
                Select Case .InputVideoInfo.FrameRateMode
                Case "VFR"
                    VideoStr = VideoStr & ", VFR=true"
                Case "CFR"
                    VideoStr = VideoStr & ", VFR=false"
                Case Else
                    ' none, A2DSource.avsi will assume it VFR (safer for DSS)
                End Select
                VideoStr = VideoStr & ", FrameRateNum=" & aFPS(0) & ", FrameRateDen=" & aFPS(1) & ", FrameRate=" & .InputVideoInfo.FPS & ")" & vbCrLf
            End Select
        End Select
        
        ' Set Audio Source
        If .InputAudioPathName(AudioNum) <> "" Then     'And .AudioIsToBeKept = False
            bFlag = False
            If .AudioIsToBeKept(AudioNum) = True Then bFlag = True
            If Preferences.AC3AudioEncoder = FFmpeg_Safe And .AudioFormat(AudioNum) = AC3 Then bFlag = True
            If Preferences.ForceFFmpeg4GB And .TimeTrimmed > 7200 Then
                Select Case .AudioChannelsMode(AudioNum)
                Case "5.0", "5.1"
                    bFlag = True
                End Select
            End If
            If bFlag = True Then
                AudioStr = AudioStr & "# Audio is frameserved by AviSynth just for Preview and Edit purposes." & vbCrLf
            End If
            If .InputAudioInfo(AudioNum).Compression <> "AviSynth" Then
                AVSAudioInput = Preferences.AVSAudioInput
                TrackNum = Val(.InputAudioInfo(AudioNum).StreamOrder)
                If TrackNum > 1 Then
                    AVSAudioInput = "FFAudioSource (forced)"
                    AudioStr = AudioStr & "# Forced 'FFAudioSource' to encode secondary Audio Tracks" & vbCrLf
                ElseIf LAVFilters.PathName <> "" And .AudioChannelsMode(AudioNum) = "5.0" Then
                    AVSAudioInput = "FFAudioSource (forced)"
                    AudioStr = AudioStr & "# Forced 'FFAudioSource' as workaround for LAV Filters not supporting 5.0 output in DirectShow mode" & vbCrLf
                End If
                If .InputAudioInfo(AudioNum).Compression = "AC3" And AVSAudioInput = "AVISource" Then
                    AVSAudioInput = "DirectShowSource"
                    AudioStr = AudioStr & "# 'AVISource' replaced with 'DirectShowSource' for AC3 audio support" & vbCrLf
                End If
                If Val(.InputGeneralInfo.AudioTracksCount) > 1 Then
                    Str = CStr(TrackNum)
                Else
                    Str = "-1"
                End If
                Select Case AVSAudioInput
                Case "AVISource"
                    AudioStr = AudioStr & "Audio = AVISource(""" & .InputAudioPathName(AudioNum) & """)" & vbCrLf
                Case "DirectShowSource"
                    AudioStr = AudioStr & "Audio = DirectShowSource(""" & .InputAudioPathName(AudioNum) & """, video=false)" & vbCrLf
                Case "FFMpegSource"
                    AudioStr = AudioStr & "Audio = FFAudioSource(""" & .InputAudioPathName(AudioNum) & """, track=" & Str & ")" & vbCrLf
                Case "FFAudioSource (forced)"
                    Randomize
                    AudioStr = AudioStr & "Audio = FFAudioSource(""" & .InputAudioPathName(AudioNum) & """, track=" & Str & ", cachefile=""" & Preferences.TempPath & "\A2DFFA_"" + String(Rand()) + "".cache""" & ")" & vbCrLf
                Case Else
                    AudioStr = AudioStr & "Audio = A2DAudioSource(""" & .InputAudioPathName(AudioNum) & """, CacheFolder=""" & Preferences.TempPath & """)" & vbCrLf
                End Select
            Else
                AudioStr = AudioStr & "Audio = Import(""" & .InputAudioPathName(AudioNum) & """)" & vbCrLf
            End If
        End If
                
        ' Write Video and Audio Sources
        sAVS = VideoStr & AudioStr & vbCrLf
        If Preferences.AVSAudioInput = "FFMpegSource" Or Preferences.AVSVideoInput = "FFMpegSource" Then
            sAVS = AudioStr & VideoStr & vbCrLf
        End If
        
        'VIDEO EDIT SECTION
        
        ' Define if source is to be considered interlaced
        bInterlaced = .InputVideoInfo.Interlaced
        If .AVSIVTC = True Then
            ' Apply Inverse Video Telecine routine
            bInterlaced = False
            sAVS = sAVS & "Video = Video.TFM.TDecimate" & vbCrLf
        End If
        
        ' Color Space/Matrix conversion
        If .AVSColorMatrix = True Then
            Str = "ColorMatrix(source=" & .AVS.ColorMatrixSource & ",dest=" & .AVS.ColorMatrixDest
            If bInterlaced = True Then
                sAVS = sAVS & "Video = Video.AssumeFrameBased()." & Str & ",interlaced=true)" & vbCrLf
            Else
                sAVS = sAVS & "Video = Video." & Str & ")" & vbCrLf
            End If
        End If
        sAVS = sAVS & "Video = Video.ConvertToYV12("
        If bInterlaced = True Then
            sAVS = sAVS & "interlaced=true"     'http://forum.doom9.org/showthread.php?p=1588645#post1588645
        End If
        sAVS = sAVS & ")" & vbCrLf
        
        ' Add DeBlock
        If .AVSDeBlock = True Then
            Str = ""
            dY = 0
            dX = 0
            With .InputVideoInfo
                If modNum.IsMultipleN(Int(Val(.Height)), 8) = False Then
                    dY = (Val(.Height) / 8 - Int(Val(.Height) / 8)) * 4
                    'sAVS = sAVS & "Video = Video.AddBorders(0," & dY & ",0," & dY & ")" & vbCrLf
                End If
                If modNum.IsMultipleN(Int(Val(.Width)), 8) = False Then
                    dX = (Val(.Width) / 8 - Int(Val(.Width) / 8)) * 4
                    'sAVS = sAVS & "Video = Video.AddBorders(" & dX & ",0," & dX & ",0)" & vbCrLf
                End If
                If dX <> 0 Or dY <> 0 Then
                    Str = "AddBorders(" & dX & "," & dY & "," & dX & "," & dY & ")."
                End If
            End With
            If bInterlaced = True Then
                Str = Str & "DeBlock_Int"
            Else
                Str = Str & "Deblock"
            End If
            Str = Str & "(" & .AVS.DeBlock & ")"
            If dX <> 0 Or dY <> 0 Then
                Str = Str & ".Crop(" & dX & "," & dY & "," & -dX & "," & -dY & ")"
            End If
            sAVS = sAVS & "Video = Video." & Str & vbCrLf
        End If
        
        ' Add deinterlace
        If .AVSDeInterlace = True Then
            sAVS = sAVS & "Video = Video.LeakKernelDeint(" & IIf(.VideoFieldOrder = "BFF", "0", "1") & "," & .AVS.DeIntThreshold & ",false,false)" & vbCrLf
        End If
        
        ' Adjust Video Aspect -> generate ResizeStr temp script
        ResizeStr = ""
        ResizeStrLast = "Video = Video." & ResizeFilter & "(" & DVD_H & "," & DVD_V & IIf(ResizeFilter = "BicubicResize", ",0,0.5", "") & ")"
        X = Val(.InputVideoInfo.Width)
        If X = 0 Then X = DVD_H
        Y = Round(X / InputDAR * IIf(.AVSVerticalResize = False, 100, Val(.AVS.VResize)) / 100, 0)
        If .AVSCrop = True Then
            ResizeStr = "Video = Video.Crop(" & .AVS.CropSx & "," & .AVS.CropUp & "," & -.AVS.CropDx & "," & -.AVS.CropDo & ")" & vbCrLf
            X = X - .AVS.CropSx - .AVS.CropDx
            Y = Y - .AVS.CropUp - .AVS.CropDo
        End If
        Select Case X / OutputDAR
        Case Is > Y
            ' Add top and bottom letterboxes
            dY = Round((X / OutputDAR - Y) / 2 * Val(.InputVideoInfo.PAR))
            If dY > 1 Then
                ResizeStr = ResizeStr & "Video = Video.AddBorders(0," & dY + CInt(IsOdd(dY)) & ",0," & dY - CInt(IsOdd(dY)) & ")" & vbCrLf
            End If
            ResizeStr = ResizeStr & ResizeStrLast
        Case Is < Y
            If Preferences.FrameAdjust = CropTopBottom Then
                ' Crop top and bottom letterboxes
                'If .AVSCrop = False Then
                    dY = Round((Y - X / OutputDAR) / 2)
                    dY = IIf(IsEven((dY)) = True, dY, dY - 1)
                    ResizeStr = ResizeStr & "Video = Video." & ResizeFilter & "(" & DVD_H & "," & DVD_V & IIf(ResizeFilter = "BicubicResize", ",0,0.5", "") & ",0," & dY & ",0,-" & dY & ")"
                'Else
                '    ResizeStr = ResizeStr & ResizeStrLast
                'End If
            Else
                ' Add left and right letterboxes
                'If .InputVideoInfo.DVDCompliant = Not_Video_Compl Then
                    dX = Round((Y * OutputDAR - X) / 2)
                    If dX > 1 Then
                        ResizeStr = ResizeStr & "Video = Video.AddBorders(" & dX + CInt(IsOdd(dX)) & ",0," & dX - CInt(IsOdd(dX)) & ",0)" & vbCrLf
                    End If
                'End If
                ResizeStr = ResizeStr & ResizeStrLast
            End If
        Case Else
            If X <> DVD_H Or Val(.InputVideoInfo.Height) <> DVD_V Then
                ResizeStr = ResizeStr & ResizeStrLast
            End If
        End Select
        If dX = 0 And dY = 0 And DVD_V = Val(.InputVideoInfo.Height) And DVD_H = Val(.InputVideoInfo.Width) And .AVSCrop = False Then
            ResizeStr = ""
        End If
        
        ' Bob interlaced clip before editing, if necessary
        If bInterlaced = True And .AVSDeInterlace = False Then
            If ResizeStr <> "" Or Val(.InputVideoInfo.FPS) <> FPS Then
                sAVS = sAVS & "Video = Video.LeakKernelBob(" & IIf(.VideoFieldOrder = "BFF", "0", "1") & ",7,false,false)" & vbCrLf
            End If
        End If
        
        ' Denoise
        If .AVSHQDN3D = True Then
            sAVS = sAVS & "Video = Video.hqdn3d(" & .AVS.HQDN3DStrength & ")" & vbCrLf
        End If
        
        ' Resize
        If ResizeStr <> "" Then
            sAVS = sAVS & ResizeStr & vbCrLf
        End If
        
        ' Sharpen
        If .AVSSharpen = True Then
            sAVS = sAVS & "Video = Video.Sharpen(" & Replace(.AVS.Sharpness, ",", ".") & ",MMX=false)" & vbCrLf
        End If
        If .AVSMSharpen = True Then
            sAVS = sAVS & "Video = Video.MSharpen(" & .AVS.MSharpenThreshold & "," & .AVS.MSharpenStrength & ")" & vbCrLf
        End If
        
        ' Adjust FPS
        Str = ""
        If FPS <> Val(.InputVideoInfo.FPS) Then
            If InStr(1, sAVS, "LeakKernelBob(") <> 0 Then
                If VideoStandard = PAL Then
                    sFPS = "50"
                Else
                    sFPS = "59.94"
                End If
            Else
                If VideoStandard = PAL Then
                    sFPS = "25"
                Else
                    sFPS = "29.97"
                End If
            End If
            Select Case .VideoFPSAdjust
            Case NoConversion
                '
            Case SelectEven
                Str = "Video = Video.SelectEven()" & vbCrLf
            Case PullDown
                Str = "#PullDown: using DGPulldown/HCenc to upsize FPS" & vbCrLf
            Case PALSpeedUp
                Str = "#PALSpeedUp: using AssumeFPS() to upsize FPS" & vbCrLf    'see below
            Case NTSCSlowDown
                Str = "#NTSCSlowDown: using AssumeFPS() to downsize FPS to 23.976 and then DGPulldown to upsize to 29.97" & vbCrLf    'see below
            Case Else
                Select Case Preferences.FPSHardConversion
                Case MotionProtectedFPS
                    Str = "MotionProtectedFPS"
                Case ChangeFPS
                    Str = "ChangeFPS"
                Case ConvertFPS
                    Str = "ConvertFPS"
                End Select
                Str = "Video = Video." & Str & "(" & sFPS & ")" & vbCrLf
            End Select
            sAVS = sAVS & Str
        End If
        
        ' Weave after video editing
        If InStr(1, sAVS, "LeakKernelBob(") <> 0 Then
            sAVS = sAVS & "Video = Video.SeparateFields().SelectEvery(4," & IIf(.VideoFieldOrder = "BFF", "0,3", "1,2") & ").Weave()" & vbCrLf
        End If
    
        ' Tweak Colors
        If .AVSTweak = True Then
            sAVS = sAVS & "Video = Video.Tweak(" & Replace(.AVS.Hue, ",", ".") & "," & _
                                                   Replace(.AVS.Saturation, ",", ".") & "," & _
                                                   Replace(.AVS.Brightness, ",", ".") & "," & _
                                                   Replace(.AVS.Contrast, ",", ".") & ")" & vbCrLf
        End If
        
        ' Insert subs
        If .InputSubsPathName(1) <> "" And .SubsHardEncode(1) = True Then
            Str = ""
            Select Case UCase(modFS.ExtOf(.InputSubsPathName(1)))
            Case "SRT", "SSA", "ASS", "TXT", "SUB"
                Str = "Video = Video.TextSub("
            Case "IDX"
                Str = "Video = Video.VobSub("
            End Select
            If Str <> "" Then
                sAVS = sAVS & Str
                Str = ""
                Str = modExtSW.Build_TextSub_Style(Title)
                If Str <> "" Then
                    sInputSubsPathname = modStr.RemoveStr(Str, ".style")
                End If
                If sInputSubsPathname = "" Then
                    sInputSubsPathname = .InputSubsPathName(1)
                End If
                sAVS = sAVS & """" & sInputSubsPathname & """)" & vbCrLf
                If Str <> "" Then sAVS = sAVS & "# Built TextSub .style file in: '" & modFS.PathOf(Str, False) & "'" & vbCrLf
            End If
        End If

        sAVS = sAVS & vbCrLf


        'AUDIO EDIT SECTION
        
        If .InputAudioPathName(AudioNum) <> "" And .AudioIsToBeKept(AudioNum) = False Then
            ' Adjust Audio settings
            With .InputAudioInfo(AudioNum)
                ' Handle MP3 VBR
                If Left(.Compression, 2) & Right(.Compression, 1) = "MP3" And .BitRateMode = "VBR" Then
                    sAVS = sAVS & "Audio = Audio.EnsureVBRMP3Sync()" & vbCrLf
                End If
                ' Adjust SampleRate
                bFlag = False
                If Val(.SampleRate) <> 48000 Then bFlag = True
            End With
            If .InputVideoPathName = .InputAudioPathName(AudioNum) And .InputVideoInfo.Compression = "DV" Then bFlag = True
            If bFlag = True Then
                sAVS = sAVS & "Audio = Audio.SSRC(48000)" & vbCrLf
            End If
            ' Normalize
            If .AudioNormalize(AudioNum) = True Then
                Str = Replace(Preferences.AudioNormalizeVal, ",", ".")
                If Val(Str) = 1 Then Str = ""
                sAVS = sAVS & "Audio = Audio.Normalize(" & Str & ")" & vbCrLf
            End If
            ' Downmix if necessary
            Select Case .AudioChannelsMode(AudioNum)
            Case "1.0"
                sAVS = sAVS & "Audio = Audio.ConvertToMono()" & vbCrLf
            Case "2.0"
                Select Case Val(.InputAudioInfo(AudioNum).Channels)
                Case 1
                    sAVS = sAVS & "Audio = Audio.UmixMonoStereo()" & vbCrLf
                Case 5, 6
                    'Select Case AVSAudioInput
                    'Case "FFMpegSource", "FFAudioSource (forced)"
                        sAVS = sAVS & "Audio = Audio.Dmix" & .InputAudioInfo(AudioNum).Channels & "Stereo()" & vbCrLf
                    'End Select
                End Select
            Case "5.0"
                Select Case .InputAudioInfo(AudioNum).Channels
                Case "2"
                    sAVS = sAVS & "Audio = Audio.UmixStereoPseudo5("
                    If .AudioNormalize(AudioNum) = True Then
                        sAVS = sAVS & "NormalizeSurround=true"
                    End If
                    sAVS = sAVS & ")" & vbCrLf
                Case "6"
                    'Select Case AVSAudioInput
                    'Case "FFMpegSource", "FFAudioSource (forced)"
                        sAVS = sAVS & "Audio = Audio.Dmix65()" & vbCrLf
                    'End Select
                End Select
            Case "5.1"
                Select Case .InputAudioInfo(AudioNum).Channels
                Case "2"
                    sAVS = sAVS & "Audio = Audio.UmixStereoPseudo6("
                    If .AudioNormalize(AudioNum) = True Then
                        sAVS = sAVS & "NormalizeSurround=true"
                    End If
                    sAVS = sAVS & ")" & vbCrLf
                End Select
            End Select
            ' Auto Delay
            Str = .InputAudioInfo(AudioNum).Delay
            If .AudioDelayAuto(AudioNum) = True And Val(Str) <> 0 Then
                sAVS = sAVS & "Audio = Audio.DelayAudio(" & Replace(Round(Val(Str) / 1000, 3), ",", ".") & ")" & vbCrLf
            End If
            ' Apply AviSynth filters from AVS variables (audio)
            If .AVSDelayAudio = True Then
                sAVS = sAVS & "Audio = Audio.DelayAudio(" & Replace(.AVS.AudioDelay, ",", ".") & ")" & vbCrLf
            End If
            If .AVSAmplifyAudio = True Then
                sAVS = sAVS & "Audio = Audio.AmplifyDB(" & Replace(.AVS.AudioAmplify, ",", ".") & ")" & vbCrLf
            End If
            If InStr(1, sAVS, "Audio = Audio.") <> 0 Then
                sAVS = sAVS & vbCrLf
            End If
        End If
        
        
        ' FINAL SECTION
        
        ' Mux Video and Audio or Return Video Only + SpeedUp/SlowDown (if any)
        bFlag = False
        If .VideoFPSAdjust = PALSpeedUp Or .VideoFPSAdjust = NTSCSlowDown Then
            bFlag = True
        End If
        If InStr(1, sAVS, "Video =") <> 0 And InStr(1, sAVS, "Audio =") <> 0 Then
            sAVS = sAVS & "AudioDub(Video, Audio)" & vbCrLf
            If bFlag = True Then
                sAVS = modStr.RemoveStr(sAVS, "Audio = Audio.SSRC(48000)" & vbCrLf & vbCrLf)
                sAVS = modStr.RemoveStr(sAVS, "Audio = Audio.SSRC(48000)" & vbCrLf)
                If FPS = 25 Then
                    sAVS = sAVS & "AssumeFPS(""pal_film"", sync_audio=true)"
                    Select Case .InputAudioInfo(AudioNum).SampleRate
                    Case "48000"
                        sAVS = sAVS & ".SSRC(48000)" & vbCrLf
                    Case Else  'SSRC does not accept all input samplerates
                        sAVS = sAVS & ".ResampleAudio(48000)" & vbCrLf
                    End Select
                Else
                    sAVS = sAVS & "AssumeFPS(""ntsc_film"", sync_audio=true).ResampleAudio(48000)" & vbCrLf
                End If
            End If
        Else
            If bFlag = True Then
                If FPS = 25 Then
                    sAVS = sAVS & "Video = Video.AssumeFPS(""pal_film"")" & vbCrLf
                Else
                    sAVS = sAVS & "Video = Video.AssumeFPS(""ntsc_film"")" & vbCrLf
                End If
            End If
            sAVS = sAVS & "Return Video" & vbCrLf
        End If
        sAVS = sAVS & vbCrLf
        
        ' Apply AviSynth filters from AVS variables (general)
        Str = ""
        If .AVSTrim = True Then
            Str = "Trim(" & .AVS.FrameStart & "," & .AVS.FrameEnd & ")"
            If InStr(1, sAVS, "Return Video" & vbCrLf) <> 0 Then
                sAVS = Replace(sAVS, "Return Video" & vbCrLf, "Return Video." & Str & vbCrLf)
            Else
                sAVS = sAVS & Str & vbCrLf
            End If
        End If
        If .AVSFadeIO = True Then
            Str = "FadeIO(" & .AVS.FadeIOFrames & ")"
            If InStr(1, sAVS, "Return Video" & vbCrLf) <> 0 Then
                sAVS = Replace(sAVS, "Return Video" & vbCrLf, "Return Video." & Str & vbCrLf)
            Else
                sAVS = sAVS & Str & vbCrLf
            End If
        End If
        If .AVSInfo = True Then
            Str = "Info()"
            If InStr(1, sAVS, "Return Video" & vbCrLf) <> 0 Then
                sAVS = Replace(sAVS, "Return Video" & vbCrLf, "Return Video." & Str & vbCrLf)
            Else
                sAVS = sAVS & Str & vbCrLf
            End If
        End If
        
    End With

    ' Append on top the Plugin calls
    If InStr(1, sAVS, "A2DVideoSource(") <> 0 Or InStr(1, sAVS, "A2DAudioSource(") <> 0 Then
        sPlugin = sPlugin & "Import(""" & App.Path & "\Lib\A2DSource.avsi""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "FFVideoSource(") <> 0 Or InStr(1, sAVS, "FFAudioSource(") <> 0 Then
        sPlugin = sPlugin & "LoadCPlugin(""" & App.Path & "\Lib\ffms2.dll""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "MPEG2Source(") <> 0 Or InStr(1, sAVS, "Deblock(") <> 0 Then
        sPlugin = sPlugin & "LoadPlugin(""" & App.Path & "\DGIndex\DGDecode.dll""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "DeBlock_Int(") <> 0 Then
        sPlugin = sPlugin & "Import(""" & App.Path & "\Lib\DeBlock_Int.avsi""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "TextSub(") <> 0 Or InStr(1, sAVS, "VobSub(") <> 0 Then
        sPlugin = sPlugin & "LoadPlugin(""" & App.Path & "\VobSub\VSFilter.dll""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "LeakKernelBob(") <> 0 Or InStr(1, sAVS, "LeakKernelDeint(") <> 0 Then
        sPlugin = sPlugin & "LoadPlugin(""" & App.Path & "\Lib\LeakKernelDeint.dll""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "ColorMatrix(") <> 0 Then
        sPlugin = sPlugin & "LoadPlugin(""" & App.Path & "\Lib\ColorMatrix.dll""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "MSharpen(") <> 0 Then
        sPlugin = sPlugin & "LoadPlugin(""" & App.Path & "\Lib\MSharpen.dll""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "hqdn3d(") <> 0 Then
        sPlugin = sPlugin & "LoadPlugin(""" & App.Path & "\Lib\hqdn3d.dll""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, ".TDecimate") <> 0 Then
        sPlugin = sPlugin & "LoadPlugin(""" & App.Path & "\Lib\TIVTC.dll""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "Dmix6") <> 0 Then
        sPlugin = sPlugin & "Import(""" & App.Path & "\Lib\Downmix.avsi""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "Dmix5") <> 0 Then
        sPlugin = sPlugin & "Import(""" & App.Path & "\Lib\Downmix.avsi""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "UmixStereo") <> 0 Then
        sPlugin = sPlugin & "Import(""" & App.Path & "\Lib\Upmix.avsi""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "UmixMono") <> 0 Then
        sPlugin = sPlugin & "Import(""" & App.Path & "\Lib\Upmix.avsi""" & ")" & vbCrLf
    End If
    If InStr(1, sAVS, "MotionProtectedFPS(") <> 0 Then
        sPlugin = sPlugin & "Import(""" & App.Path & "\Lib\MotionProtectedFPS.avsi""" & ")" & vbCrLf
    End If
    If sPlugin <> "" Then sAVS = sPlugin & vbCrLf & sAVS
    
    ' Remove junk stuff
    sAVS = Replace(sAVS, "Video = Video." & ResizeFilter & "(720,576,0,0,0,-0)", "Video = Video." & ResizeFilter & "(720,576)")
    sAVS = modStr.RemoveStr(sAVS, "Video = Video.AddBorders(0,0,0,0)" & vbCrLf)
    'If InStr(1, sAVS, "Video.LeakKernel") = 0 Then
    '    sAVS = modStr.RemoveStr(sAVS, "LoadPlugin(""" & App.Path & "\Lib\LeakKernelDeint.dll""" & ")" & vbCrLf)
    'End If
    Create_AVSScript = modStr.RemoveCharBegEnd(sAVS, Chr(10), Chr(13))
    
    Exit Function

Err_Handling:
Select Case Err.Number
Case 9999
    Resume
Case Else
    Create_AVSScript = ""
End Select

End Function
