Imports System.Diagnostics
Imports System.Text.RegularExpressions
Imports System.Threading
Imports System.Globalization
Imports System.Resources
Imports System.Reflection
Imports System.ComponentModel
Imports System.Text
Imports System.Drawing.Design

Imports Microsoft.Win32

Imports Stax
Imports Stax.UI
Imports Stax.DynamicObject
Imports Stax.Win32
Imports Stax.ComponentModel
Imports Stax.AppFramework

Public Class MainForm
    Inherits ExtendedForm

#Region " Designer "
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    Private components As System.ComponentModel.IContainer

    Public WithEvents tbAudioFile0 As System.Windows.Forms.TextBox
    Public WithEvents tbAudioFile1 As System.Windows.Forms.TextBox
    Friend WithEvents lbTrack1Source As System.Windows.Forms.Label
    Friend WithEvents lbTrack0Source As System.Windows.Forms.Label
    Public WithEvents bNext As System.Windows.Forms.Button
    Public WithEvents bOpenSourceFile As Button
    Public WithEvents bTargetPath As System.Windows.Forms.Button
    Public WithEvents tbSource As System.Windows.Forms.TextBox
    Public WithEvents tbTargetPath As System.Windows.Forms.TextBox
    Public WithEvents gbAssistant As System.Windows.Forms.GroupBox
    Friend WithEvents gbAviSynth As System.Windows.Forms.GroupBox
    Friend WithEvents bSize As BorderlessButton
    Friend WithEvents lbTargetLength As System.Windows.Forms.Label
    Friend WithEvents tbSize As System.Windows.Forms.TextBox
    Public WithEvents lAudioBitrate As System.Windows.Forms.Label
    Public WithEvents lAudioBitrateTitle As System.Windows.Forms.Label
    Friend WithEvents lSize As System.Windows.Forms.Label
    Friend WithEvents lBitrate As System.Windows.Forms.Label
    Friend WithEvents tbBitrate As System.Windows.Forms.TextBox
    Friend WithEvents lbLength As System.Windows.Forms.Label
    Public WithEvents cb169 As System.Windows.Forms.CheckBox
    Friend WithEvents lbSourceLength As System.Windows.Forms.Label
    Friend WithEvents lbSourceLengthText As System.Windows.Forms.Label
    Friend WithEvents lSourceFramerate As System.Windows.Forms.Label
    Friend WithEvents lSourceRateLabel As System.Windows.Forms.Label
    Friend WithEvents gbResize As System.Windows.Forms.GroupBox
    Friend WithEvents lPixelValue As System.Windows.Forms.Label
    Friend WithEvents lPixel As System.Windows.Forms.Label
    Friend WithEvents tbResize As System.Windows.Forms.TrackBar
    Friend WithEvents lZoom As System.Windows.Forms.Label
    Friend WithEvents lZoomLabel As System.Windows.Forms.Label
    Public WithEvents tbTargetHeight As System.Windows.Forms.TextBox
    Public WithEvents tbTargetWidth As System.Windows.Forms.TextBox
    Friend WithEvents lbTargetHeight As System.Windows.Forms.Label
    Friend WithEvents lbTargetWidth As System.Windows.Forms.Label
    Friend WithEvents lARUsedValue As System.Windows.Forms.Label
    Friend WithEvents lARUsed1 As System.Windows.Forms.Label
    Public WithEvents lCrop As System.Windows.Forms.Label
    Friend WithEvents lbCropLabel As System.Windows.Forms.Label
    Friend WithEvents gbVarious As System.Windows.Forms.GroupBox
    Friend WithEvents lSourceImageSize As System.Windows.Forms.Label
    Friend WithEvents lSourceImageSizeLabel As System.Windows.Forms.Label
    Friend WithEvents gbTarget As System.Windows.Forms.GroupBox
    Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
    Friend WithEvents lTip As System.Windows.Forms.Label
    Friend WithEvents gbEncoder As System.Windows.Forms.GroupBox
    Friend WithEvents TipProvider As Stax.UI.TipProvider
    Public WithEvents lQualityValue As System.Windows.Forms.Label
    Public WithEvents lQuality As System.Windows.Forms.Label
    Public WithEvents lCompCheckValue As System.Windows.Forms.Label
    Friend WithEvents MenuStrip As System.Windows.Forms.MenuStrip
    Friend WithEvents cmsOpen As System.Windows.Forms.ContextMenuStrip
    Friend WithEvents OpenFilesToolStripMenuItem As ExtendedToolStripMenuItem
    Friend WithEvents OpenFileToolStripMenuItem As Stax.UI.ExtendedToolStripMenuItem
    Friend WithEvents lAudioProfile0 As System.Windows.Forms.Label
    Friend WithEvents lAudioProfile1 As System.Windows.Forms.Label
    Friend WithEvents SmartTagProvider As Stax.UI.Design.SmartTagProvider
    Friend WithEvents cmsFilters As System.Windows.Forms.ContextMenuStrip
    Friend WithEvents bAudioMenu0 As System.Windows.Forms.Button
    Friend WithEvents bAudioMenu1 As System.Windows.Forms.Button
    Friend WithEvents pEncoder As System.Windows.Forms.Panel
    Friend WithEvents AviSynthListView As StaxRip.AviSynthListView
    Public WithEvents lCompCheck As System.Windows.Forms.Label

    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(MainForm))
        Me.lbTrack0Source = New System.Windows.Forms.Label
        Me.tbAudioFile0 = New System.Windows.Forms.TextBox
        Me.tbAudioFile1 = New System.Windows.Forms.TextBox
        Me.gbAssistant = New System.Windows.Forms.GroupBox
        Me.lTip = New System.Windows.Forms.Label
        Me.bNext = New System.Windows.Forms.Button
        Me.tbSource = New System.Windows.Forms.TextBox
        Me.bTargetPath = New System.Windows.Forms.Button
        Me.bOpenSourceFile = New System.Windows.Forms.Button
        Me.cmsOpen = New System.Windows.Forms.ContextMenuStrip(Me.components)
        Me.OpenFileToolStripMenuItem = New Stax.UI.ExtendedToolStripMenuItem
        Me.OpenFilesToolStripMenuItem = New Stax.UI.ExtendedToolStripMenuItem
        Me.tbTargetPath = New System.Windows.Forms.TextBox
        Me.lbTrack1Source = New System.Windows.Forms.Label
        Me.gbEncoder = New System.Windows.Forms.GroupBox
        Me.pEncoder = New System.Windows.Forms.Panel
        Me.tbSize = New System.Windows.Forms.TextBox
        Me.lQualityValue = New System.Windows.Forms.Label
        Me.tbBitrate = New System.Windows.Forms.TextBox
        Me.lPixelValue = New System.Windows.Forms.Label
        Me.tbTargetHeight = New System.Windows.Forms.TextBox
        Me.tbTargetWidth = New System.Windows.Forms.TextBox
        Me.cmsFilters = New System.Windows.Forms.ContextMenuStrip(Me.components)
        Me.gbAviSynth = New System.Windows.Forms.GroupBox
        Me.AviSynthListView = New StaxRip.AviSynthListView
        Me.gbTarget = New System.Windows.Forms.GroupBox
        Me.bSize = New Stax.UI.BorderlessButton
        Me.lbTargetLength = New System.Windows.Forms.Label
        Me.lAudioBitrate = New System.Windows.Forms.Label
        Me.lAudioBitrateTitle = New System.Windows.Forms.Label
        Me.lQuality = New System.Windows.Forms.Label
        Me.lCompCheckValue = New System.Windows.Forms.Label
        Me.lCompCheck = New System.Windows.Forms.Label
        Me.lSize = New System.Windows.Forms.Label
        Me.lBitrate = New System.Windows.Forms.Label
        Me.lbLength = New System.Windows.Forms.Label
        Me.gbVarious = New System.Windows.Forms.GroupBox
        Me.lCrop = New System.Windows.Forms.Label
        Me.lbCropLabel = New System.Windows.Forms.Label
        Me.lSourceImageSize = New System.Windows.Forms.Label
        Me.lSourceImageSizeLabel = New System.Windows.Forms.Label
        Me.lbSourceLength = New System.Windows.Forms.Label
        Me.lbSourceLengthText = New System.Windows.Forms.Label
        Me.cb169 = New System.Windows.Forms.CheckBox
        Me.lSourceFramerate = New System.Windows.Forms.Label
        Me.lSourceRateLabel = New System.Windows.Forms.Label
        Me.gbResize = New System.Windows.Forms.GroupBox
        Me.lPixel = New System.Windows.Forms.Label
        Me.tbResize = New System.Windows.Forms.TrackBar
        Me.lZoom = New System.Windows.Forms.Label
        Me.lZoomLabel = New System.Windows.Forms.Label
        Me.lbTargetHeight = New System.Windows.Forms.Label
        Me.lbTargetWidth = New System.Windows.Forms.Label
        Me.lARUsedValue = New System.Windows.Forms.Label
        Me.lARUsed1 = New System.Windows.Forms.Label
        Me.GroupBox1 = New System.Windows.Forms.GroupBox
        Me.bAudioMenu1 = New System.Windows.Forms.Button
        Me.lAudioProfile1 = New System.Windows.Forms.Label
        Me.lAudioProfile0 = New System.Windows.Forms.Label
        Me.bAudioMenu0 = New System.Windows.Forms.Button
        Me.TipProvider = New Stax.UI.TipProvider(Me.components)
        Me.MenuStrip = New System.Windows.Forms.MenuStrip
        Me.SmartTagProvider = New Stax.UI.Design.SmartTagProvider
        Me.gbAssistant.SuspendLayout()
        Me.cmsOpen.SuspendLayout()
        Me.gbEncoder.SuspendLayout()
        Me.gbAviSynth.SuspendLayout()
        Me.gbTarget.SuspendLayout()
        Me.gbVarious.SuspendLayout()
        Me.gbResize.SuspendLayout()
        CType(Me.tbResize, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.GroupBox1.SuspendLayout()
        CType(Me.TipProvider, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'lbTrack0Source
        '
        Me.lbTrack0Source.AutoSize = True
        Me.lbTrack0Source.Location = New System.Drawing.Point(8, 21)
        Me.lbTrack0Source.Name = "lbTrack0Source"
        Me.lbTrack0Source.Size = New System.Drawing.Size(47, 13)
        Me.lbTrack0Source.TabIndex = 20
        Me.lbTrack0Source.Text = "Track 1:"
        '
        'tbAudioFile0
        '
        Me.tbAudioFile0.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.tbAudioFile0.Location = New System.Drawing.Point(57, 17)
        Me.tbAudioFile0.Name = "tbAudioFile0"
        Me.tbAudioFile0.Size = New System.Drawing.Size(415, 20)
        Me.tbAudioFile0.TabIndex = 13
        Me.TipProvider.SetTipText(Me.tbAudioFile0, "The audio source file used to mux or encode")
        '
        'tbAudioFile1
        '
        Me.tbAudioFile1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.tbAudioFile1.Location = New System.Drawing.Point(57, 43)
        Me.tbAudioFile1.Name = "tbAudioFile1"
        Me.tbAudioFile1.Size = New System.Drawing.Size(415, 20)
        Me.tbAudioFile1.TabIndex = 1
        Me.TipProvider.SetTipText(Me.tbAudioFile1, "The audio source file used to mux or encode")
        '
        'gbAssistant
        '
        Me.gbAssistant.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.gbAssistant.Controls.Add(Me.lTip)
        Me.gbAssistant.Controls.Add(Me.bNext)
        Me.gbAssistant.Location = New System.Drawing.Point(8, 395)
        Me.gbAssistant.Name = "gbAssistant"
        Me.gbAssistant.Size = New System.Drawing.Size(712, 56)
        Me.gbAssistant.TabIndex = 44
        Me.gbAssistant.TabStop = False
        Me.gbAssistant.Text = "Assistant"
        '
        'lTip
        '
        Me.lTip.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.lTip.Cursor = System.Windows.Forms.Cursors.Hand
        Me.lTip.ForeColor = System.Drawing.Color.Blue
        Me.lTip.Location = New System.Drawing.Point(16, 13)
        Me.lTip.Name = "lTip"
        Me.lTip.Size = New System.Drawing.Size(592, 40)
        Me.lTip.TabIndex = 40
        Me.lTip.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'bNext
        '
        Me.bNext.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.bNext.Cursor = System.Windows.Forms.Cursors.Default
        Me.bNext.Location = New System.Drawing.Point(624, 20)
        Me.bNext.Name = "bNext"
        Me.bNext.Size = New System.Drawing.Size(80, 24)
        Me.bNext.TabIndex = 39
        Me.bNext.Text = "Next"
        Me.TipProvider.SetTipText(Me.bNext, "Displays the next tip")
        '
        'tbSource
        '
        Me.tbSource.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.tbSource.Location = New System.Drawing.Point(8, 16)
        Me.tbSource.Name = "tbSource"
        Me.tbSource.Size = New System.Drawing.Size(304, 20)
        Me.tbSource.TabIndex = 38
        '
        'bTargetPath
        '
        Me.bTargetPath.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.bTargetPath.Location = New System.Drawing.Point(319, 14)
        Me.bTargetPath.Name = "bTargetPath"
        Me.bTargetPath.Size = New System.Drawing.Size(24, 24)
        Me.bTargetPath.TabIndex = 37
        Me.bTargetPath.Text = "..."
        '
        'bOpenSourceFile
        '
        Me.bOpenSourceFile.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.bOpenSourceFile.Location = New System.Drawing.Point(319, 14)
        Me.bOpenSourceFile.Name = "bOpenSourceFile"
        Me.bOpenSourceFile.Size = New System.Drawing.Size(24, 24)
        Me.bOpenSourceFile.TabIndex = 0
        '
        'cmsOpen
        '
        Me.cmsOpen.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.OpenFileToolStripMenuItem, Me.OpenFilesToolStripMenuItem})
        Me.cmsOpen.Name = "cmsOpen"
        Me.cmsOpen.ShowImageMargin = False
        Me.cmsOpen.Size = New System.Drawing.Size(123, 48)
        '
        'OpenFileToolStripMenuItem
        '
        Me.OpenFileToolStripMenuItem.GenericMenuItem = Nothing
        Me.OpenFileToolStripMenuItem.Name = "OpenFileToolStripMenuItem"
        Me.OpenFileToolStripMenuItem.Size = New System.Drawing.Size(122, 22)
        Me.OpenFileToolStripMenuItem.Text = "Open File..."
        Me.OpenFileToolStripMenuItem.TipTarget = Nothing
        '
        'OpenFilesToolStripMenuItem
        '
        Me.OpenFilesToolStripMenuItem.GenericMenuItem = Nothing
        Me.OpenFilesToolStripMenuItem.Name = "OpenFilesToolStripMenuItem"
        Me.OpenFilesToolStripMenuItem.Size = New System.Drawing.Size(122, 22)
        Me.OpenFilesToolStripMenuItem.Text = "Open Files..."
        Me.OpenFilesToolStripMenuItem.TipTarget = Nothing
        '
        'tbTargetPath
        '
        Me.tbTargetPath.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.tbTargetPath.Location = New System.Drawing.Point(8, 16)
        Me.tbTargetPath.Name = "tbTargetPath"
        Me.tbTargetPath.Size = New System.Drawing.Size(304, 20)
        Me.tbTargetPath.TabIndex = 35
        '
        'lbTrack1Source
        '
        Me.lbTrack1Source.AutoSize = True
        Me.lbTrack1Source.Location = New System.Drawing.Point(8, 46)
        Me.lbTrack1Source.Name = "lbTrack1Source"
        Me.lbTrack1Source.Size = New System.Drawing.Size(47, 13)
        Me.lbTrack1Source.TabIndex = 21
        Me.lbTrack1Source.Text = "Track 2:"
        '
        'gbEncoder
        '
        Me.gbEncoder.Controls.Add(Me.pEncoder)
        Me.gbEncoder.Location = New System.Drawing.Point(488, 155)
        Me.gbEncoder.Name = "gbEncoder"
        Me.gbEncoder.Size = New System.Drawing.Size(232, 152)
        Me.gbEncoder.TabIndex = 51
        Me.gbEncoder.TabStop = False
        Me.gbEncoder.Text = "Encoder"
        '
        'pEncoder
        '
        Me.pEncoder.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.pEncoder.Location = New System.Drawing.Point(6, 19)
        Me.pEncoder.Name = "pEncoder"
        Me.pEncoder.Size = New System.Drawing.Size(220, 127)
        Me.pEncoder.TabIndex = 0
        '
        'tbSize
        '
        Me.tbSize.Location = New System.Drawing.Point(48, 46)
        Me.tbSize.Name = "tbSize"
        Me.tbSize.Size = New System.Drawing.Size(40, 20)
        Me.tbSize.TabIndex = 55
        Me.tbSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
        Me.TipProvider.SetTipText(Me.tbSize, "Change the value with the page up/down key")
        '
        'lQualityValue
        '
        Me.lQualityValue.ImeMode = System.Windows.Forms.ImeMode.NoControl
        Me.lQualityValue.Location = New System.Drawing.Point(56, 96)
        Me.lQualityValue.Name = "lQualityValue"
        Me.lQualityValue.Size = New System.Drawing.Size(80, 16)
        Me.lQualityValue.TabIndex = 48
        Me.lQualityValue.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'tbBitrate
        '
        Me.tbBitrate.Location = New System.Drawing.Point(232, 46)
        Me.tbBitrate.Name = "tbBitrate"
        Me.tbBitrate.Size = New System.Drawing.Size(40, 20)
        Me.tbBitrate.TabIndex = 41
        Me.tbBitrate.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
        Me.TipProvider.SetTipText(Me.tbBitrate, "Change the value with the page up/down key")
        '
        'lPixelValue
        '
        Me.lPixelValue.Location = New System.Drawing.Point(48, 96)
        Me.lPixelValue.Name = "lPixelValue"
        Me.lPixelValue.Size = New System.Drawing.Size(48, 16)
        Me.lPixelValue.TabIndex = 50
        Me.lPixelValue.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        Me.TipProvider.SetTipText(Me.lPixelValue, "high resolution = high quality = high bitrate = large filesize")
        '
        'tbTargetHeight
        '
        Me.tbTargetHeight.Location = New System.Drawing.Point(152, 24)
        Me.tbTargetHeight.Name = "tbTargetHeight"
        Me.tbTargetHeight.Size = New System.Drawing.Size(40, 20)
        Me.tbTargetHeight.TabIndex = 40
        Me.tbTargetHeight.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
        Me.TipProvider.SetTipText(Me.tbTargetHeight, "Change the value with the page up/down key")
        '
        'tbTargetWidth
        '
        Me.tbTargetWidth.Location = New System.Drawing.Point(56, 24)
        Me.tbTargetWidth.Name = "tbTargetWidth"
        Me.tbTargetWidth.Size = New System.Drawing.Size(40, 20)
        Me.tbTargetWidth.TabIndex = 39
        Me.tbTargetWidth.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
        Me.TipProvider.SetTipText(Me.tbTargetWidth, "Change the value with the page up/down key")
        '
        'cmsFilters
        '
        Me.cmsFilters.Name = "cmsFilters"
        Me.cmsFilters.ShowImageMargin = False
        Me.cmsFilters.Size = New System.Drawing.Size(36, 4)
        '
        'gbAviSynth
        '
        Me.gbAviSynth.Controls.Add(Me.AviSynthListView)
        Me.gbAviSynth.Location = New System.Drawing.Point(8, 155)
        Me.gbAviSynth.Name = "gbAviSynth"
        Me.gbAviSynth.Size = New System.Drawing.Size(232, 152)
        Me.gbAviSynth.TabIndex = 53
        Me.gbAviSynth.TabStop = False
        Me.gbAviSynth.Text = "Filters"
        '
        'AviSynthListView
        '
        Me.AviSynthListView.AllowDrop = True
        Me.AviSynthListView.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.AviSynthListView.CheckBoxes = True
        Me.AviSynthListView.FullRowSelect = True
        Me.AviSynthListView.GetProfileMethod = Nothing
        Me.AviSynthListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None
        Me.AviSynthListView.HideSelection = False
        Me.AviSynthListView.Location = New System.Drawing.Point(6, 19)
        Me.AviSynthListView.MultiSelect = False
        Me.AviSynthListView.Name = "AviSynthListView"
        Me.AviSynthListView.Size = New System.Drawing.Size(220, 127)
        Me.AviSynthListView.TabIndex = 0
        Me.AviSynthListView.UseCompatibleStateImageBehavior = False
        Me.AviSynthListView.View = System.Windows.Forms.View.Details
        '
        'gbTarget
        '
        Me.gbTarget.Controls.Add(Me.bSize)
        Me.gbTarget.Controls.Add(Me.lbTargetLength)
        Me.gbTarget.Controls.Add(Me.tbSize)
        Me.gbTarget.Controls.Add(Me.lAudioBitrate)
        Me.gbTarget.Controls.Add(Me.lAudioBitrateTitle)
        Me.gbTarget.Controls.Add(Me.lQualityValue)
        Me.gbTarget.Controls.Add(Me.lQuality)
        Me.gbTarget.Controls.Add(Me.lCompCheckValue)
        Me.gbTarget.Controls.Add(Me.lCompCheck)
        Me.gbTarget.Controls.Add(Me.lSize)
        Me.gbTarget.Controls.Add(Me.lBitrate)
        Me.gbTarget.Controls.Add(Me.tbBitrate)
        Me.gbTarget.Controls.Add(Me.lbLength)
        Me.gbTarget.Controls.Add(Me.bTargetPath)
        Me.gbTarget.Controls.Add(Me.tbTargetPath)
        Me.gbTarget.Location = New System.Drawing.Point(368, 27)
        Me.gbTarget.Name = "gbTarget"
        Me.gbTarget.Size = New System.Drawing.Size(352, 120)
        Me.gbTarget.TabIndex = 58
        Me.gbTarget.TabStop = False
        Me.gbTarget.Text = "Target"
        '
        'bSize
        '
        Me.bSize.FlatStyle = System.Windows.Forms.FlatStyle.Popup
        Me.bSize.Location = New System.Drawing.Point(89, 46)
        Me.bSize.Name = "bSize"
        Me.bSize.Size = New System.Drawing.Size(17, 20)
        Me.bSize.TabIndex = 57
        Me.bSize.Text = ">"
        '
        'lbTargetLength
        '
        Me.lbTargetLength.Location = New System.Drawing.Point(56, 72)
        Me.lbTargetLength.Name = "lbTargetLength"
        Me.lbTargetLength.Size = New System.Drawing.Size(80, 16)
        Me.lbTargetLength.TabIndex = 56
        Me.lbTargetLength.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lAudioBitrate
        '
        Me.lAudioBitrate.ImeMode = System.Windows.Forms.ImeMode.NoControl
        Me.lAudioBitrate.Location = New System.Drawing.Point(232, 72)
        Me.lAudioBitrate.Name = "lAudioBitrate"
        Me.lAudioBitrate.Size = New System.Drawing.Size(112, 16)
        Me.lAudioBitrate.TabIndex = 52
        Me.lAudioBitrate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lAudioBitrateTitle
        '
        Me.lAudioBitrateTitle.ImeMode = System.Windows.Forms.ImeMode.NoControl
        Me.lAudioBitrateTitle.Location = New System.Drawing.Point(152, 72)
        Me.lAudioBitrateTitle.Name = "lAudioBitrateTitle"
        Me.lAudioBitrateTitle.Size = New System.Drawing.Size(70, 16)
        Me.lAudioBitrateTitle.TabIndex = 51
        Me.lAudioBitrateTitle.Text = "Audio Bitrate:"
        Me.lAudioBitrateTitle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lQuality
        '
        Me.lQuality.ImeMode = System.Windows.Forms.ImeMode.NoControl
        Me.lQuality.Location = New System.Drawing.Point(8, 96)
        Me.lQuality.Name = "lQuality"
        Me.lQuality.Size = New System.Drawing.Size(42, 16)
        Me.lQuality.TabIndex = 47
        Me.lQuality.Text = "Quality:"
        Me.lQuality.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lCompCheckValue
        '
        Me.lCompCheckValue.ImeMode = System.Windows.Forms.ImeMode.NoControl
        Me.lCompCheckValue.Location = New System.Drawing.Point(233, 96)
        Me.lCompCheckValue.Name = "lCompCheckValue"
        Me.lCompCheckValue.Size = New System.Drawing.Size(111, 16)
        Me.lCompCheckValue.TabIndex = 46
        Me.lCompCheckValue.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lCompCheck
        '
        Me.lCompCheck.ImeMode = System.Windows.Forms.ImeMode.NoControl
        Me.lCompCheck.Location = New System.Drawing.Point(152, 96)
        Me.lCompCheck.Name = "lCompCheck"
        Me.lCompCheck.Size = New System.Drawing.Size(78, 16)
        Me.lCompCheck.TabIndex = 45
        Me.lCompCheck.Text = "Compressibility:"
        Me.lCompCheck.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lSize
        '
        Me.lSize.Location = New System.Drawing.Point(8, 48)
        Me.lSize.Name = "lSize"
        Me.lSize.Size = New System.Drawing.Size(30, 16)
        Me.lSize.TabIndex = 43
        Me.lSize.Text = "Size:"
        Me.lSize.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lBitrate
        '
        Me.lBitrate.Location = New System.Drawing.Point(152, 48)
        Me.lBitrate.Name = "lBitrate"
        Me.lBitrate.Size = New System.Drawing.Size(70, 16)
        Me.lBitrate.TabIndex = 42
        Me.lBitrate.Text = "Video Bitrate:"
        Me.lBitrate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lbLength
        '
        Me.lbLength.Location = New System.Drawing.Point(8, 72)
        Me.lbLength.Name = "lbLength"
        Me.lbLength.Size = New System.Drawing.Size(43, 16)
        Me.lbLength.TabIndex = 39
        Me.lbLength.Text = "Length:"
        Me.lbLength.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'gbVarious
        '
        Me.gbVarious.Controls.Add(Me.lCrop)
        Me.gbVarious.Controls.Add(Me.lbCropLabel)
        Me.gbVarious.Controls.Add(Me.lSourceImageSize)
        Me.gbVarious.Controls.Add(Me.lSourceImageSizeLabel)
        Me.gbVarious.Controls.Add(Me.lbSourceLength)
        Me.gbVarious.Controls.Add(Me.lbSourceLengthText)
        Me.gbVarious.Controls.Add(Me.cb169)
        Me.gbVarious.Controls.Add(Me.lSourceFramerate)
        Me.gbVarious.Controls.Add(Me.lSourceRateLabel)
        Me.gbVarious.Controls.Add(Me.bOpenSourceFile)
        Me.gbVarious.Controls.Add(Me.tbSource)
        Me.gbVarious.Location = New System.Drawing.Point(8, 27)
        Me.gbVarious.Name = "gbVarious"
        Me.gbVarious.Size = New System.Drawing.Size(352, 120)
        Me.gbVarious.TabIndex = 57
        Me.gbVarious.TabStop = False
        Me.gbVarious.Text = "Source"
        '
        'lCrop
        '
        Me.lCrop.Location = New System.Drawing.Point(56, 96)
        Me.lCrop.Name = "lCrop"
        Me.lCrop.Size = New System.Drawing.Size(288, 16)
        Me.lCrop.TabIndex = 16
        Me.lCrop.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lbCropLabel
        '
        Me.lbCropLabel.Location = New System.Drawing.Point(8, 96)
        Me.lbCropLabel.Name = "lbCropLabel"
        Me.lbCropLabel.Size = New System.Drawing.Size(32, 16)
        Me.lbCropLabel.TabIndex = 14
        Me.lbCropLabel.Text = "Crop:"
        Me.lbCropLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lSourceImageSize
        '
        Me.lSourceImageSize.Location = New System.Drawing.Point(56, 72)
        Me.lSourceImageSize.Name = "lSourceImageSize"
        Me.lSourceImageSize.Size = New System.Drawing.Size(128, 16)
        Me.lSourceImageSize.TabIndex = 35
        Me.lSourceImageSize.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lSourceImageSizeLabel
        '
        Me.lSourceImageSizeLabel.Location = New System.Drawing.Point(8, 72)
        Me.lSourceImageSizeLabel.Name = "lSourceImageSizeLabel"
        Me.lSourceImageSizeLabel.Size = New System.Drawing.Size(30, 16)
        Me.lSourceImageSizeLabel.TabIndex = 33
        Me.lSourceImageSizeLabel.Text = "Size:"
        Me.lSourceImageSizeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lbSourceLength
        '
        Me.lbSourceLength.Location = New System.Drawing.Point(56, 48)
        Me.lbSourceLength.Name = "lbSourceLength"
        Me.lbSourceLength.Size = New System.Drawing.Size(72, 16)
        Me.lbSourceLength.TabIndex = 42
        Me.lbSourceLength.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lbSourceLengthText
        '
        Me.lbSourceLengthText.Location = New System.Drawing.Point(8, 48)
        Me.lbSourceLengthText.Name = "lbSourceLengthText"
        Me.lbSourceLengthText.Size = New System.Drawing.Size(43, 16)
        Me.lbSourceLengthText.TabIndex = 41
        Me.lbSourceLengthText.Text = "Length:"
        Me.lbSourceLengthText.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'cb169
        '
        Me.cb169.Location = New System.Drawing.Point(192, 72)
        Me.cb169.Name = "cb169"
        Me.cb169.Size = New System.Drawing.Size(152, 16)
        Me.cb169.TabIndex = 43
        Me.cb169.Text = "16:9"
        '
        'lSourceFramerate
        '
        Me.lSourceFramerate.Location = New System.Drawing.Point(256, 48)
        Me.lSourceFramerate.Name = "lSourceFramerate"
        Me.lSourceFramerate.Size = New System.Drawing.Size(88, 16)
        Me.lSourceFramerate.TabIndex = 40
        Me.lSourceFramerate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lSourceRateLabel
        '
        Me.lSourceRateLabel.Location = New System.Drawing.Point(189, 48)
        Me.lSourceRateLabel.Name = "lSourceRateLabel"
        Me.lSourceRateLabel.Size = New System.Drawing.Size(57, 16)
        Me.lSourceRateLabel.TabIndex = 39
        Me.lSourceRateLabel.Text = "Framerate:"
        Me.lSourceRateLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'gbResize
        '
        Me.gbResize.Controls.Add(Me.lPixelValue)
        Me.gbResize.Controls.Add(Me.lPixel)
        Me.gbResize.Controls.Add(Me.tbResize)
        Me.gbResize.Controls.Add(Me.lZoom)
        Me.gbResize.Controls.Add(Me.lZoomLabel)
        Me.gbResize.Controls.Add(Me.tbTargetHeight)
        Me.gbResize.Controls.Add(Me.tbTargetWidth)
        Me.gbResize.Controls.Add(Me.lbTargetHeight)
        Me.gbResize.Controls.Add(Me.lbTargetWidth)
        Me.gbResize.Controls.Add(Me.lARUsedValue)
        Me.gbResize.Controls.Add(Me.lARUsed1)
        Me.gbResize.Location = New System.Drawing.Point(248, 155)
        Me.gbResize.Name = "gbResize"
        Me.gbResize.Size = New System.Drawing.Size(232, 152)
        Me.gbResize.TabIndex = 55
        Me.gbResize.TabStop = False
        Me.gbResize.Text = "Resize"
        '
        'lPixel
        '
        Me.lPixel.Location = New System.Drawing.Point(8, 96)
        Me.lPixel.Name = "lPixel"
        Me.lPixel.Size = New System.Drawing.Size(40, 16)
        Me.lPixel.TabIndex = 49
        Me.lPixel.Text = "Pixel:"
        Me.lPixel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'tbResize
        '
        Me.tbResize.AutoSize = False
        Me.tbResize.BackColor = System.Drawing.SystemColors.Control
        Me.tbResize.Location = New System.Drawing.Point(8, 59)
        Me.tbResize.Name = "tbResize"
        Me.tbResize.Size = New System.Drawing.Size(216, 24)
        Me.tbResize.TabIndex = 46
        '
        'lZoom
        '
        Me.lZoom.Location = New System.Drawing.Point(144, 96)
        Me.lZoom.Name = "lZoom"
        Me.lZoom.Size = New System.Drawing.Size(80, 16)
        Me.lZoom.TabIndex = 44
        Me.lZoom.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lZoomLabel
        '
        Me.lZoomLabel.Location = New System.Drawing.Point(96, 96)
        Me.lZoomLabel.Name = "lZoomLabel"
        Me.lZoomLabel.Size = New System.Drawing.Size(48, 16)
        Me.lZoomLabel.TabIndex = 42
        Me.lZoomLabel.Text = "Zoom:"
        Me.lZoomLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lbTargetHeight
        '
        Me.lbTargetHeight.Location = New System.Drawing.Point(104, 26)
        Me.lbTargetHeight.Name = "lbTargetHeight"
        Me.lbTargetHeight.Size = New System.Drawing.Size(48, 16)
        Me.lbTargetHeight.TabIndex = 38
        Me.lbTargetHeight.Text = "Height:"
        Me.lbTargetHeight.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lbTargetWidth
        '
        Me.lbTargetWidth.Location = New System.Drawing.Point(8, 26)
        Me.lbTargetWidth.Name = "lbTargetWidth"
        Me.lbTargetWidth.Size = New System.Drawing.Size(48, 16)
        Me.lbTargetWidth.TabIndex = 37
        Me.lbTargetWidth.Text = "Width:"
        Me.lbTargetWidth.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lARUsedValue
        '
        Me.lARUsedValue.ImeMode = System.Windows.Forms.ImeMode.NoControl
        Me.lARUsedValue.Location = New System.Drawing.Point(88, 120)
        Me.lARUsedValue.Name = "lARUsedValue"
        Me.lARUsedValue.Size = New System.Drawing.Size(136, 16)
        Me.lARUsedValue.TabIndex = 24
        Me.lARUsedValue.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lARUsed1
        '
        Me.lARUsed1.ImeMode = System.Windows.Forms.ImeMode.NoControl
        Me.lARUsed1.Location = New System.Drawing.Point(8, 120)
        Me.lARUsed1.Name = "lARUsed1"
        Me.lARUsed1.Size = New System.Drawing.Size(80, 16)
        Me.lARUsed1.TabIndex = 23
        Me.lARUsed1.Text = "Aspect Ratio:"
        Me.lARUsed1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'GroupBox1
        '
        Me.GroupBox1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.GroupBox1.Controls.Add(Me.bAudioMenu1)
        Me.GroupBox1.Controls.Add(Me.lAudioProfile1)
        Me.GroupBox1.Controls.Add(Me.lAudioProfile0)
        Me.GroupBox1.Controls.Add(Me.lbTrack1Source)
        Me.GroupBox1.Controls.Add(Me.tbAudioFile0)
        Me.GroupBox1.Controls.Add(Me.bAudioMenu0)
        Me.GroupBox1.Controls.Add(Me.tbAudioFile1)
        Me.GroupBox1.Controls.Add(Me.lbTrack0Source)
        Me.GroupBox1.Location = New System.Drawing.Point(8, 315)
        Me.GroupBox1.Name = "GroupBox1"
        Me.GroupBox1.Size = New System.Drawing.Size(712, 72)
        Me.GroupBox1.TabIndex = 59
        Me.GroupBox1.TabStop = False
        Me.GroupBox1.Text = "Audio"
        '
        'bAudioMenu1
        '
        Me.bAudioMenu1.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.bAudioMenu1.Location = New System.Drawing.Point(680, 41)
        Me.bAudioMenu1.Name = "bAudioMenu1"
        Me.bAudioMenu1.Size = New System.Drawing.Size(24, 24)
        Me.bAudioMenu1.TabIndex = 27
        '
        'lAudioProfile1
        '
        Me.lAudioProfile1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.lAudioProfile1.Location = New System.Drawing.Point(486, 46)
        Me.lAudioProfile1.Name = "lAudioProfile1"
        Me.lAudioProfile1.Size = New System.Drawing.Size(184, 16)
        Me.lAudioProfile1.TabIndex = 26
        '
        'lAudioProfile0
        '
        Me.lAudioProfile0.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.lAudioProfile0.Location = New System.Drawing.Point(486, 20)
        Me.lAudioProfile0.Name = "lAudioProfile0"
        Me.lAudioProfile0.Size = New System.Drawing.Size(184, 16)
        Me.lAudioProfile0.TabIndex = 25
        '
        'bAudioMenu0
        '
        Me.bAudioMenu0.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.bAudioMenu0.Location = New System.Drawing.Point(680, 14)
        Me.bAudioMenu0.Name = "bAudioMenu0"
        Me.bAudioMenu0.Size = New System.Drawing.Size(24, 24)
        Me.bAudioMenu0.TabIndex = 3
        '
        'MenuStrip
        '
        Me.MenuStrip.Location = New System.Drawing.Point(0, 0)
        Me.MenuStrip.Name = "MenuStrip"
        Me.MenuStrip.Size = New System.Drawing.Size(730, 24)
        Me.MenuStrip.TabIndex = 60
        Me.MenuStrip.Text = "MenuStrip"
        '
        'MainForm
        '
        Me.AllowDrop = True
        Me.ClientSize = New System.Drawing.Size(730, 461)
        Me.Controls.Add(Me.GroupBox1)
        Me.Controls.Add(Me.gbTarget)
        Me.Controls.Add(Me.gbVarious)
        Me.Controls.Add(Me.gbResize)
        Me.Controls.Add(Me.gbAviSynth)
        Me.Controls.Add(Me.gbEncoder)
        Me.Controls.Add(Me.gbAssistant)
        Me.Controls.Add(Me.MenuStrip)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.HelpButton = True
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.KeyPreview = True
        Me.MainMenuStrip = Me.MenuStrip
        Me.MaximizeBox = False
        Me.Name = "MainForm"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.Manual
        Me.Text = "StaxRip"
        Me.gbAssistant.ResumeLayout(False)
        Me.cmsOpen.ResumeLayout(False)
        Me.gbEncoder.ResumeLayout(False)
        Me.gbAviSynth.ResumeLayout(False)
        Me.gbTarget.ResumeLayout(False)
        Me.gbTarget.PerformLayout()
        Me.gbVarious.ResumeLayout(False)
        Me.gbVarious.PerformLayout()
        Me.gbResize.ResumeLayout(False)
        Me.gbResize.PerformLayout()
        CType(Me.tbResize, System.ComponentModel.ISupportInitialize).EndInit()
        Me.GroupBox1.ResumeLayout(False)
        Me.GroupBox1.PerformLayout()
        CType(Me.TipProvider, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

#End Region

    Public BlockSubtitlesItemCheck As Boolean
    Public WithEvents GenericMenu As GenericMenu
    Public WithEvents GenericMenuSize As GenericMenu
    Public CurrentAssistantTipKey As String

    Private SizeContextMenuStrip As New ContextMenuStrip
    Private BlockAviSynthItemCheck As Boolean
    Private EncoderMenu As New Hashtable
    Private TipTargetIsToolTip As Boolean
    Private TipChache As New StringPair
    Private TipTarget As TipTarget
    Private AssistantOkMessage As String = "Click on the next button to start the encoding process or click here to add the project to the job list."
    Private CanChangeSize As Boolean = True
    Private CanChangeBitrate As Boolean = True
    Private AudioMenu0 As New ContextMenuStrip
    Private AudioMenu1 As New ContextMenuStrip
    Private CanIgnoreTip As Boolean = True
    Private IsLoading As Boolean = True

    Public Sub New()
        MyBase.New()

        Try
            InitializeComponent()

            AddHandler Application.ThreadException, AddressOf g.ApplicationThreadException

            g.MainForm = Me

            ActiveControl = bOpenSourceFile

            s = DirectCast(SafeSerialization.Deserialize(New ApplicationSettings, Paths.SettingsFile), ApplicationSettings)

            WhenSettingsChange()
            InitStaxLibrary()
            TipTarget = New TipTarget(gbAssistant, lTip)
            AviSynthListView.GetProfileMethod = AddressOf GetTargetAviSynthDocument
            OpenProject(Paths.DefaultProjectPath)
            MenuStrip.SuspendLayout()

            GenericMenu = New GenericMenu(AddressOf GetDefaultMainMenu, _
                s.GenericMenuMainForm, Me, MenuStrip, TipTarget)

            GenericMenu.BuildMenu()
            InitMainMenuDynamic()
            UpdateAudioMenu()
            MenuStrip.ResumeLayout()

            SizeContextMenuStrip.SuspendLayout()
            SizeContextMenuStrip.ShowImageMargin = False

            GenericMenuSize = New GenericMenu(AddressOf GetDefaultMenuSize, _
                s.GenericMenuSize, Me, SizeContextMenuStrip, TipTarget)

            GenericMenuSize.BuildMenu()
            SizeContextMenuStrip.ResumeLayout()
            s.WindowPositions.Restore(Me, WindowPositions.Mode.Position)
        Catch ex As Exception
            g.HandleException(ex)
            Application.Exit()
        End Try
    End Sub

    Private Sub InitStaxLibrary()
        StaxApplication.StringList = s.StringList
        StaxApplication.StringDictionary = s.StringDictionary
        StaxApplication.WindowPositions = s.WindowPositions
        StaxApplication.Icon = Icon

        HelpForm.ButtonsFunction = New FunctionDelegate(Of List(Of ToolStripButton))(AddressOf GetHelpButtons)
        HelpForm.AutoGenPath = Paths.DocumentsDir + "auto.htm"
        HelpForm.InfoFilePath = Paths.DocumentsDir + "info.htm"
    End Sub

    Public Function GetHelpButtons() As List(Of ToolStripButton)
        Dim ret As New List(Of ToolStripButton)

        Dim help As New ToolStripButton
        help.Image = StaxRip.My.Resources.Resources.Help16
        help.ImageTransparentColor = System.Drawing.Color.Magenta
        help.Name = "tsbHelp"
        help.Text = "Help"
        help.Tag = Paths.DocumentsDir + "help.htm"
        ret.Add(help)

        Dim support As New ToolStripButton
        support.Image = StaxRip.My.Resources.Resources.Support16
        support.ImageTransparentColor = System.Drawing.Color.Magenta
        support.Name = "tsbSupport"
        support.Text = "Support"
        support.Tag = Paths.DocumentsDir + "support.htm"
        ret.Add(support)

        Dim changelog As New ToolStripButton
        changelog.Image = StaxRip.My.Resources.Resources.Notice16
        changelog.ImageTransparentColor = System.Drawing.Color.Magenta
        changelog.Name = "tsbChangelog"
        changelog.Text = "Changelog"
        changelog.Tag = Paths.DocumentsDir + "changelog.htm"
        ret.Add(changelog)

        Dim info As New ToolStripButton
        info.Image = StaxRip.My.Resources.Resources.Info16
        info.ImageTransparentColor = System.Drawing.Color.Magenta
        info.Name = "tsbInfo"
        info.Text = "Info"
        info.Tag = Paths.DocumentsDir + "info.htm"
        ret.Add(info)

        Return ret
    End Function

    Public Sub RenameDVDTracks()
        Dim ifoPath As String = StringHelp.DeleteRight(p.SourceFile, 5) + "0.ifo"

        If Not File.Exists(ifoPath) Then
            Exit Sub
        End If

        For Each i As String In Directory.GetFiles(Filepath.GetDir(p.SourceFile))
            If g.BelongsToSource(i) AndAlso i.Contains("VTS") Then
                Dim re As New Regex(" T(\d\d) ")
                Dim m As Match = re.Match(i)

                If m.Success Then
                    Try
                        Paths.MediaInfo.Active = True

                        If Not Paths.MediaInfo.VerifyOK() Then
                            Exit Sub
                        End If
                    Finally
                        Paths.MediaInfo.Active = False
                    End Try

                    Dim indexFilename As Integer = CInt(m.Groups(1).Value) - 1

                    Using mi As New MediaInfo(ifoPath)
                        For Each iAudioTrack As MediaInfoAudioTrack In mi.AudioTracks
                            If indexFilename = mi.AudioTracks.IndexOf(iAudioTrack) Then
                                Dim ci As CultureInfo

                                Try
                                    ci = New CultureInfo(iAudioTrack.LanguageTwoLetter)
                                Catch
                                    ci = Language.Languages(0).CultureInfo
                                End Try

                                Dim newName As String

                                If iAudioTrack.Info <> "" Then
                                    newName = re.Replace(i, " " + (indexFilename + 1).ToString("d2") + " " + ci.TwoLetterISOLanguageName + "-" + ci.EnglishName + " " + iAudioTrack.Info + " ")
                                Else
                                    newName = re.Replace(i, " " + (indexFilename + 1).ToString("d2") + " " + ci.TwoLetterISOLanguageName + "-" + ci.EnglishName + " ")
                                End If

                                FileHelp.Move(i, newName)
                            End If
                        Next
                    End Using
                End If
            End If
        Next
    End Sub

    Private Sub LoadAudioFiles()
        RenameDVDTracks()

        tbAudioFile0.Text = ""
        tbAudioFile1.Text = ""

        Dim files As String() = Directory.GetFiles(Filepath.GetDir(p.SourceFile))

        For Each iExt As String In p.Audio0.Profile.SupportedInputFileTypes
            For Each iPath As String In files
                If g.BelongsToSource(iPath) AndAlso iPath.ToUpper.EndsWith(iExt.ToUpper) Then
                    If p.Audio0.File = "" AndAlso _
                        iPath <> p.Audio1.File AndAlso _
                        iPath.Contains(p.Audio0.Language.TwoLetterCode + "-" + p.Audio0.Language.Name) Then

                        tbAudioFile0.Text = iPath
                    End If
                End If
            Next
        Next

        For Each iExt As String In p.Audio1.Profile.SupportedInputFileTypes
            For Each iPath As String In files
                If g.BelongsToSource(iPath) AndAlso iPath.ToUpper.EndsWith(iExt.ToUpper) Then
                    If p.Audio1.File = "" AndAlso _
                        iPath <> p.Audio0.File AndAlso _
                        iPath.Contains(p.Audio1.Language.TwoLetterCode + "-" + p.Audio1.Language.Name) Then

                        tbAudioFile1.Text = iPath
                    End If
                End If
            Next
        Next

        For Each iExt As String In p.Audio0.Profile.SupportedInputFileTypes
            For Each iPath As String In files
                If g.BelongsToSource(iPath) AndAlso iPath.ToUpper.EndsWith(iExt.ToUpper) Then
                    If p.Audio0.File = "" AndAlso iPath <> p.Audio1.File Then
                        tbAudioFile0.Text = iPath
                    End If
                End If
            Next
        Next

        For Each iExt As String In p.Audio1.Profile.SupportedInputFileTypes
            For Each iPath As String In files
                If g.BelongsToSource(iPath) AndAlso iPath.ToUpper.EndsWith(iExt.ToUpper) Then
                    If p.Audio1.File = "" AndAlso iPath <> p.Audio0.File AndAlso _
                        Filepath.GetExt(iPath) = Filepath.GetExt(tbAudioFile0.Text) Then

                        tbAudioFile1.Text = iPath
                    End If
                End If
            Next
        Next
    End Sub

    Private Function IsTemplatePath(ByVal path As String) As Boolean
        Return path = Paths.DefaultProjectPath OrElse path.StartsWith(Paths.TemplateDir)
    End Function

    Public Sub SaveProject(ByVal path As String)
        If Not IsTemplatePath(path) Then
            g.ProjectPath = path
            Text = Application.ProductName + " - " + Filepath.GetNameWithExt(path)
            UpdateRecentProjectsMenuItems(path)
            g.SavedProject = DirectCast(Stax.ObjectHelp.GetCopy(p), Project)
        Else
            If p.SourceFile <> "" Then
                Msg.Show("A template project cannot be created after a source file was opened.", MsgIcon.Warning)
                Exit Sub
            End If
        End If

        SafeSerialization.Serialize(p, path)
    End Sub

    Public Function IsSaveCanceled() As Boolean
        'StringHelp.WriteFile(CommonDirs.UserDesktop + "test1.txt", ObjectHelp.GetCompareString(g.SavedProject))
        'StringHelp.WriteFile(CommonDirs.UserDesktop + "test2.txt", ObjectHelp.GetCompareString(p))

        If ObjectHelp.GetCompareString(g.SavedProject) <> ObjectHelp.GetCompareString(p) Then
            Dim msgtext As String

            If g.ProjectPath Is Nothing Then
                msgtext = "Save changed project?"
            Else
                msgtext = "Save changes in " + Filepath.GetNameWithExt(g.ProjectPath) + "?"
            End If

            Dim result As DialogResult = Msg.Show(msgtext, "Save Project", _
                MsgIcon.Question, MessageBoxButtons.YesNoCancel)

            Refresh()

            Select Case result
                Case Windows.Forms.DialogResult.Yes
                    If g.ProjectPath Is Nothing Then
                        If Not ShowSaveDialog() Then
                            Return True
                        End If
                    Else
                        SaveProject(g.ProjectPath)
                    End If
                Case Windows.Forms.DialogResult.Cancel
                    Return True
            End Select
        End If
    End Function

    Public Sub UpdateRecentProjectsMenuItems(ByVal path As String)
        If Not IsTemplatePath(path) Then
            Misc.UpdateMostRecentList(s.RecentProjects, path, 9)

            For Each i As ExtendedToolStripMenuItem In GenericMenu.MenuItems
                If i.GenericMenuItem.MethodName = "DynamicMenuItem" AndAlso _
                    i.GenericMenuItem.Parameters(0).ToString = "Recent Projects" Then

                    i.DropDownItems.Clear()

                    For Each iRecent As String In s.RecentProjects
                        If File.Exists(iRecent) Then
                            i.DropDownItems.Add(New ParamToolStripMenuItem(Of String)(iRecent, AddressOf LoadProject, iRecent))
                        End If
                    Next

                    Exit For
                End If
            Next
        End If
    End Sub

    Public Sub UpdateTemplateProjectsMenuItems()
        For Each i As ExtendedToolStripMenuItem In GenericMenu.MenuItems
            If i.GenericMenuItem.MethodName = "DynamicMenuItem" AndAlso _
                i.GenericMenuItem.Parameters(0).ToString = "Template Projects" Then

                i.DropDownItems.Clear()

                For Each iFile As String In Directory.GetFiles(Paths.TemplateDir)
                    i.DropDownItems.Add(New ParamToolStripMenuItem(Of String)(Filepath.GetNameNoExt(iFile), AddressOf LoadProject, iFile))
                Next

                Exit For
            End If
        Next
    End Sub

    Public Sub LoadProject(ByVal path As String)
        Refresh()

        If Not File.Exists(path) Then
            Msg.Show("Project file not found.", MsgIcon.Warning)
            UpdateTemplateProjectsMenuItems()
            UpdateRecentProjectsMenuItems("")
        Else
            OpenProject(path)
        End If
    End Sub

    Public Function ShowSaveDialog() As Boolean
        Using d As New SaveFileDialog
            If Not g.ProjectPath Is Nothing Then
                d.FileName = g.ProjectPath
            ElseIf p.SourceFile <> "" Then
                d.FileName = Filepath.GetDir(p.SourceFile) + p.Name + ".rip"
            Else
                d.FileName = "Untitled"
            End If

            d.DefaultExt = "rip"
            d.Filter = "Project Files|*.rip"

            If d.ShowDialog() = Windows.Forms.DialogResult.OK Then
                SaveProject(d.FileName)
                Return True
            End If
        End Using
    End Function

    Public Function OpenProject(ByVal path As String) As Boolean
        Return OpenProject(path, True)
    End Function

    Public Function OpenProject(ByVal path As String, ByVal saveCurrent As Boolean) As Boolean
        If saveCurrent AndAlso IsSaveCanceled() Then
            Return False
        End If

        Log.Clear()

        If IsTemplatePath(path) Then
            Text = "StaxRip - Untitled.rip"
            g.ProjectPath = Nothing
        Else
            g.ProjectPath = path
            Text = "StaxRip - " + Filepath.GetNameWithExt(path)
        End If

        p = DirectCast(SafeSerialization.Deserialize(New Project, path), Project)

        Dim width As Integer = p.TargetWidth
        Dim height As Integer = p.TargetHeight
        Dim size As Integer = p.Size
        Dim bitrate As Integer = p.VideoBitrate

        SetTargetLength(p.TargetSeconds)
        lbSourceLength.Text = GetLengthString(p.SourceSeconds)

        AviSynthListView.Load()
        OnLoadEncoder()

        Dim targetPath As String = p.TargetFile

        Dim audio0 As String = p.Audio0.File
        Dim audio1 As String = p.Audio1.File

        Dim delay0 As Integer = p.Audio0.Delay
        Dim delay1 As Integer = p.Audio1.Delay

        tbSource.Text = p.SourceFile

        If p.SourceFile <> "" Then
            s.LastSourceDir = Filepath.GetDir(p.SourceFile)
        End If

        tbAudioFile0.Text = audio0
        tbAudioFile1.Text = audio1

        lAudioProfile0.Text = p.Audio0.Profile.Name
        lAudioProfile1.Text = p.Audio1.Profile.Name

        p.Audio0.Delay = delay0
        p.Audio1.Delay = delay1

        tbSize.Text = size.ToString()
        cb169.Checked = p.Source169

        tbTargetWidth.Text = width.ToString
        tbTargetHeight.Text = height.ToString

        tbTargetPath.Text = targetPath

        g.SavedProject = DirectCast(Stax.ObjectHelp.GetCopy(p), Project)

        Assistant()
        UpdateRecentProjectsMenuItems(path)

        Return True
    End Function

    Public Sub WhenSettingsChange()
        tbResize.Maximum = CInt((s.ResizeSliderMax.Value - s.ResizeSliderMin.Value) / 16)
    End Sub

    Public Function ExtractDelay(ByVal value As String) As Integer
        Dim m As Match = Regex.Match(value, "(-?\d+)ms\.")
        If m.Success Then Return CInt(m.Groups(1).Value)
    End Function

    Public Sub FormMain_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) Handles MyBase.DragEnter
        e.Effect = DragDropEffects.Copy
    End Sub

    Public Sub FormMain_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles MyBase.DragDrop
        Dim a As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())

        If Not a Is Nothing AndAlso a.Length > 0 Then
            OpenAnyFile(New List(Of String)(a))
        End If
    End Sub

    Public Sub OpenAnyFile(ByVal l As List(Of String))
        Select Case Filepath.GetExt(l(0))
            Case ".rip"
                OpenProject(l(0))
            Case ".mpa", ".mp2", ".mp3", ".ac3", ".aac", ".wav"
                tbAudioFile0.Text = l(0)
            Case Else
                l.Sort()
                OpenVideoSourceFiles(l)
        End Select
    End Sub

    Public Sub OpenVideoSourceFiles(ByVal files As List(Of String))
        OpenVideoSourceFiles(files, True)
    End Sub

    Public Sub OpenVideoSourceFiles(ByVal files As List(Of String), ByVal autoMode As Boolean)
        Try
            For Each i As DriveInfo In DriveInfo.GetDrives()
                If i.DriveType = DriveType.CDRom AndAlso files(0).ToUpper.StartsWith(i.RootDirectory.ToString.ToUpper) Then
                    Msg.Show("Opening files from a CD/DVD drive is not supported.", MsgIcon.Warning)
                    g.ShowHelpTopic("help")
                    Exit Sub
                End If
            Next

            If Filepath.GetExt(files(0)) = ".avs" Then
                Msg.Show("AviSynth scripts can't be imported, please use the build in AviSynth feature.", MsgIcon.Warning)
                Exit Sub
            End If

            If StringHelp.ContainsUnicodeChars(files(0)) Then
                Msg.Show("Filenames with unicode characters are not supported by some required applications. Please rename the file.", MsgIcon.Warning)
                Exit Sub
            End If

            If files(0).Contains(",") Then
                Msg.Show("Filenames with comma are not supported by some required applications. Please rename the file.", MsgIcon.Warning)
                Exit Sub
            End If

            If autoMode AndAlso p.BatchMode.Value Then
                p.AutoSourceFiles = files
                Assistant()
                Exit Sub
            End If

            If Not Paths.VerifyRequirements() Then
                Exit Sub
            End If

            If p.SourceFile <> "" AndAlso Not p.BatchMode.Value Then
                If Not OpenProject(Paths.DefaultProjectPath) Then
                    Exit Sub
                End If
            End If

            s.LastSourceDir = Filepath.GetDir(p.SourceFile)
            p.SourceFiles = files
            p.SourceFile = files(0)

            tbTargetPath.Text = Filepath.GetDirAndNameNoExt(p.SourceFile) + p.VideoEncoder.Muxer.GetExtension

            If p.SourceFile = p.TargetFile Then
                tbTargetPath.Text = Filepath.GetDirAndNameNoExt(p.TargetFile) + "_new" + Filepath.GetExt(p.TargetFile)
            End If

            Prepare()

            If Filepath.GetExt(p.SourceFile) = ".d2v" AndAlso _
                Not p.TargetAVSDoc.GetFilter("Source").Script.ToLower.Contains("mpeg2source(") Then

                p.TargetAVSDoc = AviSynthDocument.GetDefaults()(0)
                g.MainForm.AviSynthListView.Load()
            ElseIf Filepath.GetExt(p.SourceFile) <> ".d2v" AndAlso _
                p.TargetAVSDoc.GetFilter("Source").Script.ToLower.Contains("mpeg2source(") Then

                If Filepath.GetExt(p.SourceFile) = ".avi" Then
                    p.TargetAVSDoc = AviSynthDocument.GetDefaults()(0)
                    p.TargetAVSDoc.Filters.RemoveAt(0)
                    p.TargetAVSDoc.Filters.Insert(0, New AviSynthFilter("Source", "AVISource", "AVISource(%source_files_comma%,audio=false)", True))
                Else
                    p.TargetAVSDoc = AviSynthDocument.GetDefaults()(0)
                    p.TargetAVSDoc.Filters.RemoveAt(0)
                    p.TargetAVSDoc.Filters.Insert(0, New AviSynthFilter("Source", "DirectShowSource", "DirectShowSource(""%source_file%"")", True))
                End If

                g.MainForm.AviSynthListView.Load()
            End If

            LoadAudioFiles()

            If Filepath.GetExt(p.SourceFile) = ".d2v" Then
                Dim content As String = StringHelp.ReadFile(p.SourceFile)

                cb169.Checked = content.Contains("Aspect_Ratio=16:9")

                If content.Contains("Frame_Rate=29970") Then
                    Dim m As Match = Regex.Match(content, "FINISHED +(\d\d)\.")

                    If m.Success Then
                        Dim film As Integer = CInt(m.Groups(1).Value)

                        If film > 95 Then
                            content = content.Replace("Field_Operation=0" + vbCrLf + "Frame_Rate=29970", "Field_Operation=1" + vbCrLf + "Frame_Rate=23976")
                            StringHelp.WriteFile(p.SourceFile, content)
                        End If
                    End If
                End If
            End If

            p.VideoEncoder.Muxer.Init()

            p.SourceAviSynthDocument.Synchronize()

            If Not p.SourceAviSynthDocument.IsValid Then
                ProcessForm.CloseProcessForm()

                Dim filter As AviSynthFilter = p.TargetAVSDoc.GetFilter("Source")

                If filter Is Nothing Then
                    Msg.Show("It's required to have a filter with the category ""Source"" that returns a valid script.", MsgIcon.Error)
                Else
                    Msg.Show("Failed to load source.", "Invalid Source", MsgIcon.Warning)

                    Dim f As New PreviewForm(p.SourceAviSynthDocument)
                    f.ShowDialog()
                    f.Dispose()
                End If

                Exit Sub
            End If

            p.SourceWidth = p.SourceAviSynthDocument.GetSize.Width
            p.SourceHeight = p.SourceAviSynthDocument.GetSize.Height
            p.SourceSeconds = CInt(p.SourceAviSynthDocument.GetFrames / p.SourceAviSynthDocument.GetFramerate)
            p.SourceFramerate = p.SourceAviSynthDocument.GetFramerate
            p.SourceFrames = p.SourceAviSynthDocument.GetFrames

            tbSource.Text = p.SourceFile
            g.PreviewLastPosition = 0

            SetTargetLength(p.SourceSeconds)
            lbSourceLength.Text = lbTargetLength.Text

            If p.AutoCrop AndAlso p.TargetAVSDoc.Contains("%crop_left%") Then
                g.AutoCrop()
            End If

            If p.AutoResizeImage <> 0 AndAlso p.TargetAVSDoc.Contains("%target_width%") Then
                g.AutoResize()
            End If

            If p.AutoSmartCrop.Value Then
                g.SmartCrop()
            End If

            If p.AutoCompCheck AndAlso p.VideoEncoder.IsCompCheckEnabled Then
                p.VideoEncoder.StartCompCheck()
            End If

            UpdateControls()
            Assistant()
            ProcessForm.CloseProcessForm()
        Catch ex As AbortException
            ProcessForm.CloseProcessForm()
        End Try
    End Sub

    Public Sub Encode()
        Dim startTime As DateTime = DateTime.Now

        If p.BatchMode.Value Then
            If g.ProjectPath Is Nothing Then
                g.ProjectPath = Filepath.GetDirAndNameNoExt(p.AutoSourceFiles(0)) + ".rip"
            End If

            SaveProject(g.ProjectPath)
            OpenVideoSourceFiles(p.AutoSourceFiles, False)
        End If

        ProcessForm.ShowForm(True)

        If g.ProjectPath Is Nothing Then
            g.ProjectPath = Filepath.GetDir(p.SourceFile) + p.Name + ".rip"
        End If

        SaveProject(g.ProjectPath)

        Log.WriteHeader("Versions")
        Log.AddLines(Info.GetVersions)

        Log.WriteHeader("Macros")
        Log.AddLines(Info.GetMacros)

        Log.WriteHeader("AviSynth Plugins")
        Log.AddLines(Info.GetAviSynthPlugins)

        Log.WriteHeader("AviSynth Script")
        Log.AddLines(Macro.Solve(p.TargetAVSDoc.GetScript))

        CutPreProcessing(p.Audio0)
        p.Audio0.Profile.Encode()

        CutPreProcessing(p.Audio1)
        p.Audio1.Profile.Encode()

        p.VideoEncoder.Encode()
        p.VideoEncoder.Muxer.Mux()

        Log.WriteHeader("Overall Statistics")
        Log.WriteStats(startTime, p.TargetAVSDoc.GetFrames, False)

        Log.Save()
        Process.Start(Filepath.GetDir(p.SourceFile))
    End Sub

    Public Sub CutPreProcessing(ByVal settings As AudioSettings)
        If p.Ranges.Count = 0 Then Exit Sub
        If Not File.Exists(settings.File) Then Exit Sub

        Dim start As DateTime = DateTime.Now

        If Filepath.GetExt(settings.File) = ".ac3" Then
            Dim doc As New AviSynthDocument
            doc.Path = Paths.GetTempDir + p.Name + "_Cutting.avs"

            For Each i As AviSynthFilter In p.TargetAVSDoc.Filters
                If i.Category = "Source" Then
                    doc.Filters.Add(i.GetCopy)
                End If
            Next

            doc.Synchronize()

            Dim script As New VirtualDubScript
            script.Open(doc.Path)
            script.StreamSetSource(0, settings.File, StreamType.AC3)
            script.StreamSetMode(0, AudioMode.DirectStreamCopy)
            script.SubsetClear()

            For Each i As Range In p.Ranges
                script.SubsetAddRange(i.Start, i.End - i.Start)
            Next

            settings.File = Paths.GetTempDir + Filepath.GetNameNoExt(settings.File) + "_Cutting.ac3"

            script.StreamDemux(0, settings.File)
            script.SaveScript(Paths.GetTempDir + p.Name + "_Cutting.vcf")

            Dim pwCut As New ProcessWrapper
            ProcessForm.ProcessWrapper = pwCut

            pwCut.File = Paths.VirtualDubMod.GetPath(False)
            pwCut.Arguments = "/s""" + Paths.GetTempDir + p.Name + "_Cutting.vcf"" /x"
            pwCut.Minimized = s.RunAppsMinimized.Value
            pwCut.Wait = True
            pwCut.Priority = s.ProcessPriority.Value

            Log.WriteHeader("Audio Cutting")
            Log.WriteLine(Macro.Solve(doc.GetScript).Trim)

            pwCut.Start()

            Log.WriteHeader("Audio Cutting Statistics")
            Log.WriteStats(start, p.TargetAVSDoc.GetFrames)
        Else
            Dim wavfile As String = Paths.GetTempDir + Filepath.GetNameNoExt(settings.File) + ".wav"

            If Not File.Exists(wavfile) Then
                Dim pw As New ProcessWrapper
                ProcessForm.ProcessWrapper = pw

                pw.File = Paths.BeSweet.GetPath(False)
                pw.Arguments = "-core( -input """ + settings.File + """ -output """ + wavfile + """ -2ch ) -azid( -c normal -L -3db )"

                Log.WriteHeader("Audio Decoding")
                Log.WriteLine(pw.CommandLine)

                pw.Minimized = s.RunAppsMinimized.Value
                pw.Wait = True
                pw.Priority = s.ProcessPriority.Value
                pw.Start()

                Log.WriteHeader("Audio Decoding Statistics")
                Log.WriteStats(start, p.SourceFrames)
            End If

            Dim doc As New AviSynthDocument
            doc.Path = Paths.GetTempDir + p.Name + "_Cutting.avs"

            For Each i As AviSynthFilter In p.TargetAVSDoc.Filters
                If i.Category = "Source" Then
                    doc.Filters.Add(i.GetCopy)
                End If
            Next

            doc.Filters.Add(New AviSynthFilter("Audio", "Audio", "AudioDub(last,WAVSource(""" + wavfile + """))", True))

            For Each i As AviSynthFilter In p.TargetAVSDoc.Filters
                If i.Category = "Cutting" Then
                    doc.Filters.Add(i.GetCopy)
                End If
            Next

            doc.Synchronize()

            settings.File = Paths.GetTempDir + Filepath.GetNameNoExt(settings.File) + "_Cutting.wav"

            Dim script As New VirtualDubScript
            script.Open(doc.Path)
            script.SaveWAV(settings.File)
            script.SaveScript(Paths.GetTempDir + p.Name + "_Cutting.vcf")

            Dim pwCut As New ProcessWrapper
            ProcessForm.ProcessWrapper = pwCut

            pwCut.File = Paths.VirtualDubMod.GetPath(False)
            pwCut.Arguments = "/s""" + Paths.GetTempDir + p.Name + "_Cutting.vcf"" /x"
            pwCut.Minimized = s.RunAppsMinimized.Value
            pwCut.Wait = True
            pwCut.Priority = s.ProcessPriority.Value

            Log.WriteHeader("Audio Cutting")
            Log.WriteLine(Macro.Solve(doc.GetScript).Trim)

            start = DateTime.Now

            pwCut.Start()

            Log.WriteHeader("Audio Cutting Statistics")
            Log.WriteStats(start, p.TargetAVSDoc.GetFrames)
        End If
    End Sub

    Public Function ProcessTip(ByVal message As String) As Boolean
        lTip.Text = message
        CurrentAssistantTipKey = StringHelp.GetMD5Hash(message)

        If Not p.SkippedAssistantTips.Contains(CurrentAssistantTipKey) Then
            Return True
        End If
    End Function

    Private AssistantMethodValue As SubDelegate

    Public Property AssistantMethod() As SubDelegate
        Get
            Return AssistantMethodValue
        End Get
        Set(ByVal Value As SubDelegate)
            AssistantMethodValue = Value

            If Value Is Nothing Then
                lTip.Cursor = Cursors.Default
            Else
                lTip.Cursor = Cursors.Hand
            End If
        End Set
    End Property

    Public Function Assistant() As Boolean
        lTip.Text = ""
        gbAssistant.Text = ""
        AssistantMethod = Nothing
        CanIgnoreTip = True

        g.Highlight(False, lCompCheckValue)
        g.Highlight(False, lQualityValue)
        g.Highlight(False, tbBitrate)
        g.Highlight(False, tbSize)
        g.Highlight(False, tbTargetWidth)
        g.Highlight(False, tbTargetHeight)
        g.Highlight(False, lARUsedValue)
        g.Highlight(False, tbAudioFile0)
        g.Highlight(False, tbAudioFile1)
        g.Highlight(False, tbTargetPath)
        g.Highlight(False, tbSource)
        g.Highlight(False, lAudioProfile0)
        g.Highlight(False, lAudioProfile1)

        If Not p.BatchMode.Value Then
            If p.SourceSeconds = 0 Then
                If ProcessTip("This assistant guides you preparing your encode. Please click here to open a source file.") Then
                    AssistantMethod = AddressOf OpenFileToolStripMenuItem.PerformClick
                    gbAssistant.Text = "Assistant"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            If p.SourceFile = p.TargetFile Then
                If ProcessTip("The source and target filepath is identical.") Then
                    g.Highlight(True, tbTargetPath)
                    gbAssistant.Text = "Invalid Targetpath"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            If p.Audio0.File = p.TargetFile OrElse p.Audio1.File = p.TargetFile Then
                If ProcessTip("The audio source and target filepath is identical.") Then
                    g.Highlight(True, tbTargetPath)
                    gbAssistant.Text = "Invalid Targetpath"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            If ProcessTip("Please click here to open the crop dialog. When done continue with Next.") Then
                AssistantMethod = AddressOf OpenCropDialog
                gbAssistant.Text = "Crop"
                Return False
            End If

            If p.Audio0.File <> "" AndAlso p.Audio0.File = p.Audio1.File Then
                If ProcessTip("The first and second audio source files are identical.") Then
                    g.Highlight(True, tbAudioFile0)
                    g.Highlight(True, tbAudioFile1)
                    gbAssistant.Text = "Invalid Audio Settings"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            If TypeOf p.VideoEncoder.Muxer Is EncoderMuxer Then
                If Not DirectCast(p.VideoEncoder.Muxer, EncoderMuxer).Encoder.IsAssignableFrom(p.VideoEncoder.GetType) Then
                    If ProcessTip("Muxer and encoder are not compatible.") Then
                        gbAssistant.Text = "Invalid Muxer"
                        CanIgnoreTip = False
                        Return False
                    End If
                End If
            End If

            If Not p.VideoEncoder.Muxer.IsStreamSupported(p.VideoEncoder.OutputStreamType) Then
                If ProcessTip("The encoder outputs '" + StreamTypeUtils.GetName(p.VideoEncoder.OutputStreamType) + "' but the container supports only " + StreamTypeUtils.GetNames(p.VideoEncoder.Muxer.InputTypes) + ". Please configure the encoder to output another format (most encoders don't allow this though) or choose another container.") Then
                    gbAssistant.Text = "Encoder conflicts with container"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            If p.Audio0.File <> "" AndAlso Not p.VideoEncoder.Muxer.IsStreamSupported(p.Audio0.Profile.StreamType) AndAlso Not p.Audio0.Profile.StreamType = StreamType.Ignore Then
                If ProcessTip("The audio format is '" + StreamTypeUtils.GetName(p.Audio0.Profile.StreamType) + "' but the container supports only " + StreamTypeUtils.GetNames(p.VideoEncoder.Muxer.InputTypes) + ". Please choose another audio profile or another container.") Then
                    g.Highlight(True, lAudioProfile0)
                    gbAssistant.Text = "Audio format conflicts with container"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            If p.Audio1.File <> "" AndAlso Not p.VideoEncoder.Muxer.IsStreamSupported(p.Audio1.Profile.StreamType) AndAlso Not p.Audio1.Profile.StreamType = StreamType.Ignore Then
                If ProcessTip("The audio format is '" + StreamTypeUtils.GetName(p.Audio1.Profile.StreamType) + "' but the container supports only " + StreamTypeUtils.GetNames(p.VideoEncoder.Muxer.InputTypes) + ". Please choose another audio profile or another container.") Then
                    g.Highlight(True, lAudioProfile1)
                    gbAssistant.Text = "Audio format conflicts with container"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            If p.Audio0.File <> "" AndAlso Not p.Audio0.Profile.SupportedInputFileTypes.Contains( _
                Filepath.GetExtNoDot(p.Audio0.File)) Then

                If ProcessTip("The audio profile supports the input formats " + String.Join(", ", p.Audio0.Profile.SupportedInputFileTypes.ToArray) + ". Please choose another audio profile.") Then
                    g.Highlight(True, tbAudioFile0)
                    g.Highlight(True, lAudioProfile0)
                    gbAssistant.Text = "Audio profile incompatible with source"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            If p.Audio1.File <> "" AndAlso Not p.Audio1.Profile.SupportedInputFileTypes.Contains( _
                Filepath.GetExtNoDot(p.Audio1.File)) Then

                If ProcessTip("The audio profile supports the input formats " + String.Join(", ", p.Audio1.Profile.SupportedInputFileTypes.ToArray) + ". Please choose another audio profile.") Then
                    g.Highlight(True, tbAudioFile1)
                    g.Highlight(True, lAudioProfile1)
                    gbAssistant.Text = "Audio profile incompatible with source"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            If p.VideoEncoder.Muxer.GetExtension <> Filepath.GetExt(p.TargetFile) Then
                If ProcessTip("The container requires " + p.VideoEncoder.Muxer.GetExtension.Trim("."c).ToUpper + " as target file type.") Then
                    g.Highlight(True, tbTargetPath)
                    gbAssistant.Text = "Invalid File Type"
                    CanIgnoreTip = False
                    Return False
                End If
            End If

            Dim ae As Double = GetAspectRatioError()

            If p.SourceWidth > 0 AndAlso (ae > 2 OrElse ae < -2) _
                AndAlso p.TargetAVSDoc.IsFilterActive("Resize") Then

                If ProcessTip("Please use the resize slider in order to fix the aspect ratio error.") Then
                    g.Highlight(True, lARUsedValue)
                    gbAssistant.Text = "Aspect Ratio Error"
                    Return False
                End If
            End If

            If ProcessTip("Please verify the filter setup. When done continue with Next.") Then
                gbAssistant.Text = "Filter Setup"
                Return False
            End If

            If p.Ranges.Count = 0 Then
                If ProcessTip("Please click here to open the preview for cutting if necessary. When done continue with Next.") Then
                    AssistantMethod = AddressOf OpenPreview
                    gbAssistant.Text = "Cutting"
                    Return False
                End If
            Else
                If TypeOf p.Audio0.Profile Is MuxAudioProfile AndAlso _
                    p.Audio0.Profile.StreamType <> StreamType.AC3 AndAlso _
                    p.Audio0.Profile.StreamType <> StreamType.WAV AndAlso _
                    File.Exists(p.Audio0.File) Then

                    If ProcessTip("Muxing audio profiles can only be used with WAV and AC3 sources when cutting.") Then
                        gbAssistant.Text = "Invalid Audio Profile"
                        g.Highlight(True, lAudioProfile0)
                        CanIgnoreTip = False
                        Return False
                    End If
                End If

                If TypeOf p.Audio1.Profile Is MuxAudioProfile AndAlso _
                    p.Audio1.Profile.StreamType <> StreamType.AC3 AndAlso _
                    p.Audio1.Profile.StreamType <> StreamType.WAV AndAlso _
                    File.Exists(p.Audio1.File) Then

                    If ProcessTip("Muxing audio profiles can only be used with WAV and AC3 sources when cutting.") Then
                        gbAssistant.Text = "Invalid Audio Profile"
                        g.Highlight(True, lAudioProfile0)
                        CanIgnoreTip = False
                        Return False
                    End If
                End If

                If Not p.TargetAVSDoc.IsFilterActive("Cutting") Then
                    If ProcessTip("The cutting filter settings don't match with the cutting settings used in the preview.") Then
                        gbAssistant.Text = "Invalid Cutting Settings"
                        CanIgnoreTip = False
                        Return False
                    End If
                End If
            End If

            If p.VideoEncoder.IsCompCheckEnabled AndAlso p.Compressibility = 0 Then
                If ProcessTip("Please click here to start the compressibility check. The compressibility check finds the optimal bitrate.") Then
                    AssistantMethod = AddressOf p.VideoEncoder.StartCompCheck
                    g.Highlight(True, lCompCheckValue)
                    gbAssistant.Text = "Compressibility Check"
                    Return False
                End If
            End If

            If File.Exists(p.TargetFile) Then
                If ProcessTip("The target file already exist. Click next to overwrite it.") Then
                    g.Highlight(True, tbTargetPath)
                    gbAssistant.Text = "Target File"
                    Return False
                End If
            End If

            If p.TargetAVSDoc.IsFilterActive("Source") Then
                If p.TargetWidth Mod 16 <> 0 Then
                    If ProcessTip("Please move the resize slider to adjust the target width to be divisible by 16.") Then
                        g.Highlight(True, tbTargetWidth)
                        gbAssistant.Text = "Invalid Target Width"
                        Return False
                    End If
                End If

                If p.TargetHeight Mod 16 <> 0 Then
                    If ProcessTip("Please move the resize slider to adjust the target height to be divisible by of 16.") Then
                        g.Highlight(True, tbTargetHeight)
                        gbAssistant.Text = "Invalid Target Height"
                        Return False
                    End If
                End If
            Else
                If p.TargetAVSDoc.GetSize.Width Mod 16 <> 0 Then
                    If ProcessTip("The image width is not a multiple of 16.") Then
                        g.Highlight(True, tbTargetWidth)
                        gbAssistant.Text = "Invalid Image Width"
                        Return False
                    End If
                End If

                If p.TargetAVSDoc.GetSize.Height Mod 16 <> 0 Then
                    If ProcessTip("The image height is not a multiple of 16.") Then
                        g.Highlight(True, tbTargetHeight)
                        gbAssistant.Text = "Invalid Image Height"
                        Return False
                    End If
                End If
            End If

            If p.VideoEncoder.IsCompCheckEnabled AndAlso p.Compressibility > 0 Then
                Dim value As Double = Calc.GetPercent 'slow when resizing because script must be synchronized

                If value < (p.VideoEncoder.AutoCompCheckValue - 10) Then
                    If ProcessTip("Please decrease the resolution or increase the bitrate. A too low quality values causes a poor image quality.") Then
                        g.Highlight(True, tbSize)
                        g.Highlight(True, tbBitrate)
                        g.Highlight(True, tbTargetWidth)
                        g.Highlight(True, tbTargetHeight)
                        g.Highlight(True, lQualityValue)
                        lQualityValue.BackColor = Color.Red
                        gbAssistant.Text = "Too Low Quality"
                        Return False
                    End If
                ElseIf value > (p.VideoEncoder.AutoCompCheckValue + 10) Then
                    If ProcessTip("Please increase the resolution or decrease the bitrate. A too high quality values might produce a unnecessary large target file.") Then
                        g.Highlight(True, tbSize)
                        g.Highlight(True, tbBitrate)
                        g.Highlight(True, tbTargetWidth)
                        g.Highlight(True, tbTargetHeight)
                        lQualityValue.BackColor = Color.Red
                        gbAssistant.Text = "Too High Quality"
                        Return False
                    End If
                End If
            End If

            If TypeOf p.VideoEncoder Is x264Encoder AndAlso p.TargetAVSDoc.GetFourCC <> "YV12" Then
                If ProcessTip("x264 requires YV12 input. Right-click the filters, select 'Add' and choose 'Misc/ConvertToYV12'.") Then
                    CanIgnoreTip = False
                    gbAssistant.Text = "Unsupported Colorspace"
                    Return False
                End If
            End If
        Else
            If p.AutoSourceFiles.Count = 0 Then
                If ProcessTip("Please click here to open a source file.") Then
                    AssistantMethod = AddressOf OpenFileToolStripMenuItem.PerformClick
                    gbAssistant.Text = "Assistant"
                    CanIgnoreTip = False
                    Return False
                End If
            End If
        End If

        gbAssistant.Text = "Ready"
        lTip.Text = AssistantOkMessage
        AssistantMethod = AddressOf OpenJobsDialog
    End Function

    Public Sub tbAudioFile0_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbAudioFile0.TextChanged
        p.Audio0.File = tbAudioFile0.Text
        SetDelay(p.Audio0)
        Calc.SetAudioBitrateFromFile(p.Audio0)
        lAudioBitrate.Text = CInt(Calc.GetAudioBitrate).ToString
        tbSize_TextChanged(Nothing, Nothing)
    End Sub

    Public Sub tbAudioFile1_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbAudioFile1.TextChanged
        p.Audio1.File = tbAudioFile1.Text
        SetDelay(p.Audio1)
        Calc.SetAudioBitrateFromFile(p.Audio1)
        lAudioBitrate.Text = CInt(Calc.GetAudioBitrate).ToString
        tbSize_TextChanged(Nothing, Nothing)
    End Sub

    Public Sub SetDelay(ByVal settings As AudioSettings)
        If Not TypeOf settings.Profile Is MuxAudioProfile Then
            settings.Delay = ExtractDelay(settings.File)
        End If
    End Sub

    Public Sub bSkip_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bNext.Click
        If Not CanIgnoreTip Then
            Msg.Show("The current assistant instruction or warning cannot be skipped.", MsgIcon.Warning)
            Exit Sub
        End If

        If Not p.SkippedAssistantTips.Contains(CurrentAssistantTipKey) Then
            p.SkippedAssistantTips.Add(CurrentAssistantTipKey)
        End If

        If lTip.Text = AssistantOkMessage Then
            StartEncoding()
        Else
            Assistant()
        End If
    End Sub

    Private Sub StartEncoding()
        If Paths.VerifyRequirements() = False Then
            Exit Sub
        End If

        Dim aborted As Boolean

        Try
            Encode()
        Catch ex As AbortException
            aborted = True
        Catch ex As Exception
            Throw
        End Try

        OpenProject(g.ProjectPath, False)
        ProcessForm.CloseProcessForm()

        If Not aborted Then
            g.ShutdownPC()
        End If
    End Sub

    Private Sub Prepare()
        For Each i As Preparer In p.Preparers
            If Not i.Active Then Continue For

            If i.Input.Contains(Filepath.GetExtNoDot(p.SourceFile)) Then
                Preparer.ActivePreparer = i

                If Not Paths.VerifyRequirements Then
                    Throw New AbortException
                End If

                i.Run()
                Refresh()

                For Each iExt As String In i.VideoOutput
                    For Each iFile As String In Directory.GetFiles( _
                        Filepath.GetDir(p.SourceFile), "*." + iExt)

                        If g.BelongsToSource(iFile) Then
                            p.SourceFile = Filepath.GetDirAndNameNoExt(p.SourceFile) + "." + iExt
                            p.SourceFiles.Clear()
                            p.SourceFiles.Add(p.SourceFile)
                            tbSource.Text = p.SourceFile
                            Exit For
                        End If
                    Next
                Next

                For Each iExt As String In i.AudioOutput
                    For Each iFile As String In Directory.GetFiles( _
                        Filepath.GetDir(p.SourceFile), "*." + iExt)

                        If g.BelongsToSource(iFile) Then
                            p.Audio0.File = Filepath.GetDirAndNameNoExt(p.SourceFile) + "." + iExt
                            tbAudioFile0.Text = p.Audio0.File
                            Exit For
                        End If
                    Next
                Next
            End If
        Next

        Preparer.ActivePreparer = Nothing
    End Sub

    Public Sub tbSource_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles tbSource.DoubleClick
        OpenFileToolStripMenuItem.PerformClick()
    End Sub

    <GenericMenuMethod("Open Project", "Opens a project. Please press the right mouse button for help about projects.", "Projects")> _
    Public Sub OpenProjectFile()
        Dim d As New OpenFileDialog
        d.Filter = "Project Files|*.rip"
        d.ShowDialog()

        If Filepath.GetExt(d.FileName) = ".rip" Then
            OpenProject(d.FileName)
        End If

        d.Dispose()
    End Sub

    <GenericMenuMethod("Open Settings Dialog", "Opens the settings dialog.")> _
    Public Sub OpenSettingsDialog( _
        <Name("Section"), _
        Description("Name of the section to be shown.")> _
        ByVal section As String)

        Dim access As String
        Dim f As New SettingTreeViewForm("Settings")

        access = Paths.SettingsDir
        Dim settingsDir As String = RegistryHelp.CurrentUser.GetApplicationString("SettingsDir")
        Dim settingsDirBag As New SettingBag(Of String)(settingsDir)
        f.SettingTreeView.AddSetting(New FolderBrowserTreeNodeSetting("Settings Directory", "General", settingsDirBag, "Directory where StaxRip saves settings. The path may be relative to the startup path."))

        f.SettingTreeView.AddSetting(New ComboboxTreeNodeSetting(Of Integer)("Minimal Width", "General/Resolution Slider", s.ResizeSliderMin, "Minimal value of the resize slider in the main dialog.", 160, 320))
        f.SettingTreeView.AddSetting(New ComboboxTreeNodeSetting(Of Integer)("Maximal Width", "General/Resolution Slider", s.ResizeSliderMax, "Maximal value of the resize slider in the main dialog.", 720, 1280, 1920))

        f.SettingTreeView.AddSetting(New CheckBoxTreeNodeSetting("Run with minimized window", "External Applications", s.RunAppsMinimized, "Runs applications with minimized window."))

        Dim priority As ComboboxTreeNodeSetting(Of ProcessPriorityClass) = New ComboboxTreeNodeSetting(Of ProcessPriorityClass)("Process Priority", "External Applications", s.ProcessPriority, "Process priority of the applications StaxRip launches.")
        priority.ClearItems()
        priority.AddItem("Real Time", ProcessPriorityClass.RealTime)
        priority.AddItem("High", ProcessPriorityClass.High)
        priority.AddItem("Above Normal", ProcessPriorityClass.AboveNormal)
        priority.AddItem("Normal", ProcessPriorityClass.Normal)
        priority.AddItem("Below Normal", ProcessPriorityClass.BelowNormal)
        priority.AddItem("Idle", ProcessPriorityClass.Idle)
        f.SettingTreeView.AddSetting(priority)

        access = Paths.DownloadDir + Paths.ExtractDir
        f.SettingTreeView.AddSetting(New FolderBrowserTreeNodeSetting("Download Directory", "External Applications", s.DownloadDir, "Directory where external applications get downloaded. The path may be relative to the startup path."))
        f.SettingTreeView.AddSetting(New FolderBrowserTreeNodeSetting("Install Directory", "External Applications", s.ExtractDir, "Directory where downloaded zip archieves that don't have a installer get extracted. The path may be relative to the startup path."))

        Dim pluginDir As String = Paths.AviSynthPluginsDir
        Dim pluginDirBag As New SettingBag(Of String)(pluginDir)
        f.SettingTreeView.AddSetting(New FolderBrowserTreeNodeSetting("AviSynth Plugin Directory", "System", pluginDirBag, "The directory AviSynth uses to auto load plugins."))

        f.SettingTreeView.AddSetting(New TextBoxTreeNodeSetting("YV12 Decoder", "System", s.YV12Decoder, Nothing))

        f.SettingTreeView.ExpandNode(section)

        If f.ShowDialog() = Windows.Forms.DialogResult.OK Then
            RegistryHelp.CurrentUser.SetApplicationValue("SettingsDir", settingsDirBag.Value)
            RegistryHelp.LocalMachine.SetValue("SOFTWARE\AviSynth", "plugindir2_5", pluginDirBag.Value)
        End If

        f.Dispose()
        WhenSettingsChange()
        UpdateControls()
    End Sub

    'obsolete
    <GenericMenuMethod("Execute File", "Executes using file and arguments.")> _
    Public Sub Execute( _
        <Name("File"), _
        Description("Shell supported commands e.g. applications, files, directories, websites etc."), _
        Editor(GetType(OpenFileDialogEditor), GetType(UITypeEditor))> _
        ByVal file As String, _
        <Name("Arguments"), _
        Description("Arguments passed to the application.")> _
        ByVal arguments As String)

        Using pw As New ProcessWrapper
            pw.File = Macro.Solve(file)
            pw.Arguments = Macro.Solve(arguments)
            pw.Start()
        End Using
    End Sub

    <GenericMenuMethod("Execute Command Line", "Executes a command line.")> _
    Public Sub ExecuteCL( _
        <Name("Command Line"), _
        Description("Command Line to be executed."), _
        Editor(GetType(CLTypeEditor), GetType(UITypeEditor))> _
        ByVal commandLines As String)

        For Each i As String In StringHelp.SplitLines(Macro.Solve(commandLines))
            Using pw As New ProcessWrapper
                pw.CommandLine = i
                pw.Start()
            End Using
        Next
    End Sub

    <GenericMenuMethod("Save Project", "Saves the current project. Please press the right mouse button for help about projects.", "Projects")> _
    Public Sub SaveProject()
        If g.ProjectPath Is Nothing Then
            ShowSaveDialog()
        Else
            SaveProject(g.ProjectPath)
        End If
    End Sub

    <GenericMenuMethod("Save Project As", "Saves the current project using the File Save Dialog. Please press the right mouse button for help about projects.", "Projects")> _
    Public Sub SaveProjectAs()
        ShowSaveDialog()
    End Sub

    <GenericMenuMethod("Save Project As Template", "Saves the current project as template project. Please press the right mouse button for help about projects.", "Projects")> _
    Public Sub SaveProjectAsTemplate()
        If p.SourceFile = "" Then
            Using d As New SaveFileDialog
                d.FileName = "Untitled"
                d.DefaultExt = "rip"
                d.Filter = "Project Files|*.rip"
                d.InitialDirectory = Paths.TemplateDir

                If d.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    SaveProject(d.FileName)
                    UpdateTemplateProjectsMenuItems()
                End If
            End Using

            UpdateTemplateProjectsMenuItems()
        Else
            Msg.Show("A template project cannot be created after a source file was opened.", MsgIcon.Warning)
        End If
    End Sub

    <GenericMenuMethod("Load Default Project", "Loads the default project. Please press the right mouse button for help about projects.", "Projects")> _
    Public Sub LoadDefaultProjectFile()
        OpenProject(Paths.DefaultProjectPath)
    End Sub

    <GenericMenuMethod("Save Default Project", "Overwrites the default project with the current project. Please press the right mouse button for help about projects.", "Projects")> _
    Public Sub SaveDefaultProjectFile()
        If p.SourceFile = "" Then
            SaveProject(Paths.DefaultProjectPath)
            Assistant()
        Else
            Msg.Show("A template project cannot be created after a source file was opened.", MsgIcon.Warning)
        End If
    End Sub

    <GenericMenuMethod("Exit Application", "Exits the application.")> _
    Public Sub ExitStaxRip()
        Close()
    End Sub

    <GenericMenuMethod("Open External Applications Dialog", "Opens a dialog to manage external applications.")> _
    Public Sub OpenExternalApplicationsDialog()
        Dim f As New ExternalApplicationsForm

        Dim found As Boolean

        If s.StringDictionary.ContainsKey("RecentExternalApplicationControl") Then
            For Each i As Package In Paths.Packages.Values
                If i.Name = s.StringDictionary("RecentExternalApplicationControl") Then
                    f.ShowPackage(i)
                    found = True
                    Exit For
                End If
            Next
        End If

        If Not found Then
            f.ShowPackage(Paths.Packages("XviD"))
        End If

        f.ShowDialog()
        f.Dispose()
    End Sub

    <GenericMenuMethod("Open Encoder Profiles Dialog", "Opens a dialog to manage encoder profiles.")> _
    Public Sub OpenEncoderProfilesDialog()
        Dim f As New ProfilesForm("Encoder Profiles", s.VideoEncoderProfiles, AddressOf LoadVideoEncoder, AddressOf GetNewVideoEncoderProfile)

        If f.ShowDialog() = Windows.Forms.DialogResult.OK Then
            PopulateDynamicMenu("Encoder")
        End If

        f.Dispose()
    End Sub

    <GenericMenuMethod("Open Muxer Profiles Dialog", "Opens a dialog to manage Muxer profiles.")> _
    Public Sub OpenMuxerProfilesDialog()
        If p.VideoEncoder.OpenMuxerProfilesDialog() = Windows.Forms.DialogResult.OK Then
            PopulateDynamicMenu("Muxer")
        End If

        Assistant()
    End Sub

    Private Sub LoadVideoEncoder(ByVal profile As Profile)
        p.VideoEncoder = DirectCast(ObjectHelp.GetCopy(profile), VideoEncoder)
        p.VideoEncoder.Muxer.Init()

        tbTargetPath.Text = Filepath.GetChangeExt(p.TargetFile, p.VideoEncoder.Muxer.GetExtension)
        OnLoadEncoder()
        RecalcBitrate()
        Assistant()
    End Sub

    Public Sub RecalcBitrate()
        tbSize_TextChanged(Nothing, Nothing)
    End Sub

    Private Function GetNewVideoEncoderProfile() As Profile
        Dim sb As New SelectionBox(Of VideoEncoder)
        sb.Title = "New Profile"
        sb.Text = Strings.AddProfile

        sb.AddItem("Current Project", p.VideoEncoder)

        For Each i As VideoEncoder In VideoEncoder.GetDefaults()
            sb.AddItem(i)
        Next

        If sb.Show = Windows.Forms.DialogResult.OK Then
            Return sb.SelecteItem
        End If

        Return Nothing
    End Function

    <GenericMenuMethod("Reset Default Project", "Resets the default project. Please press the right mouse button for help about projects.", "Projects")> _
    Public Sub ResetDefaultProject()
        If Msg.Show("Please confirm to reset the default project.", _
            MsgIcon.Question, MessageBoxButtons.OKCancel) = Windows.Forms.DialogResult.OK Then

            Dim path As String = Paths.DefaultProjectPath

            If File.Exists(path) Then
                File.Delete(path)
            End If

            If Msg.Show("The default project was reset. Do you want to load it now?", _
                MsgIcon.Question, MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then

                OpenProject(path)
            End If
        End If
    End Sub

    <GenericMenuMethod("Dynamic Menu Item", Nothing)> _
    Public Sub DynamicMenuItem(<Name("Name")> ByVal t As String)
    End Sub

    Public Sub PopulateDynamicMenuItem(ByVal ic As ToolStripItemCollection, ByVal profiles As IList, ByVal profilesDialog As SubDelegate, ByVal loadProfile As ParamDelegate(Of Profile))
        Dim dic As New Dictionary(Of String, List(Of Profile))

        For Each i As Profile In profiles
            Dim group As String

            If i.Name.Contains(" - ") Then
                group = StringHelp.GetLeft(i.Name, " - ")
            Else
                group = i.Name
            End If

            If Not dic.ContainsKey(group) Then
                dic(group) = New List(Of Profile)
            End If

            dic(group).Add(i)
        Next

        For Each i As String In dic.Keys
            If dic(i).Count > 1 Then
                Dim root As New ToolStripMenuItem(i)
                ic.Add(root)

                For Each iProfile As Profile In dic(i)
                    root.DropDownItems.Add(New ParamToolStripMenuItem(Of Profile)(iProfile.Name, loadProfile, iProfile))
                Next
            End If
        Next

        For Each i As String In dic.Keys
            If dic(i).Count <= 1 Then
                For Each iProfile As Profile In dic(i)
                    ic.Add(New ParamToolStripMenuItem(Of Profile)(iProfile.Name, loadProfile, iProfile))
                Next
            End If
        Next

        If Not profilesDialog Is Nothing Then
            ic.Add(New ToolStripSeparator)
            ic.Add(New SubToolStripMenuItem("Edit...", profilesDialog))
        End If
    End Sub

    Public Sub PopulateDynamicMenu(ByVal profileType As String)
        For Each i As ExtendedToolStripMenuItem In GenericMenu.MenuItems
            If i.GenericMenuItem.MethodName = "DynamicMenuItem" AndAlso _
                i.GenericMenuItem.Parameters(0).ToString = profileType Then

                i.DropDownItems.Clear()

                Select Case profileType
                    Case "Encoder"
                        PopulateDynamicMenuItem(i.DropDownItems, s.VideoEncoderProfiles, AddressOf OpenEncoderProfilesDialog, AddressOf LoadVideoEncoder)
                    Case "Muxer"
                        PopulateDynamicMenuItem(i.DropDownItems, s.MuxerProfiles, AddressOf OpenMuxerProfilesDialog, AddressOf LoadMuxer)
                    Case "Audio 1"
                        PopulateDynamicMenuItem(i.DropDownItems, s.AudioProfiles, Nothing, AddressOf LoadAudioProfile0)

                        i.DropDownItems.Add(New ToolStripSeparator)
                        i.DropDownItems.Add(New ParamToolStripMenuItem(Of Integer)("Edit...", AddressOf OpenAudioProfilesDialog, 0))
                    Case "Audio 2"
                        PopulateDynamicMenuItem(i.DropDownItems, s.AudioProfiles, Nothing, AddressOf LoadAudioProfile1)

                        i.DropDownItems.Add(New ToolStripSeparator)
                        i.DropDownItems.Add(New ParamToolStripMenuItem(Of Integer)("Edit...", AddressOf OpenAudioProfilesDialog, 1))
                    Case "Filter Setup"
                        PopulateDynamicMenuItem(i.DropDownItems, s.AviSynthProfiles, AddressOf OpenAviSynthProfilesDialog, AddressOf LoadAviSynthProfile)
                End Select

                Exit For
            End If
        Next
    End Sub

    <GenericMenuMethod("Add Foreced Subtitle", "Adds a forced subtitle.")> _
    Public Sub AddForecedSubtitle()
        Dim f As New OpenFileDialog
        f.Filter = "Subtitle File|*.idx;*.srt;*.ssa;*.smi;*.ass|All Files|*.*"
        f.InitialDirectory = s.LastSourceDir

        If f.ShowDialog = Windows.Forms.DialogResult.OK Then
            If Filepath.GetExt(f.FileName) = ".idx" Then
                Dim idx As New IDX
                idx.Path = f.FileName

                Dim sb As New SelectionBox(Of Subtitle)
                sb.Title = "Language"
                sb.Text = "Please select a language."

                For Each i As Subtitle In idx.Subtitles
                    sb.AddItem(i.Language.Name, i)
                Next

                If sb.Show = Windows.Forms.DialogResult.Cancel Then
                    Exit Sub
                End If

                StringHelp.WriteFile(f.FileName, Regex.Replace(StringHelp.ReadFile(f.FileName), "langidx: \d+", "langidx: " + sb.SelecteItem.Index.ToString))
            End If

            Dim filter As New AviSynthFilter

            filter.Category = "Subtitle"
            filter.Name = Filepath.GetNameWithExt(f.FileName)
            filter.Active = True

            If Filepath.GetExt(f.FileName) = ".idx" Then
                filter.Script = "VobSub(""" + f.FileName + """)"
            Else
                filter.Script = "TextSub(""" + f.FileName + """)"
            End If

            p.TargetAVSDoc.Filters.Add(filter)
            AviSynthListView.Load()
            Paths.VerifyRequirements()
        End If
    End Sub

    <GenericMenuMethod("Open Crop Dialog", "Opens the crop dialog. The crop dialog allows to crop borders.")> _
    Public Sub OpenCropDialog()
        If Not Paths.VerifyRequirements Then Exit Sub
        If Not g.IsValidSource Then Exit Sub

        If Not p.TargetAVSDoc.Contains("Crop(%crop_left%,%crop_top%,-%crop_right%,-%crop_bottom%)") Then
            Msg.Show("The current filter setup don't allow cropping.", "No Cropping", MsgIcon.Warning)
            Exit Sub
        End If

        Dim f As New CropForm
        f.ShowDialog()
        f.Dispose()

        UpdateControls()
        Assistant()
    End Sub

    <GenericMenuMethod("Opens Preview", "Opens a dialog to preview or cut the video.")> _
    Public Sub OpenPreview()
        If Not Paths.VerifyRequirements Then Exit Sub
        If Not g.IsValidSource Then Exit Sub

        Dim cutting As AviSynthFilter = p.TargetAVSDoc.GetFilter("Cutting")

        If Not cutting Is Nothing Then
            p.TargetAVSDoc.Filters.Remove(cutting)
            g.MainForm.AviSynthListView.Load()
            g.MainForm.SetTargetLength(p.TargetAVSDoc.GetSeconds)
        End If

        Dim f As New PreviewForm(p.TargetAVSDoc)
        f.Owner = g.MainForm
        f.Show()
    End Sub

    <GenericMenuMethod("Open Main Menu Editor", "Opens a dialog to configure the main menu.")> _
    Public Sub OpenMainMenuEditor()
        s.GenericMenuMainForm = GenericMenu.Edit()
        InitMainMenuDynamic()
        UpdateRecentProjectsMenuItems("")
        UpdateTemplateProjectsMenuItems()
    End Sub

    <GenericMenuMethod("Open Jobs Dialog", "Opens a dialog to manage batch jobs.")> _
    Public Sub OpenJobsDialog()
        Dim f As New JobsForm(Me)
        f.ShowDialog()
        f.Dispose()

        If f.Start Then
            For Each i As String In (New Dictionary(Of String, Boolean)(s.Jobs)).Keys
                If s.Jobs(i) Then
                    g.MainForm.OpenProject(i, False)

                    Try
                        Encode()
                    Catch ex As AbortException
                        OpenProject(g.ProjectPath, False)
                        ProcessForm.CloseProcessForm()
                        Exit Sub
                    Catch ex As Exception
                        Throw
                    End Try

                    s.Jobs.Remove(i)
                End If
            Next

            OpenProject(g.ProjectPath, False)
            ProcessForm.CloseProcessForm()
            g.ShutdownPC()
        End If
    End Sub

    <GenericMenuMethod("Open Options Dialog", "Opens a dialog to configure project options.")> _
    Public Sub OpenOptionsDialog()
        Dim f As New OptionsForm

        If f.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Assistant()
        End If

        f.Dispose()
    End Sub

    <GenericMenuMethod("Open AviSynth Profiles Dialog", "Opens a dialog to configure AviSynth profiles.")> _
    Public Sub OpenAviSynthProfilesDialog()
        Dim f As New ProfilesForm("AviSynth Profiles", s.AviSynthProfiles, AddressOf LoadAviSynthProfile, AddressOf GetAVSDocAsProfile)

        If f.ShowDialog() = Windows.Forms.DialogResult.OK Then
            PopulateDynamicMenu("Filter Setup")
        End If

        f.Dispose()
    End Sub

    <GenericMenuMethod("Open AviSynth Filter Profiles Dialog", "Opens a dialog to configure AviSynth filter profiles.")> _
    Public Sub OpenAviSynthFilterProfilesDialog()
        Dim le As New ListEditor
        le.EditValue(s.AviSynthCategories, GetType(AviSynthCategory), "Categories")

        For Each i As AviSynthCategory In s.AviSynthCategories
            For Each iFilter As AviSynthFilter In i.Filters
                iFilter.Active = True
                iFilter.Category = i.Name
            Next
        Next
    End Sub

    <GenericMenuMethod("Open Help Main Dialog", "Opens the help of the dialog.")> _
    Public Sub OpenHelpMainDialog()
        Dim f As New HelpForm()
        f.Document.WriteStart("Main Dialog")
        f.Document.WriteParagraph("The main dialog organizes the application's functionality in a user friendly manner. Please read the [[help.htm|general help]] to get started with StaxRip.")
        f.Document.WriteTips(GenericMenu.GetTips)
        f.Document.WriteTable("Shortcut Keys", GenericMenu.GetKeys, False)
        f.Show()
    End Sub

    <GenericMenuMethod("Open Help Topic", Nothing)> _
    Public Sub OpenHelpTopic( _
        <Name("Help Topic"), _
        Description("Name of the help topic to be opened.")> ByVal topic As String)

        g.ShowHelpTopic(topic)
    End Sub

    <GenericMenuMethod("Open Help File", Nothing)> _
    Public Sub OpenHelpURL(<Name("URL"), Description("URL of a Internet Explorer supported document.")> ByVal url As String)
        Dim f As New HelpForm(Macro.Solve(url))
        f.Show()
    End Sub

    <GenericMenuMethod("Send Report Bug", "Send a bug report by email.")> _
    Public Sub SendBugReport()
        g.SendBugReport(Nothing)
    End Sub

    Public Shared Function GetDefaultMainMenu() As GenericMenuItem
        Dim ret As GenericMenuItem = New GenericMenuItem("Root")

        Dim file As New GenericMenuItem("File")
        ret.SubItems.Add(file)

        Dim openProject As New GenericMenuItem("Open Project...")
        openProject.KeyData = Keys.O Or Keys.Control
        openProject.MethodName = "OpenProjectFile"
        file.SubItems.Add(openProject)

        Dim saveProject As New GenericMenuItem("Save Project")
        saveProject.KeyData = Keys.S Or Keys.Control
        saveProject.MethodName = "SaveProject"
        file.SubItems.Add(saveProject)

        Dim saveAsProject As New GenericMenuItem("Save Project As...")
        saveAsProject.MethodName = "SaveProjectAs"
        file.SubItems.Add(saveAsProject)

        Dim saveProjectAsTemplate As New GenericMenuItem("Save Project As Template...")
        saveProjectAsTemplate.MethodName = "SaveProjectAsTemplate"
        file.SubItems.Add(saveProjectAsTemplate)

        file.SubItems.Add(New GenericMenuItem("-"))

        Dim recentProjects As New GenericMenuItem("Recent Projects")
        recentProjects.MethodName = "DynamicMenuItem"
        recentProjects.Parameters.Add("Recent Projects")
        file.SubItems.Add(recentProjects)

        Dim templateProjects As New GenericMenuItem("Template Projects")
        templateProjects.MethodName = "DynamicMenuItem"
        templateProjects.Parameters.Add("Template Projects")
        file.SubItems.Add(templateProjects)

        Dim defaultProject As New GenericMenuItem("Default Project")
        file.SubItems.Add(defaultProject)

        Dim loadDefaultProject As New GenericMenuItem("Load")
        loadDefaultProject.MethodName = "LoadDefaultProjectFile"
        defaultProject.SubItems.Add(loadDefaultProject)

        Dim saveDefaultProject As New GenericMenuItem("Save")
        saveDefaultProject.MethodName = "SaveDefaultProjectFile"
        defaultProject.SubItems.Add(saveDefaultProject)

        Dim resetDefaultProject As New GenericMenuItem("Reset")
        resetDefaultProject.MethodName = "ResetDefaultProject"
        defaultProject.SubItems.Add(resetDefaultProject)

        file.SubItems.Add(New GenericMenuItem("-"))

        Dim exitMenuItem As New GenericMenuItem("Exit")
        exitMenuItem.KeyData = Keys.Escape
        exitMenuItem.MethodName = "ExitStaxRip"
        file.SubItems.Add(exitMenuItem)

        Dim view As New GenericMenuItem("View")
        ret.SubItems.Add(view)

        Dim crop As New GenericMenuItem("Crop...")
        crop.KeyData = Keys.F4
        crop.MethodName = "OpenCropDialog"
        view.SubItems.Add(crop)

        Dim preview As New GenericMenuItem("Preview...")
        preview.KeyData = Keys.F5
        preview.MethodName = "OpenPreview"
        view.SubItems.Add(preview)

        Dim jobs As New GenericMenuItem("Jobs...")
        jobs.KeyData = Keys.F6
        jobs.MethodName = "OpenJobsDialog"
        view.SubItems.Add(jobs)

        Dim options As New GenericMenuItem("Project Options...")
        options.KeyData = Keys.F7
        options.MethodName = "OpenOptionsDialog"
        view.SubItems.Add(options)

        Dim profiles As New GenericMenuItem("Profiles")
        ret.SubItems.Add(profiles)

        Dim encoderRoot As New GenericMenuItem("Encoder")
        encoderRoot.MethodName = "DynamicMenuItem"
        encoderRoot.Parameters.Add("Encoder")
        profiles.SubItems.Add(encoderRoot)

        Dim muxerRoot As New GenericMenuItem("Container")
        muxerRoot.MethodName = "DynamicMenuItem"
        muxerRoot.Parameters.Add("Muxer")
        profiles.SubItems.Add(muxerRoot)

        profiles.SubItems.Add(New GenericMenuItem("-"))

        Dim audio1Root As New GenericMenuItem("Audio 1")
        audio1Root.MethodName = "DynamicMenuItem"
        audio1Root.Parameters.Add("Audio 1")
        profiles.SubItems.Add(audio1Root)

        Dim audio2Root As New GenericMenuItem("Audio 2")
        audio2Root.MethodName = "DynamicMenuItem"
        audio2Root.Parameters.Add("Audio 2")
        profiles.SubItems.Add(audio2Root)

        profiles.SubItems.Add(New GenericMenuItem("-"))

        Dim scriptRoot As New GenericMenuItem("Filter Setup")
        scriptRoot.MethodName = "DynamicMenuItem"
        scriptRoot.Parameters.Add("Filter Setup")
        profiles.SubItems.Add(scriptRoot)

        Dim tools As New GenericMenuItem("Tools")
        ret.SubItems.Add(tools)

        Dim settings As New GenericMenuItem("Settings...")
        settings.MethodName = "OpenSettingsDialog"
        settings.Parameters.Add("")
        tools.SubItems.Add(settings)

        Dim externalApplicationsDialog As New GenericMenuItem("External Applications...")
        externalApplicationsDialog.MethodName = "OpenExternalApplicationsDialog"
        tools.SubItems.Add(externalApplicationsDialog)

        Dim forcedSubtitles As New GenericMenuItem("Add Forced Subtitle...")
        forcedSubtitles.MethodName = "AddForecedSubtitle"
        tools.SubItems.Add(forcedSubtitles)

        Dim directories As New GenericMenuItem("Directories")
        tools.SubItems.Add(directories)

        Dim sourceFileDirectory As New GenericMenuItem("Source file directory")
        sourceFileDirectory.MethodName = "ExecuteCL"
        sourceFileDirectory.Parameters.Add("""%source_dir%""")
        directories.SubItems.Add(sourceFileDirectory)

        Dim targetFileDirectory As New GenericMenuItem("Target file directory")
        targetFileDirectory.MethodName = "ExecuteCL"
        targetFileDirectory.Parameters.Add("""%target_dir%""")
        directories.SubItems.Add(targetFileDirectory)

        Dim menuEditor As New GenericMenuItem("Edit Menu...")
        menuEditor.MethodName = "OpenMainMenuEditor"
        tools.SubItems.Add(menuEditor)

        Dim help As New GenericMenuItem("Help")
        ret.SubItems.Add(help)

        Dim helpGeneral As New GenericMenuItem("Help General...")
        helpGeneral.KeyData = Keys.F1
        helpGeneral.MethodName = "OpenHelpTopic"
        helpGeneral.Parameters.Add("help")
        help.SubItems.Add(helpGeneral)

        Dim helpDialog As New GenericMenuItem("Help Main Dialog...")
        helpDialog.KeyData = Keys.F2
        helpDialog.MethodName = "OpenHelpMainDialog"
        help.SubItems.Add(helpDialog)

        Dim support As New GenericMenuItem("Support...")
        support.KeyData = Keys.F3
        support.MethodName = "OpenHelpTopic"
        support.Parameters.Add("support")
        help.SubItems.Add(support)

        Dim changelog As New GenericMenuItem("Changelog...")
        changelog.MethodName = "OpenHelpURL"
        changelog.Parameters.Add("%application_dir%Documents\changelog.htm")
        help.SubItems.Add(changelog)

        Dim sendBugReport As New GenericMenuItem("Send Bug Report...")
        sendBugReport.MethodName = "SendBugReport"
        help.SubItems.Add(sendBugReport)

        Dim info As New GenericMenuItem("Info...")
        info.MethodName = "OpenHelpURL"
        info.Parameters.Add("%application_dir%Documents\info.htm")
        help.SubItems.Add(info)

        Return ret
    End Function

    Private Sub tbResize_Scroll(ByVal sender As Object, ByVal e As EventArgs) Handles tbResize.Scroll
        tbTargetWidth.Text = CInt(s.ResizeSliderMin.Value + tbResize.Value * 16).ToString
        tbTargetHeight.Text = Calc.FixMod(CInt(p.TargetWidth / Calc.GetAR()), 16).ToString()
    End Sub

    Public Function GetAspectRatioError() As Double
        Return (Calc.GetAR() / (p.TargetWidth / p.TargetHeight)) * 100 - 100
    End Function

    Private Function GetNextMod(ByVal val As Integer, ByVal step1 As Integer) As Integer
        Do
            val += 1
        Loop Until val Mod step1 = 0

        Return val
    End Function

    Private Function GetPreviousMod(ByVal val As Integer, ByVal step1 As Integer) As Integer
        Do
            val -= 1
        Loop Until val Mod step1 = 0

        Return val
    End Function

    Private Sub tbBitrate_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles tbBitrate.KeyDown
        If e.KeyData = Keys.PageUp Then
            tbBitrate.Text = GetPreviousMod(StringHelp.GetInt(tbBitrate.Text, 1), 50).ToString
        ElseIf e.KeyData = Keys.PageDown Then
            tbBitrate.Text = GetNextMod(StringHelp.GetInt(tbBitrate.Text, 1), 50).ToString
        End If
    End Sub

    Private Sub tbSize_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles tbSize.KeyDown
        Dim l As Integer

        Select Case p.TargetSeconds
            Case Is > 80 * 60
                l = 50
            Case Is > 40 * 60
                l = 20
            Case Is > 20 * 60
                l = 10
            Case Is > 10 * 60
                l = 5
            Case Else
                l = 1
        End Select

        If e.KeyData = Keys.PageUp Then
            tbSize.Text = GetPreviousMod(StringHelp.GetInt(tbSize.Text, 1), l).ToString
        ElseIf e.KeyData = Keys.PageDown Then
            tbSize.Text = GetNextMod(StringHelp.GetInt(tbSize.Text, 1), l).ToString
        End If
    End Sub

    Private InputList As New List(Of Control)

    Public Sub SetText(ByVal c As Control, ByVal value As String)
        If Not InputList.Contains(c) Then
            c.Text = value
        End If
    End Sub

    Public Sub EndInput(ByVal c As Control)
        InputList.Remove(c)

        If InputList.Count = 0 Then
            Assistant()
        End If
    End Sub

    Public Sub tbSize_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbSize.TextChanged
        If tbSize.Text.Length > 5 Then
            tbSize.Text = tbSize.Text.Substring(0, 5)
        End If

        If Not IntegerHelp.IsInteger(tbSize.Text) Then
            tbSize.Text = p.Size.ToString
        End If

        InputList.Add(tbSize)

        p.Size = CInt(tbSize.Text)

        If Not InputList.Contains(tbBitrate) Then
            tbBitrate.Text = CInt(Calc.GetVideoBitrate).ToString
        End If

        UpdateControls()
        Assistant()

        EndInput(tbSize)
    End Sub

    Public Sub tbBitrate_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbBitrate.TextChanged
        If tbBitrate.Text.Length > 5 Then
            tbBitrate.Text = tbBitrate.Text.Substring(0, 5)
        End If

        If Not IntegerHelp.IsInteger(tbBitrate.Text) Then
            tbBitrate.Text = p.VideoBitrate.ToString
        End If

        InputList.Add(tbBitrate)
        p.VideoBitrate = CInt(tbBitrate.Text)

        If Not InputList.Contains(tbSize) Then
            tbSize.Text = CInt((Calc.GetVideoKBytes() + Calc.GetAudioKBytes() + Calc.GetOverheadAndSubtitlesKBytes()) / 1024).ToString
        End If

        UpdateControls()
        Assistant()

        EndInput(tbBitrate)
    End Sub

    Public Sub tbTargetWidth_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbTargetWidth.TextChanged
        p.TargetWidth = StringHelp.GetInt(tbTargetWidth.Text, p.TargetWidth)
        UpdateControls()
        Assistant()
    End Sub

    Public Sub tbTargetHeight_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbTargetHeight.TextChanged
        p.TargetHeight = StringHelp.GetInt(tbTargetHeight.Text, p.TargetHeight)
        UpdateControls()
        Assistant()
    End Sub

    Private Sub cb169_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cb169.CheckedChanged
        p.Source169 = cb169.Checked
        tbTargetHeight.Text = Calc.FixMod(CInt(p.TargetWidth / Calc.GetAR()), 16).ToString()
    End Sub

    Private Sub tbTargetWidth_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles tbTargetWidth.KeyDown
        If e.KeyData = Keys.Up Then
            e.Handled = True
            tbTargetWidth.Text = Calc.FixMod(p.TargetWidth + 16, 16).ToString()
        ElseIf e.KeyData = Keys.Down Then
            e.Handled = True
            tbTargetWidth.Text = Calc.FixMod(p.TargetWidth - 16, 16).ToString()
        End If
    End Sub

    Private Sub tbTargetHeight_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles tbTargetHeight.KeyDown
        If e.KeyData = Keys.Up Then
            e.Handled = True
            tbTargetHeight.Text = Calc.FixMod(p.TargetHeight + 16, 16).ToString()
        ElseIf e.KeyData = Keys.Down Then
            e.Handled = True
            tbTargetHeight.Text = Calc.FixMod(p.TargetHeight - 16, 16).ToString()
        End If
    End Sub

    Public Shared Function GetDefaultMenuSize() As GenericMenuItem
        Dim t As Type = GetType(MainForm)
        Dim ret As GenericMenuItem = New GenericMenuItem("Root")

        Dim size650 As New GenericMenuItem("650 MB")
        size650.MethodName = "SetSize"
        size650.Parameters.Add(650)
        ret.SubItems.Add(size650)

        Dim size700 As New GenericMenuItem("700 MB")
        size700.MethodName = "SetSize"
        size700.Parameters.Add(700)
        ret.SubItems.Add(size700)

        Dim size800 As New GenericMenuItem("800 MB")
        size800.MethodName = "SetSize"
        size800.Parameters.Add(800)
        ret.SubItems.Add(size800)

        Dim thirdDVD As New GenericMenuItem("1/3 DVD")
        thirdDVD.MethodName = "SetSize"
        thirdDVD.Parameters.Add(1493)
        ret.SubItems.Add(thirdDVD)

        ret.SubItems.Add(New GenericMenuItem("-"))

        Dim percent60 As New GenericMenuItem("60 %")
        percent60.MethodName = "SetPercent"
        percent60.Parameters.Add(60)
        ret.SubItems.Add(percent60)

        Dim percent70 As New GenericMenuItem("70 %")
        percent70.MethodName = "SetPercent"
        percent70.Parameters.Add(70)
        ret.SubItems.Add(percent70)

        Dim percent80 As New GenericMenuItem("80 %")
        percent80.MethodName = "SetPercent"
        percent80.Parameters.Add(80)
        ret.SubItems.Add(percent80)

        Dim percent90 As New GenericMenuItem("90 %")
        percent90.MethodName = "SetPercent"
        percent90.Parameters.Add(90)
        ret.SubItems.Add(percent90)

        ret.SubItems.Add(New GenericMenuItem("-"))

        Dim editMenu As New GenericMenuItem("Edit Menu...")
        editMenu.MethodName = "OpenSizeMenuEditor"
        ret.SubItems.Add(editMenu)

        Return ret
    End Function

    <GenericMenuMethod("Set Size", "Sets the size.")> _
    Public Sub SetSize(<Name("Target Size")> ByVal targetSize As Integer)
        tbSize.Text = targetSize.ToString
    End Sub

    <GenericMenuMethod("Set Bitrate", "Sets the bitrate according to the compressibility.")> _
    Public Sub SetPercent(<Name("Percent Value")> ByVal value As Integer)
        tbSize.Text = g.GetAutoSize(value).ToString
    End Sub

    <GenericMenuMethod("Open Size Menu Editor", "Opens the menu editor for the size menu.")> _
    Public Sub OpenSizeMenuEditor()
        s.GenericMenuSize = GenericMenuSize.Edit()
    End Sub

    Private Sub bSize_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bSize.Click
        UpdateSizeMenu()
        SizeContextMenuStrip.Show(bSize, 0, bSize.Height)
    End Sub

    Private Sub UpdateSizeMenu()
        For Each i As ExtendedToolStripMenuItem In GenericMenuSize.MenuItems
            If i.GenericMenuItem.MethodName = "SetPercent" Then
                i.Enabled = p.Compressibility > 0
            End If
        Next
    End Sub

    Private Function GetAVSDocAsProfile() As Profile
        Dim sb As New SelectionBox(Of TargetAviSynthDocument)

        sb.Title = "New Profile"
        sb.Text = Strings.AddProfile

        sb.AddItem("Current Project", p.TargetAVSDoc)

        For Each i As TargetAviSynthDocument In AviSynthDocument.GetDefaults
            sb.AddItem(i)
        Next

        If sb.Show = Windows.Forms.DialogResult.OK Then
            Return sb.SelecteItem
        End If

        Return Nothing
    End Function

    Private Function GetTargetAviSynthDocument() As AviSynthDocument
        Return p.TargetAVSDoc
    End Function

    Private Sub LoadAviSynthProfile(ByVal profileInterface As Profile)
        p.TargetAVSDoc = DirectCast(ObjectHelp.GetCopy(profileInterface), TargetAviSynthDocument)
        AviSynthListView.Load()
        Assistant()
    End Sub

    Private Sub GenericMenu_Topic(ByVal item As GenericMenuItem) Handles GenericMenu.Topic
        g.ShowHelpTopic(item.MethodItem.Attribute.Topic)
    End Sub

    Private Sub GenericMenu_Trigger(ByVal item As GenericMenuItem) Handles GenericMenu.Trigger
        Refresh()

        Select Case item.MethodName
            Case ""
            Case Else
                GenericMenu.Invoke(item)
        End Select
    End Sub

    Private Sub GenericMenuSize_Trigger(ByVal item As GenericMenuItem) Handles GenericMenuSize.Trigger
        GenericMenuSize.Invoke(item)
    End Sub

    Private Sub MainForm_ActivatedFirstTime() Handles MyBase.ActivatedFirstTime
        UpdateRecentProjectsMenuItems("")
        UpdateTemplateProjectsMenuItems()

        Dim files As New List(Of String)

        For Each i As CLIArg In CLIArg.GetArgs
            Try
                If Not i.IsFile AndAlso files.Count > 0 Then
                    Dim l As New List(Of String)(files)
                    OpenAnyFile(l)
                    files.Clear()
                End If

                If i.IsMatch("?", "h", "help") Then
                    Dim f As New HelpForm()
                    f.Owner = Me

                    f.Document.WriteStart("Command Line Help")
                    f.Document.WriteParagraph("StaxRip uses a similar command line syntax as the .NET framework tools as it simplifies development and usage. The arguments a processed sequentially in the order they appear in the command line.")

                    Dim l As New StringPairList

                    l.Add("<i>files</i>", "Opening files don't require a switch. Paths containing blanks must<br>be quoted of course and multible files separated with a blank.")
                    l.Add("-help, -h, -?", "Shows this help.")
                    l.Add("-template:<i>name</i>, -t:<i>name</i>", "Loads a template.")
                    l.Add("-standby", "Puts the PC into standby.")
                    l.Add("-shutdown", "Shuts the PC down.")
                    l.Add("-encode, -e", "Starts the encoding.")
                    l.Add("-exit", "Exits StaxRip")

                    f.Document.WriteTable("Switches", l, True)

                    f.Document.WriteElement("h2", "Examples")
                    f.Document.WriteParagraph("StaxRip C:\Movie\project.rip")
                    f.Document.WriteParagraph("StaxRip ""C:\Movie 2\project.rip""")
                    f.Document.WriteParagraph("StaxRip ""C:\Movie 2\VTS_01_1.VOB""")
                    f.Document.WriteParagraph("StaxRip ""C:\Movie 2\VTS_01_1.VOB"" ""C:\Movie 2\VTS_01_2.VOB""")
                    f.Document.WriteParagraph("StaxRip -template:DVB ""C:\Movie 2\capture.mpg"" -encode -standby")
                    f.Document.WriteParagraph("StaxRip -template:DVD ""C:\Movie 2\VTS_01_1.VOB"" ""C:\Movie 2\VTS_01_2.VOB"" -encode -shutdown")

                    f.WindowState = FormWindowState.Maximized
                    f.Show()
                ElseIf i.IsMatch("t", "template") Then
                    LoadProject(Paths.TemplateDir + i.GetString + ".rip")
                ElseIf i.IsMatch("standby") Then
                    g.ShutdownMode = ShutdownMode.Standby
                    g.ShutdownPC()
                ElseIf i.IsMatch("shutdown") Then
                    g.ShutdownMode = ShutdownMode.Shutdown
                    g.ShutdownPC()
                ElseIf i.IsMatch("e", "encode") Then
                    StartEncoding()
                ElseIf i.IsMatch("exit") Then
                    Close()
                ElseIf i.IsFile Then
                    files.Add(i.Value)
                Else
                    Throw New Exception
                End If
            Catch
                Msg.Show("Error parsing argument: " + i.Value, MsgIcon.Warning)
            End Try
        Next

        If files.Count > 0 Then
            OpenAnyFile(files)
        End If

        IsLoading = False
    End Sub

    Private Sub OnLoadEncoder()
        gbEncoder.Text = p.VideoEncoder.Name

        pEncoder.Controls.Add(p.VideoEncoder.EditControl)

        If pEncoder.Controls.Count > 1 Then
            pEncoder.Controls.RemoveAt(0)
        End If

        If TypeOf p.VideoEncoder.EditControl Is OptionListBox Then
            DirectCast(p.VideoEncoder.EditControl, OptionListBox).TipTarget = TipTarget
        End If

        UpdateEncoderStateRelatedControls()
    End Sub

    Public Sub UpdateEncoderStateRelatedControls()
        lSize.Visible = Not p.VideoEncoder.QualityMode
        tbSize.Visible = Not p.VideoEncoder.QualityMode
        bSize.Visible = Not p.VideoEncoder.QualityMode
        lBitrate.Visible = Not p.VideoEncoder.QualityMode
        tbBitrate.Visible = Not p.VideoEncoder.QualityMode
        lQuality.Visible = Not p.VideoEncoder.QualityMode
        lQualityValue.Visible = Not p.VideoEncoder.QualityMode
        lCompCheck.Visible = Not p.VideoEncoder.QualityMode
        lCompCheckValue.Visible = Not p.VideoEncoder.QualityMode
    End Sub

    Private Sub bOpenSourceFile_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bOpenSourceFile.Click
        cmsOpen.Show(bOpenSourceFile, 0, bOpenSourceFile.Height)
    End Sub

    Private Sub OpenFileToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles OpenFileToolStripMenuItem.Click
        Dim d As New OpenFileDialog
        d.Filter = FileDialogFilter.GetVideo()
        d.InitialDirectory = s.LastSourceDir

        If d.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Refresh()
            Dim list As New List(Of String)
            list.Add(d.FileName)
            OpenVideoSourceFiles(list)
        End If

        d.Dispose()
    End Sub

    Private Sub OpenFilesToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles OpenFilesToolStripMenuItem.Click
        Dim f As New SourceFilesForm(p.AutoSourceFiles)

        If f.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim list As New List(Of String)

            For Each i As String In f.lbFiles.Items
                list.Add(i)
            Next

            OpenVideoSourceFiles(list)
        End If

        f.Dispose()
    End Sub

    Private Sub bOpenSourceFile_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles bOpenSourceFile.Paint
        ButtonHelp.DrawDropDownGlyph(bOpenSourceFile, e.Graphics, HorizontalAlignment.Center)
    End Sub

    Private Sub LoadAudioProfile0(ByVal profile As Profile)
        p.Audio0.Profile = DirectCast(ObjectHelp.GetCopy(profile), AudioProfile)
        lAudioProfile0.Text = p.Audio0.Profile.Name
        Calc.SetAudioBitrateFromFile(p.Audio0)
        lAudioBitrate.Text = CInt(Calc.GetAudioBitrate).ToString
        tbSize_TextChanged(Nothing, Nothing)
        Assistant()
    End Sub

    Private Sub LoadAudioProfile1(ByVal profile As Profile)
        p.Audio1.Profile = DirectCast(ObjectHelp.GetCopy(profile), AudioProfile)
        lAudioProfile1.Text = p.Audio1.Profile.Name
        Calc.SetAudioBitrateFromFile(p.Audio1)
        lAudioBitrate.Text = CInt(Calc.GetAudioBitrate).ToString
        tbSize_TextChanged(Nothing, Nothing)
        Assistant()
    End Sub

    Public Function GetAudioProfile0() As Profile
        Return GetNewAudioProfile(p.Audio0.Profile)
    End Function

    Public Function GetAudioProfile1() As Profile
        Return GetNewAudioProfile(p.Audio1.Profile)
    End Function

    Public Function GetNewAudioProfile(ByVal currentProfile As AudioProfile) As AudioProfile
        Dim sb As New SelectionBox(Of AudioProfile)
        sb.Title = "New Profile"
        sb.Text = Strings.AddProfile

        sb.AddItem("Current Project", currentProfile)

        For Each i As AudioProfile In AudioProfile.GetDefaults(True)
            sb.AddItem(i)
        Next

        If sb.Show = Windows.Forms.DialogResult.OK Then
            Return sb.SelecteItem
        End If

        Return Nothing
    End Function

    Private Sub bAudioMenu0_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles bAudioMenu0.Paint
        ButtonHelp.DrawDropDownGlyph(bAudioMenu0, e.Graphics, HorizontalAlignment.Center)
    End Sub

    Private Sub bAudioMenu1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles bAudioMenu1.Paint
        ButtonHelp.DrawDropDownGlyph(bAudioMenu1, e.Graphics, HorizontalAlignment.Center)
    End Sub

    Public Sub tbAudioFile0_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles tbAudioFile0.DoubleClick
        Dim d As New OpenFileDialog

        d.Filter = FileDialogFilter.GetAudio()
        d.InitialDirectory = Filepath.GetDir(p.SourceFile)
        d.ShowDialog()

        If d.FileName <> "" Then
            tbAudioFile0.Text = d.FileName
        End If

        d.Dispose()
    End Sub

    Public Sub tbAudioFile1_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles tbAudioFile1.DoubleClick
        Dim d As New OpenFileDialog

        d.Filter = FileDialogFilter.GetAudio()
        d.InitialDirectory = Filepath.GetDir(p.SourceFile)
        d.ShowDialog()

        If d.FileName <> "" Then
            tbAudioFile1.Text = d.FileName
        End If

        d.Dispose()
    End Sub

    Private Sub bSize_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles bSize.Paint
        ButtonHelp.DrawDropDownGlyph(bSize, e.Graphics, HorizontalAlignment.Center)
    End Sub

    Private Sub lTip_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lTip.Click
        If Not AssistantMethod Is Nothing Then
            AssistantMethod.Invoke()
        End If
    End Sub

    Public Sub SetTargetLength(ByVal seconds As Integer)
        p.TargetSeconds = seconds
        lbTargetLength.Text = GetLengthString(seconds)
        Calc.SetAudioBitrateFromFile(p.Audio0)
        Calc.SetAudioBitrateFromFile(p.Audio1)
        tbSize_TextChanged(Nothing, Nothing)
    End Sub

    Public Function GetLengthString(ByVal seconds As Integer) As String
        Dim sec As Integer = seconds Mod 60

        If sec <= 9 Then
            Return (seconds \ 60).ToString + ":0" + sec.ToString
        Else
            Return (seconds \ 60).ToString + ":" + sec.ToString
        End If
    End Function

    Public Sub UpdateControls()
        Dim croppedWidth As Integer = p.SourceWidth - p.CropLeft - p.CropRight
        Dim croppedHeight As Integer = p.SourceHeight - p.CropTop - p.CropBottom

        lCrop.Text = croppedWidth.ToString() + "/" + croppedHeight.ToString()

        Dim widthZoom As Integer
        Dim heightZoom As Integer

        If croppedWidth <> 0 Then
            widthZoom = CInt((p.TargetWidth / croppedWidth) * 100)
        End If

        If croppedWidth <> 0 Then
            heightZoom = CInt((p.TargetHeight / croppedHeight) * 100)
        End If

        g.Highlight(widthZoom > 100 AndAlso heightZoom > 100, lZoom)

        lZoom.Text = widthZoom.ToString() + "/" + heightZoom.ToString

        lPixelValue.Text = CInt(p.TargetWidth * p.TargetHeight).ToString

        Dim trackBarValue As Integer = CInt((p.TargetWidth - s.ResizeSliderMin.Value) / 16)

        If trackBarValue < tbResize.Minimum Then
            trackBarValue = tbResize.Minimum
        End If

        If trackBarValue > tbResize.Maximum Then
            trackBarValue = tbResize.Maximum
        End If

        tbResize.Value = trackBarValue
        lCompCheckValue.Text = p.Compressibility.ToString("f2")
        lQualityValue.Text = CInt(Calc.GetPercent).ToString() + " %"
        lAudioBitrate.Text = CInt(Calc.GetAudioBitrate).ToString

        lARUsedValue.Text = (p.TargetWidth / p.TargetHeight).ToString("f3") + _
            " (" + GetAspectRatioError().ToString("f2") + "%)"

        lSourceImageSize.Text = p.SourceWidth.ToString + "/" + p.SourceHeight.ToString
        lSourceFramerate.Text = p.SourceFramerate.ToString("f3")
    End Sub

    Private Sub MainForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing
        If IsSaveCanceled() Then
            e.Cancel = True
            Exit Sub
        End If

        SaveSettings()
    End Sub

    Public Sub SaveSettings()
        SafeSerialization.Serialize(s, Paths.SettingsFile)
    End Sub

    Private Sub MainForm_LocationChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Me.LocationChanged
        If Not s Is Nothing Then
            s.WindowPositions.Save(Me, WindowPositions.Mode.Position)
        End If
    End Sub

    Private Sub pEncoder_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) Handles pEncoder.MouseLeave
        Assistant()
    End Sub

    Private Sub AudioEdit0ToolStripMenuItemClick()
        p.Audio0.Profile.ShowDialog()
        lAudioProfile0.Text = p.Audio0.Profile.Name
        Calc.SetAudioBitrateFromFile(p.Audio1)
        tbSize_TextChanged(Nothing, Nothing)
    End Sub

    Private Sub AudioEdit1ToolStripMenuItemClick()
        p.Audio1.Profile.ShowDialog()
        lAudioProfile1.Text = p.Audio1.Profile.Name
        Calc.SetAudioBitrateFromFile(p.Audio1)
        tbSize_TextChanged(Nothing, Nothing)
    End Sub

    Private Sub AudioSource0ToolStripMenuItemClick()
        tbAudioFile0_DoubleClick(Nothing, Nothing)
    End Sub

    Private Sub AudioSource1ToolStripMenuItemClick()
        tbAudioFile1_DoubleClick(Nothing, Nothing)
    End Sub

    <GenericMenuMethod("Open Audio Profiles Dialog", "Opens a dialog to manage audio profiles.")> _
    Public Sub OpenAudioProfilesDialog(<Name("Track Number")> ByVal number As Integer)
        Dim f As ProfilesForm

        If number = 0 Then
            f = New ProfilesForm("Audio Profiles", s.AudioProfiles, AddressOf LoadAudioProfile0, AddressOf GetAudioProfile0)
        Else
            f = New ProfilesForm("Audio Profiles", s.AudioProfiles, AddressOf LoadAudioProfile1, AddressOf GetAudioProfile1)
        End If

        f.ShowDialog()
        f.Dispose()

        UpdateAudioMenu()

        PopulateDynamicMenu("Audio 1")
        PopulateDynamicMenu("Audio 2")
    End Sub

    Private Sub bAudioMenu0_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bAudioMenu0.Click
        AudioMenu0.Show(bAudioMenu0, 0, bAudioMenu0.Height)
    End Sub

    Private Sub bAudioMenu1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bAudioMenu1.Click
        AudioMenu1.Show(bAudioMenu1, 0, bAudioMenu1.Height)
    End Sub

    Private Sub InitMainMenuDynamic()
        PopulateDynamicMenu("Encoder")
        PopulateDynamicMenu("Muxer")
        PopulateDynamicMenu("Audio 1")
        PopulateDynamicMenu("Audio 2")
        PopulateDynamicMenu("Filter Setup")
    End Sub

    Private Sub UpdateAudioMenu()
        AudioMenu0.Items.Clear()
        AudioMenu1.Items.Clear()

        AudioMenu0.Items.Add(New SubToolStripMenuItem("Source File...", AddressOf AudioSource0ToolStripMenuItemClick))
        AudioMenu1.Items.Add(New SubToolStripMenuItem("Source File...", AddressOf AudioSource1ToolStripMenuItemClick))

        AudioMenu0.Items.Add(New SubToolStripMenuItem("Edit...", AddressOf AudioEdit0ToolStripMenuItemClick))
        AudioMenu1.Items.Add(New SubToolStripMenuItem("Edit...", AddressOf AudioEdit1ToolStripMenuItemClick))

        AudioMenu0.Items.Add(New ParamToolStripMenuItem(Of Integer)("Profiles...", AddressOf OpenAudioProfilesDialog, 0))
        AudioMenu1.Items.Add(New ParamToolStripMenuItem(Of Integer)("Profiles...", AddressOf OpenAudioProfilesDialog, 1))

        AudioMenu0.Items.Add(New ToolStripSeparator)
        AudioMenu1.Items.Add(New ToolStripSeparator)

        PopulateDynamicMenuItem(AudioMenu0.Items, s.AudioProfiles, Nothing, AddressOf LoadAudioProfile0)
        PopulateDynamicMenuItem(AudioMenu1.Items, s.AudioProfiles, Nothing, AddressOf LoadAudioProfile1)
    End Sub

    Public Sub LoadMuxer(ByVal profile As Profile)
        p.VideoEncoder.LoadMuxer(profile)
    End Sub

    Private Sub AviSynthListView_ItemCheck(ByVal sender As Object, ByVal e As ItemCheckEventArgs) Handles AviSynthListView.ItemCheck
        If Not IsLoading Then
            Assistant()
        End If
    End Sub

    Public Sub tbTargetPath_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbTargetPath.TextChanged
        p.Name = Filepath.GetNameNoExt(tbTargetPath.Text)
        p.TargetFile = tbTargetPath.Text
    End Sub

    Public Sub tbTargetPath_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles tbTargetPath.DoubleClick
        bTargetPath.PerformClick()
    End Sub

    Private Sub tbTargetPath_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles tbTargetPath.Validating
        Assistant()
    End Sub

    Public Sub bTargetPath_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bTargetPath.Click
        Using d As New SaveFileDialog
            d.FileName = p.TargetFile
            d.DefaultExt = p.VideoEncoder.Muxer.GetExtension

            If d.ShowDialog() = Windows.Forms.DialogResult.OK Then
                tbTargetPath.Text = d.FileName
                Assistant()
            End If
        End Using
    End Sub
End Class