    ﻿using Nikse.SubtitleEdit.Controls;
    using Nikse.SubtitleEdit.Core;
    using Nikse.SubtitleEdit.Core.BluRaySup;
    using Nikse.SubtitleEdit.Core.ContainerFormats.MaterialExchangeFormat;
    using Nikse.SubtitleEdit.Core.ContainerFormats.Matroska;
    using Nikse.SubtitleEdit.Core.ContainerFormats.Mp4;
    using Nikse.SubtitleEdit.Core.ContainerFormats.Mp4.Boxes;
    using Nikse.SubtitleEdit.Core.Enums;
    using Nikse.SubtitleEdit.Core.Forms;
    using Nikse.SubtitleEdit.Core.NetflixQualityCheck;
    using Nikse.SubtitleEdit.Core.SpellCheck;
    using Nikse.SubtitleEdit.Core.SubtitleFormats;
    using Nikse.SubtitleEdit.Core.TransportStream;
    using Nikse.SubtitleEdit.Core.VobSub;
    using Nikse.SubtitleEdit.Forms.Ocr;
    using Nikse.SubtitleEdit.Forms.Styles;
    using Nikse.SubtitleEdit.Logic;
    using Nikse.SubtitleEdit.Logic.Networking;
    using Nikse.SubtitleEdit.Logic.VideoPlayers;
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Reflection;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Windows.Forms;

    namespace Nikse.SubtitleEdit.Forms
    {

        public sealed partial class Main : Form
        {
            private class ComboBoxZoomItem
            {
                public string Text { get; set; }
                public double ZoomFactor { get; set; }

                public override string ToString()
                {
                    return Text;
                }
            }

            private const int TabControlListView = 0;
            private const int TabControlSourceView = 1;

            private Subtitle _subtitle = new Subtitle();

            private int _undoIndex = -1;
            private string _listViewTextUndoLast;
            private int _listViewTextUndoIndex = -1;
            private long _listViewTextTicks = -1;
            private string _listViewAlternateTextUndoLast;
            private long _listViewAlternateTextTicks = -1;

            private Subtitle _subtitleAlternate = new Subtitle();
            private string _subtitleAlternateFileName;
            private string _fileName;
            private string _videoFileName;
            private int _videoAudioTrackNumber = -1;

            public string VideoFileName
            {
                get { return _videoFileName; }
                set { _videoFileName = value; }
            }

            private DateTime _fileDateTime;
            private string _title;
            private FindReplaceDialogHelper _findHelper;
            private int _replaceStartLineIndex;
            private bool _sourceViewChange;
            private string _changeSubtitleToString = string.Empty;
            private string _changeAlternateSubtitleToString = string.Empty;
            private int _subtitleListViewIndex = -1;
            private Paragraph _oldSelectedParagraph;
            private bool _converted;
            private SubtitleFormat _oldSubtitleFormat;
            private List<int> _selectedIndices;
            private LanguageStructure.Main _language;
            private LanguageStructure.General _languageGeneral;
            private SpellCheck _spellCheckForm;
            private bool _loading = true;
            private bool _exitWhenLoaded;
            private int _repeatCount = -1;
            private double _endSeconds = -1;
            private double _endSecondsNewPosition = -1;
            private long _endSecondsNewPositionTicks = 0;
            private const double EndDelay = 0.05;
            private int _autoContinueDelayCount = -1;
            private long _lastTextKeyDownTicks;
            private long _lastHistoryTicks;
            private long _lastWaveformMenuCloseTicks;
            private double? _audioWaveformRightClickSeconds;
            private Timer _timerDoSyntaxColoring = new Timer();
            private Timer _timerAutoSave = new Timer();
            private Timer _timerClearStatus = new Timer();
            private string _textAutoSave;
            private string _textAutoSaveOriginal;
            private List<string> _statusLog = new List<string>();
            private StatusLog _statusLogForm;
            private bool _makeHistoryPaused;
            private bool _saveAsCalled;

            private CheckForUpdatesHelper _checkForUpdatesHelper;
            private Timer _timerCheckForUpdates;

            private NikseWebServiceSession _networkSession;
            private NetworkChat _networkChat;

            private ShowEarlierLater _showEarlierOrLater;

            private bool _isVideoControlsUndocked;
            private VideoPlayerUndocked _videoPlayerUndocked;
            private WaveformUndocked _waveformUndocked;
            private VideoControlsUndocked _videoControlsUndocked;

            private GoogleOrMicrosoftTranslate _googleOrMicrosoftTranslate;

            private bool _cancelWordSpellCheck = true;

            private bool _clearLastFind;
            private FindType _clearLastFindType = FindType.Normal;
            private string _clearLastFindText = string.Empty;

            private Keys _mainGeneralGoToFirstSelectedLine = Keys.None;
            private Keys _mainGeneralGoToFirstEmptyLine = Keys.None;
            private Keys _mainGeneralMergeSelectedLines = Keys.None;
            private Keys _mainGeneralMergeSelectedLinesOnlyFirstText = Keys.None;
            private Keys _mainGeneralToggleTranslationMode = Keys.None;
            private Keys _mainGeneralSwitchTranslationAndOriginal = Keys.None;
            private Keys _mainGeneralMergeTranslationAndOriginal = Keys.None;
            private Keys _mainGeneralMergeWithNext = Keys.None;
            private Keys _mainGeneralMergeWithPrevious = Keys.None;
            private Keys _mainGeneralGoToNextSubtitle = Keys.None;
            private Keys _mainGeneralGoToPrevSubtitle = Keys.None;
            private Keys _mainGeneralGoToStartOfCurrentSubtitle = Keys.None;
            private Keys _mainGeneralGoToEndOfCurrentSubtitle = Keys.None;
            private Keys _mainGeneralFileSaveAll = Keys.None;
            private Keys _mainToolsAutoDuration = Keys.None;
            private Keys _mainToolsBeamer = Keys.None;
            private Keys _toggleVideoDockUndock = Keys.None;
            private Keys _videoPause = Keys.None;
            private Keys _videoPlayPauseToggle = Keys.None;
            private Keys _video1FrameLeft = Keys.None;
            private Keys _video1FrameRight = Keys.None;
            private Keys _video1FrameLeftWithPlay = Keys.None;
            private Keys _video1FrameRightWithPlay = Keys.None;
            private Keys _video100MsLeft = Keys.None;
            private Keys _video100MsRight = Keys.None;
            private Keys _video500MsLeft = Keys.None;
            private Keys _video500MsRight = Keys.None;
            private Keys _video1000MsLeft = Keys.None;
            private Keys _video1000MsRight = Keys.None;
            private Keys _video5000MsLeft = Keys.None;
            private Keys _video5000MsRight = Keys.None;
            private Keys _videoPlayFirstSelected = Keys.None;
            private Keys _mainVideoFullscreen = Keys.None;
            private Keys _mainGoToPreviousSubtitleAndFocusVideo = Keys.None;
            private Keys _mainGoToNextSubtitleAndFocusVideo = Keys.None;
            private Keys _mainAdjustExtendCurrentSubtitle = Keys.None;
            private Keys _mainAutoCalcCurrentDuration = Keys.None;
            private Keys _mainUnbreakNoSpace = Keys.None;
            private Keys _mainTextBoxSplitAtCursor = Keys.None;
            private Keys _mainTextBoxSplitAtCursorAndVideoPos = Keys.None;
            private Keys _mainTextBoxMoveLastWordDown = Keys.None;
            private Keys _mainTextBoxMoveFirstWordFromNextUp = Keys.None;
            private Keys _mainTextBoxMoveLastWordDownCurrent = Keys.None;
            private Keys _mainTextBoxMoveFirstWordUpCurrent = Keys.None;
            private Keys _mainTextBoxSelectionToLower = Keys.None;
            private Keys _mainTextBoxSelectionToUpper = Keys.None;
            private Keys _mainTextBoxToggleAutoDuration = Keys.None;
            private Keys _mainCreateInsertSubAtVideoPos = Keys.None;
            private Keys _mainCreatePlayFromJustBefore = Keys.None;
            private Keys _mainCreateSetStart = Keys.None;
            private Keys _mainCreateSetEnd = Keys.None;
            private Keys _mainCreateStartDownEndUp = Keys.None;
            private Keys _mainCreateSetEndAddNewAndGoToNew = Keys.None;
            private Keys _mainAdjustSetStartAndOffsetTheRest = Keys.None;
            private Keys _mainAdjustSetEndAndOffsetTheRest = Keys.None;
            private Keys _mainAdjustSetEndAndOffsetTheRestAndGoToNext = Keys.None;
            private Keys _mainAdjustSetEndAndGotoNext = Keys.None;
            private Keys _mainAdjustInsertViaEndAutoStartAndGoToNext = Keys.None;
            private Keys _mainAdjustSetStartAutoDurationAndGoToNext = Keys.None;
            private Keys _mainAdjustSetEndNextStartAndGoToNext = Keys.None;
            private Keys _mainAdjustStartDownEndUpAndGoToNext = Keys.None;
            private Keys _mainAdjustSetStart = Keys.None;
            private Keys _mainAdjustSetStartKeepDuration = Keys.None;
            private Keys _mainAdjustSetEnd = Keys.None;
            private Keys _mainAdjustSelected100MsForward = Keys.None;
            private Keys _mainAdjustSelected100MsBack = Keys.None;
            private Keys _mainAdjustAdjustStartXMsBack = Keys.None;
            private Keys _mainAdjustAdjustStartXMsForward = Keys.None;
            private Keys _mainAdjustAdjustEndXMsBack = Keys.None;
            private Keys _mainAdjustAdjustEndXMsForward = Keys.None;
            private Keys _mainInsertAfter = Keys.None;
            private Keys _mainInsertBefore = Keys.None;
            private Keys _mainTextBoxInsertAfter = Keys.None;
            private Keys _mainTextBoxAutoBreak = Keys.None;
            private Keys _mainTextBoxUnbreak = Keys.None;
            private Keys _mainMergeDialog = Keys.None;
            private Keys _mainToggleFocus = Keys.None;
            private Keys _mainListViewToggleDashes = Keys.None;
            private Keys _mainListViewAutoDuration = Keys.None;
            private Keys _mainListViewFocusWaveform = Keys.None;
            private Keys _mainListViewGoToNextError = Keys.None;
            private Keys _mainListViewCopyText = Keys.None;
            private Keys _mainEditReverseStartAndEndingForRTL = Keys.None;
            private Keys _waveformVerticalZoom = Keys.None;
            private Keys _waveformVerticalZoomOut = Keys.None;
            private Keys _waveformZoomIn = Keys.None;
            private Keys _waveformZoomOut = Keys.None;
            private Keys _waveformPlaySelection = Keys.None;
            private Keys _waveformPlaySelectionEnd = Keys.None;
            private Keys _waveformSearchSilenceForward = Keys.None;
            private Keys _waveformSearchSilenceBack = Keys.None;
            private Keys _waveformAddTextAtHere = Keys.None;
            private Keys _waveformAddTextAtHereFromClipboard = Keys.None;
            private Keys _waveformFocusListView = Keys.None;
            private Keys _waveformGoToNextSubtitle = Keys.None;
            private Keys _waveformGoToPreviousSceneChange = Keys.None;
            private Keys _waveformGoToNextSceneChange = Keys.None;
            private Keys _waveformToggleSceneChange = Keys.None;
            private Keys _mainTranslateCustomSearch1 = Keys.None;
            private Keys _mainTranslateCustomSearch2 = Keys.None;
            private Keys _mainTranslateCustomSearch3 = Keys.None;
            private Keys _mainTranslateCustomSearch4 = Keys.None;
            private Keys _mainTranslateCustomSearch5 = Keys.None;
            private Keys _mainTranslateCustomSearch6 = Keys.None;
            private bool _videoLoadedGoToSubPosAndPause;
            private string _cutText = string.Empty;
            private Paragraph _mainCreateStartDownEndUpParagraph;
            private Paragraph _mainAdjustStartDownEndUpAndGoToNextParagraph;
            private string _lastDoNotPrompt = string.Empty;
            private VideoInfo _videoInfo;
            private bool _splitDualSami;
            private bool _openFileDialogOn;
            private bool _resetVideo = true;
            private bool _doAutoBreakOnTextChanged = true;
            private static object _syncUndo = new object();
            private string[] _dragAndDropFiles;
            private readonly Timer _dragAndDropTimer = new Timer(); // to prevent locking windows explorer
            private long _labelNextTicks = -1;

            public bool IsMenuOpen { get; private set; }

            private bool AutoRepeatContinueOn
            {
                get { return tabControlButtons.SelectedIndex == 0 && checkBoxAutoContinue.Checked; }
            }

            private bool AutoRepeatOn
            {
                get { return tabControlButtons.SelectedIndex == 0 && checkBoxAutoRepeatOn.Checked; }
            }

            public string Title
            {
                get
                {
                    if (_title == null)
                    {
                        var versionInfo = Utilities.AssemblyVersion.Split('.');
                        _title = String.Format("{0} {1}.{2}.{3}", _languageGeneral.Title, versionInfo[0], versionInfo[1], versionInfo[2]);
                    }
                    return _title;
                }
            }

            private void SetCurrentFormat(string subtitleFormatName)
            {
                SetCurrentFormat(FormatNameToFormat(subtitleFormatName));
            }

            private void SetCurrentFormat(SubtitleFormat format)
            {
                if (format.IsVobSubIndexFile)
                {
                    UiUtil.InitializeSubtitleFormatComboBox(comboBoxSubtitleFormats, format);
                    SubtitleListview1.HideNonVobSubColumns();
                }
                else if (comboBoxSubtitleFormats.Items.Count == 1)
                {
                    SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Extra);
                    SetFormatTo(format);
                }
                else
                {
                    int index = 0;
                    foreach (string name in comboBoxSubtitleFormats.Items)
                    {
                        if (name == format.FriendlyName)
                        {
                            comboBoxSubtitleFormats.SelectedIndex = index;
                            return;
                        }
                        index++;
                    }
                }
            }

            private SubtitleFormat FormatNameToFormat(string subtitleFormatName)
            {
                subtitleFormatName = subtitleFormatName.Trim();
                foreach (var format in SubtitleFormat.AllSubtitleFormats)
                {
                    if (format.Name.Trim().Equals(subtitleFormatName, StringComparison.OrdinalIgnoreCase) ||
                        format.FriendlyName.Trim().Equals(subtitleFormatName, StringComparison.OrdinalIgnoreCase))
                    {
                        return format;
                    }
                }
                return new SubRip();
            }

            protected override void OnLoad(EventArgs e)
            {
                UiUtil.FixFonts(this, 10000);
                UiUtil.FixLargeFonts(tabControlButtons, buttonAutoBreak);
                UiUtil.FixLargeFonts(tabControlButtons, buttonAutoBreak);
                UiUtil.FixLargeFonts(groupBoxEdit, buttonAutoBreak);
                UiUtil.InitializeSubtitleFont(textBoxSource);
                UiUtil.InitializeSubtitleFont(textBoxListViewText);
                UiUtil.InitializeSubtitleFont(textBoxListViewTextAlternate);
                UiUtil.InitializeSubtitleFont(SubtitleListview1);

                using (var graphics = CreateGraphics())
                {
                    // avoid weird looking layout for high DPI
                    if (graphics.DpiX > 120)
                    {
                        Font = new Font(Font.FontFamily, (float)(Font.Size * graphics.DpiX / 96.0));

                        numericUpDownDuration.Left = timeUpDownStartTime.Right + 15;
                        numericUpDownDuration.Width += 5;
                        labelDuration.Left = numericUpDownDuration.Left - 3;
                        labelAutoDuration.Left = labelDuration.Left - (labelAutoDuration.Width - 5);
                    }
                }

                base.OnLoad(e);
            }

            public Main()
            {
                if (Configuration.IsRunningOnLinux())
                    NativeMethods.setlocale(NativeMethods.LC_NUMERIC, "C");
                try
                {
                    UiUtil.PreInitialize(this);
                    InitializeComponent();

                    Icon = Properties.Resources.SubtitleEditFormIcon;

                    textBoxListViewTextAlternate.Visible = false;
                    labelAlternateText.Visible = false;
                    labelAlternateCharactersPerSecond.Visible = false;
                    labelTextAlternateLineLengths.Visible = false;
                    labelAlternateSingleLine.Visible = false;
                    labelTextAlternateLineTotal.Visible = false;
                    labelNextWord.Visible = false;

                    SetLanguage(Configuration.Settings.General.Language);
                    toolStripStatusNetworking.Visible = false;
                    labelTextLineLengths.Text = string.Empty;
                    labelCharactersPerSecond.Text = string.Empty;
                    labelTextLineTotal.Text = string.Empty;
                    labelStartTimeWarning.Text = string.Empty;
                    labelDurationWarning.Text = string.Empty;
                    labelVideoInfo.Text = string.Empty;
                    labelSingleLine.Text = string.Empty;
                    Text = Title;
                    timeUpDownStartTime.TimeCode = new TimeCode();
                    timeUpDownStartTime.UseVideoOffset = true;
                    timeUpDownVideoPosition.UseVideoOffset = true;
                    timeUpDownVideoPositionAdjust.UseVideoOffset = true;
                    checkBoxAutoRepeatOn.Checked = Configuration.Settings.General.AutoRepeatOn;
                    comboBoxAutoRepeat.SelectedIndex = Configuration.Settings.General.AutoRepeatCount;
                    checkBoxAutoContinue.Checked = Configuration.Settings.General.AutoContinueOn;
                    checkBoxSyncListViewWithVideoWhilePlaying.Checked = Configuration.Settings.General.SyncListViewWithVideoWhilePlaying;

                    SetFormatTo(Configuration.Settings.General.DefaultSubtitleFormat);

                    UiUtil.InitializeTextEncodingComboBox(comboBoxEncoding.ComboBox);

                    // set up UI interfaces / injections
                    YouTubeAnnotations.GetYouTubeAnnotationStyles = new UiGetYouTubeAnnotationStyles();
                    Ebu.EbuUiHelper = new UiEbuSaveHelper();
                    Pac.GetPacEncodingImplementation = new UiGetPacEncoding();
                    RichTextToPlainText.NativeRtfTextConverter = new RtfTextConverterRichTextBox();

                    toolStripComboBoxFrameRate.Items.Add((23.976).ToString());
                    toolStripComboBoxFrameRate.Items.Add((24.0).ToString());
                    toolStripComboBoxFrameRate.Items.Add((25.0).ToString());
                    toolStripComboBoxFrameRate.Items.Add((29.97).ToString());
                    toolStripComboBoxFrameRate.Items.Add((30).ToString());
                    toolStripComboBoxFrameRate.Text = Configuration.Settings.General.DefaultFrameRate.ToString();

                    UpdateRecentFilesUI();
                    InitializeToolbar();
                    UpdateNetflixGlyphCheckToolsVisibility();

                    if (Configuration.Settings.General.CenterSubtitleInTextBox)
                    {
                        textBoxListViewText.TextAlign = HorizontalAlignment.Center;
                        textBoxListViewTextAlternate.TextAlign = HorizontalAlignment.Center;
                    }

                    tabControlSubtitle.SelectTab(TabControlSourceView); // AC
                    ShowSourceLineNumber(); // AC
                    tabControlSubtitle.SelectTab(TabControlListView); // AC
                    if (Configuration.Settings.General.StartInSourceView)
                        tabControlSubtitle.SelectTab(TabControlSourceView);

                    audioVisualizer.Visible = Configuration.Settings.General.ShowAudioVisualizer;
                    audioVisualizer.ShowWaveform = Configuration.Settings.General.ShowWaveform;
                    audioVisualizer.ShowSpectrogram = Configuration.Settings.General.ShowSpectrogram;
                    panelWaveformControls.Visible = Configuration.Settings.General.ShowAudioVisualizer;
                    trackBarWaveformPosition.Visible = Configuration.Settings.General.ShowAudioVisualizer;
                    toolStripButtonToggleWaveform.Checked = Configuration.Settings.General.ShowAudioVisualizer;
                    toolStripButtonToggleVideo.Checked = Configuration.Settings.General.ShowVideoPlayer;

                    if (Configuration.Settings.General.UseTimeFormatHHMMSSFF)
                    {
                        numericUpDownDuration.DecimalPlaces = 2;
                        numericUpDownDuration.Increment = (decimal)(0.01);
                        toolStripSeparatorFrameRate.Visible = true;
                        toolStripLabelFrameRate.Visible = true;
                        toolStripComboBoxFrameRate.Visible = true;
                        toolStripButtonGetFrameRate.Visible = true;
                    }

                    _timerClearStatus.Interval = Configuration.Settings.General.ClearStatusBarAfterSeconds * 1000;
                    _timerClearStatus.Tick += TimerClearStatus_Tick;

                    var fileName = string.Empty;
                    var args = Environment.GetCommandLineArgs();
                    int srcLineNumber = -1;
                    if (args.Length >= 2 && (args[1].Equals("/convert", StringComparison.OrdinalIgnoreCase) || args[1].Equals("/?", StringComparison.Ordinal) ||
                        args[1].Equals("/help", StringComparison.OrdinalIgnoreCase) || args[1].Equals("-help", StringComparison.OrdinalIgnoreCase)))
                    {
                        CommandLineConvert.Convert(Title, args);
                        return;
                    }
                    if (args.Length >= 2)
                    {
                        fileName = args[1];
                        if (args.Length > 2 && args[2].StartsWith("/srcline:", StringComparison.OrdinalIgnoreCase))
                        {
                            string srcLine = args[2].Remove(0, 9);
                            if (!int.TryParse(srcLine, out srcLineNumber))
                                srcLineNumber = -1;
                        }
                    }

                    labelAutoDuration.Visible = false;
                    mediaPlayer.SubtitleText = string.Empty;
                    comboBoxAutoContinue.SelectedIndex = Configuration.Settings.General.AutoContinueDelay;

                    timeUpDownVideoPosition.TimeCode = new TimeCode();
                    timeUpDownVideoPositionAdjust.TimeCode = new TimeCode();
                    timeUpDownVideoPosition.TimeCodeChanged += VideoPositionChanged;
                    timeUpDownVideoPositionAdjust.TimeCodeChanged += VideoPositionChanged;
                    timeUpDownVideoPosition.Enabled = false;
                    timeUpDownVideoPositionAdjust.Enabled = false;

                    switch (Configuration.Settings.VideoControls.LastActiveTab)
                    {
                        case "Translate":
                            tabControlButtons.SelectedIndex = 0;
                            break;
                        case "Create":
                            tabControlButtons.SelectedIndex = 1;
                            break;
                        case "Adjust":
                            tabControlButtons.SelectedIndex = 2;
                            break;
                    }
                    tabControl1_SelectedIndexChanged(null, null);
                    buttonCustomUrl1.Text = Configuration.Settings.VideoControls.CustomSearchText1;
                    buttonCustomUrl1.Visible = Configuration.Settings.VideoControls.CustomSearchUrl1.Length > 1;
                    buttonCustomUrl2.Text = Configuration.Settings.VideoControls.CustomSearchText2;
                    buttonCustomUrl2.Visible = Configuration.Settings.VideoControls.CustomSearchUrl2.Length > 1;

                    if (fileName.Length > 0 && File.Exists(fileName))
                    {
                        fileName = Path.GetFullPath(fileName);
                        OpenSubtitle(fileName, null);
                        if (srcLineNumber >= 0 && GetCurrentSubtitleFormat().GetType() == typeof(SubRip) && srcLineNumber < textBoxSource.Lines.Length)
                        {
                            int pos = 0;
                            for (int i = 0; i < srcLineNumber; i++)
                            {
                                pos += textBoxSource.Lines[i].Length;
                            }
                            if (pos + 35 < textBoxSource.TextLength)
                                pos += 35;
                            string s = textBoxSource.Text.Substring(0, pos);
                            int lastTimeCode = s.LastIndexOf(" --> ", StringComparison.Ordinal); // 00:02:26,407 --> 00:02:31,356
                            if (lastTimeCode > 14 && lastTimeCode + 16 >= s.Length)
                            {
                                s = s.Substring(0, lastTimeCode - 5);
                                lastTimeCode = s.LastIndexOf(" --> ", StringComparison.Ordinal);
                            }

                            if (lastTimeCode > 14 && lastTimeCode + 16 < s.Length)
                            {
                                string tc = s.Substring(lastTimeCode - 13, 30).Trim();
                                int index = 0;
                                foreach (var p in _subtitle.Paragraphs)
                                {
                                    if (tc == p.StartTime + " --> " + p.EndTime)
                                    {
                                        SubtitleListview1.SelectNone();
                                        SubtitleListview1.Items[0].Selected = false;
                                        SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                                        break;
                                    }
                                    index++;
                                }
                            }
                        }
                    }
                    else if (Configuration.Settings.General.StartLoadLastFile)
                    {
                        if (Configuration.Settings.RecentFiles.Files.Count > 0)
                        {
                            fileName = Configuration.Settings.RecentFiles.Files[0].FileName;
                            if (File.Exists(fileName))
                            {
                                OpenSubtitle(fileName, null, Configuration.Settings.RecentFiles.Files[0].VideoFileName, Configuration.Settings.RecentFiles.Files[0].OriginalFileName);
                                SetRecentIndices(fileName);
                                if (Configuration.Settings.RecentFiles.Files[0].VideoOffsetInMs > 0 && _subtitle != null)
                                {
                                    Configuration.Settings.General.CurrentVideoOffsetInMs = Configuration.Settings.RecentFiles.Files[0].VideoOffsetInMs;
                                    _subtitle.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(-Configuration.Settings.General.CurrentVideoOffsetInMs));
                                    _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                                    SubtitleListview1.Fill(_subtitle);
                                }
                                GotoSubPosAndPause();
                            }
                        }
                    }

                    // Initialize events etc. for audio waveform
                    audioVisualizer.OnDoubleClickNonParagraph += AudioWaveform_OnDoubleClickNonParagraph;
                    audioVisualizer.OnPositionSelected += AudioWaveform_OnPositionSelected;
                    audioVisualizer.OnTimeChanged += AudioWaveform_OnTimeChanged; // start and/or end position of paragraph changed
                    audioVisualizer.OnNewSelectionRightClicked += AudioWaveform_OnNewSelectionRightClicked;
                    audioVisualizer.OnParagraphRightClicked += AudioWaveform_OnParagraphRightClicked;
                    audioVisualizer.OnNonParagraphRightClicked += AudioWaveform_OnNonParagraphRightClicked;
                    audioVisualizer.OnSingleClick += AudioWaveform_OnSingleClick;
                    audioVisualizer.OnPause += AudioWaveform_OnPause;
                    audioVisualizer.OnTimeChangedAndOffsetRest += AudioWaveform_OnTimeChangedAndOffsetRest;
                    audioVisualizer.OnZoomedChanged += AudioWaveform_OnZoomedChanged;
                    audioVisualizer.InsertAtVideoPosition += audioVisualizer_InsertAtVideoPosition;
                    audioVisualizer.ShowGridLines = Configuration.Settings.VideoControls.WaveformDrawGrid;
                    audioVisualizer.GridColor = Configuration.Settings.VideoControls.WaveformGridColor;
                    audioVisualizer.SelectedColor = Configuration.Settings.VideoControls.WaveformSelectedColor;
                    audioVisualizer.Color = Configuration.Settings.VideoControls.WaveformColor;
                    audioVisualizer.BackgroundColor = Configuration.Settings.VideoControls.WaveformBackgroundColor;
                    audioVisualizer.TextColor = Configuration.Settings.VideoControls.WaveformTextColor;
                    audioVisualizer.TextSize = Configuration.Settings.VideoControls.WaveformTextSize;
                    audioVisualizer.TextBold = Configuration.Settings.VideoControls.WaveformTextBold;
                    audioVisualizer.MouseWheelScrollUpIsForward = Configuration.Settings.VideoControls.WaveformMouseWheelScrollUpIsForward;
                    audioVisualizer.AllowOverlap = Configuration.Settings.VideoControls.WaveformAllowOverlap;
                    audioVisualizer.ClosenessForBorderSelection = Configuration.Settings.VideoControls.WaveformBorderHitMs;
                    if (Configuration.Settings.General.WaveformUpdateIntervalMs > 0 && Configuration.Settings.General.WaveformUpdateIntervalMs < 200)
                        timerWaveform.Interval = Configuration.Settings.General.WaveformUpdateIntervalMs;

                    for (double zoomCounter = AudioVisualizer.ZoomMinimum; zoomCounter <= AudioVisualizer.ZoomMaximum + (0.001); zoomCounter += 0.1)
                    {
                        int percent = (int)Math.Round((zoomCounter * 100));
                        var item = new ComboBoxZoomItem { Text = percent + "%", ZoomFactor = zoomCounter };
                        toolStripComboBoxWaveform.Items.Add(item);
                        if (percent == 100)
                            toolStripComboBoxWaveform.SelectedIndex = toolStripComboBoxWaveform.Items.Count - 1;
                    }
                    toolStripComboBoxWaveform.SelectedIndexChanged += toolStripComboBoxWaveform_SelectedIndexChanged;

                    FixLargeFonts();

                    if (Configuration.Settings.General.RightToLeftMode)
                        ToolStripMenuItemRightToLeftModeClick(null, null);
                }
                catch (Exception exception)
                {
                    Cursor = Cursors.Default;
                    MessageBox.Show(exception.Message + Environment.NewLine + exception.StackTrace);
                }
            }

            private void audioVisualizer_InsertAtVideoPosition(object sender, EventArgs e)
            {
                InsertNewTextAtVideoPosition();
            }

            private void TimerClearStatus_Tick(object sender, EventArgs e)
            {
                ShowStatus(string.Empty);
            }

            private void SetEncoding(Encoding encoding)
            {
                foreach (TextEncodingListItem item in comboBoxEncoding.Items)
                {
                    if (item.Equals(encoding))
                    {
                        comboBoxEncoding.SelectedItem = item;
                        return;
                    }
                }
                comboBoxEncoding.SelectedIndex = 0; // UTF-8
            }

            private void SetEncoding(string encodingName)
            {
                foreach (TextEncodingListItem item in comboBoxEncoding.Items)
                {
                    if (item.Equals(encodingName))
                    {
                        comboBoxEncoding.SelectedItem = item;
                        return;
                    }
                }
                comboBoxEncoding.SelectedIndex = 0; // UTF-8
            }

            private Encoding GetCurrentEncoding()
            {
                return UiUtil.GetTextEncodingComboBoxCurrentEncoding(comboBoxEncoding.ComboBox);
            }

            private void AudioWaveform_OnNonParagraphRightClicked(object sender, AudioVisualizer.ParagraphEventArgs e)
            {
                addParagraphHereToolStripMenuItem.Visible = false;
                addParagraphAndPasteToolStripMenuItem.Visible = false;
                deleteParagraphToolStripMenuItem.Visible = false;
                toolStripMenuItemFocusTextbox.Visible = true;
                splitToolStripMenuItem1.Visible = false;
                mergeWithPreviousToolStripMenuItem.Visible = false;
                mergeWithNextToolStripMenuItem.Visible = false;
                toolStripSeparator11.Visible = false;
                toolStripMenuItemWaveformPlaySelection.Visible = false;
                toolStripSeparator24.Visible = false;
                if (audioVisualizer?.GetSceneChangeIndex(e.Seconds) >= 0)
                {
                    removeSceneChangeToolStripMenuItem.Visible = true;
                    addSceneChangeToolStripMenuItem.Visible = false;
                }
                else
                {
                    removeSceneChangeToolStripMenuItem.Visible = false;
                    addSceneChangeToolStripMenuItem.Visible = true;
                }
                _audioWaveformRightClickSeconds = e.Seconds;
                contextMenuStripWaveform.Show(MousePosition.X, MousePosition.Y);
            }

            private void AudioWaveform_OnDoubleClickNonParagraph(object sender, AudioVisualizer.ParagraphEventArgs e)
            {
                if (mediaPlayer.VideoPlayer != null)
                {
                    _endSeconds = -1;
                    if (e.Paragraph == null)
                    {
                        if (Configuration.Settings.VideoControls.WaveformDoubleClickOnNonParagraphAction == "PlayPause")
                            mediaPlayer.TogglePlayPause();
                    }
                    else
                    {
                        SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.GetIndex(e.Paragraph));
                    }
                }
            }

            private void AudioWaveform_OnZoomedChanged(object sender, EventArgs e)
            {
                SelectZoomTextInComboBox();
            }

            private void AudioWaveform_OnTimeChangedAndOffsetRest(object sender, AudioVisualizer.ParagraphEventArgs e)
            {
                if (mediaPlayer.VideoPlayer == null)
                    return;

                int index = _subtitle.Paragraphs.IndexOf(e.Paragraph);
                if (index < 0)
                {
                    if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible && Configuration.Settings.General.ShowOriginalAsPreviewIfAvailable)
                    {
                        index = _subtitleAlternate.GetIndex(e.Paragraph);
                        if (index >= 0)
                        {
                            var current = Utilities.GetOriginalParagraph(index, e.Paragraph, _subtitle.Paragraphs);
                            if (current != null)
                            {
                                index = _subtitle.Paragraphs.IndexOf(current);
                            }
                        }
                    }
                    else if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible)
                    {
                        index = _subtitle.GetIndex(e.Paragraph);
                    }
                }
                if (index >= 0)
                {
                    SubtitleListview1.SelectIndexAndEnsureVisible(index);
                    mediaPlayer.CurrentPosition = e.Seconds;
                    SetStartAndOffsetTheRest(e.Seconds);
                }
                audioVisualizer.Invalidate();
            }

            private void AudioWaveform_OnPause(object sender, EventArgs e)
            {
                _endSeconds = -1;
                if (mediaPlayer.VideoPlayer != null)
                    mediaPlayer.Pause();
            }

            private void AudioWaveform_OnSingleClick(object sender, AudioVisualizer.ParagraphEventArgs e)
            {
                timerWaveform.Stop();
                _endSeconds = -1;
                if (mediaPlayer.VideoPlayer != null)
                    mediaPlayer.Pause();

                mediaPlayer.CurrentPosition = e.Seconds;

                int index = -1;
                if (SubtitleListview1.SelectedItems.Count > 0)
                    index = SubtitleListview1.SelectedItems[0].Index;
                SetWaveformPosition(audioVisualizer.StartPositionSeconds, e.Seconds, index);
                timerWaveform.Start();
            }

            private void AudioWaveform_OnParagraphRightClicked(object sender, AudioVisualizer.ParagraphEventArgs e)
            {
                SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.GetIndex(e.Paragraph));

                addParagraphHereToolStripMenuItem.Visible = false;
                addParagraphAndPasteToolStripMenuItem.Visible = false;
                deleteParagraphToolStripMenuItem.Visible = true;
                toolStripMenuItemFocusTextbox.Visible = true;
                splitToolStripMenuItem1.Visible = true;
                mergeWithPreviousToolStripMenuItem.Visible = true;
                mergeWithNextToolStripMenuItem.Visible = true;
                toolStripSeparator11.Visible = true;
                toolStripMenuItemWaveformPlaySelection.Visible = true;
                toolStripSeparator24.Visible = true;
                if (audioVisualizer?.GetSceneChangeIndex(e.Seconds) >= 0)
                {
                    removeSceneChangeToolStripMenuItem.Visible = true;
                    addSceneChangeToolStripMenuItem.Visible = false;
                }
                else
                {
                    removeSceneChangeToolStripMenuItem.Visible = false;
                    addSceneChangeToolStripMenuItem.Visible = true;
                }
                _audioWaveformRightClickSeconds = e.Seconds;
                contextMenuStripWaveform.Show(MousePosition.X, MousePosition.Y);
            }

            private void removeSceneChangeToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (!_audioWaveformRightClickSeconds.HasValue)
                    return;

                var idx = audioVisualizer?.GetSceneChangeIndex(_audioWaveformRightClickSeconds.Value);
                if (idx >= 0 && idx < audioVisualizer.SceneChanges.Count)
                {
                    audioVisualizer.SceneChanges[idx.Value] = -1;
                    SceneChangeHelper.SaveSceneChanges(_videoFileName, audioVisualizer.SceneChanges.Where(p => p > 0).ToList());
                }
            }

            private void addSceneChangeToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (!_audioWaveformRightClickSeconds.HasValue)
                    return;

                var list = audioVisualizer.SceneChanges.Where(p => p > 0).ToList();
                list.Add(_audioWaveformRightClickSeconds.Value);
                list.Sort();
                audioVisualizer.SceneChanges = list;
                SceneChangeHelper.SaveSceneChanges(_videoFileName, list);
            }

            private void AudioWaveform_OnNewSelectionRightClicked(object sender, AudioVisualizer.ParagraphEventArgs e)
            {
                SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.GetIndex(e.Paragraph));

                addParagraphHereToolStripMenuItem.Visible = true;
                addParagraphAndPasteToolStripMenuItem.Visible = Clipboard.ContainsText();

                deleteParagraphToolStripMenuItem.Visible = false;
                toolStripMenuItemFocusTextbox.Visible = false;
                splitToolStripMenuItem1.Visible = false;
                mergeWithPreviousToolStripMenuItem.Visible = false;
                mergeWithNextToolStripMenuItem.Visible = false;

                contextMenuStripWaveform.Show(MousePosition.X, MousePosition.Y);
            }

            private void AudioWaveform_OnTimeChanged(object sender, AudioVisualizer.ParagraphEventArgs e)
            {
                var paragraph = e.Paragraph;
                var beforeParagraph = e.BeforeParagraph;
                if (beforeParagraph == null)
                    beforeParagraph = paragraph;

                if (Math.Abs(beforeParagraph.StartTime.TotalMilliseconds - paragraph.StartTime.TotalMilliseconds) < 0.01 &&
                    Math.Abs(beforeParagraph.EndTime.TotalMilliseconds - paragraph.EndTime.TotalMilliseconds) < 0.01)
                    _makeHistoryPaused = true;

                int selectedIndex = FirstSelectedIndex;
                int index = _subtitle.Paragraphs.IndexOf(paragraph);

                // TODO: Moving selected lines
                // current idx must also be selected
                //if (e.MouseDownParagraphType == AudioVisualizer.MouseDownParagraphType.Whole && SubtitleListview1.SelectedIndices.Count > 1)
                //{
                //    foreach (int idx in SubtitleListview1.SelectedIndices)
                //    {
                //        var p = _subtitle.Paragraphs[idx];
                //        if (p != paragraph)
                //        {
                //            var dur = p.Duration.TotalMilliseconds;
                //            p.StartTime.TotalMilliseconds += e.AdjustMs;
                //            p.EndTime.TotalMilliseconds += e.AdjustMs;
                //            SubtitleListview1.SetStartTimeAndDuration(idx, p);
                //        }
                //    }
                //}

                if (index == _subtitleListViewIndex)
                {
                    // Make history item for rollback (change paragraph back for history + change again)
                    _subtitle.Paragraphs[index] = new Paragraph(beforeParagraph);
                    MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.VideoControls.BeforeChangingTimeInWaveformX, "#" + paragraph.Number + " " + paragraph.Text));
                    _subtitle.Paragraphs[index] = paragraph;
                    _makeHistoryPaused = true;

                    Paragraph original = null;
                    if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible)
                        original = Utilities.GetOriginalParagraph(index, beforeParagraph, _subtitleAlternate.Paragraphs);

                    if (Configuration.Settings.General.UseTimeFormatHHMMSSFF)
                    { // so we don't get weird rounds we'll use whole frames when moving start time
                        double fr = TimeCode.BaseUnit / Configuration.Settings.General.CurrentFrameRate;
                        if (e.BeforeParagraph != null && e.BeforeParagraph.StartTime.TotalMilliseconds != e.Paragraph.StartTime.TotalMilliseconds &&
                            e.BeforeParagraph.Duration.TotalMilliseconds == e.Paragraph.Duration.TotalMilliseconds)
                        {
                            // move paragraph
                            paragraph.StartTime.TotalMilliseconds = ((int)Math.Round(paragraph.StartTime.TotalMilliseconds / fr)) * fr;
                            paragraph.EndTime.TotalMilliseconds = paragraph.StartTime.TotalMilliseconds + e.BeforeParagraph.Duration.TotalMilliseconds;
                        }
                        else if (e.BeforeParagraph != null && e.BeforeParagraph.EndTime.TotalMilliseconds == e.Paragraph.EndTime.TotalMilliseconds)
                        {
                            paragraph.EndTime.TotalMilliseconds = ((int)Math.Round(paragraph.EndTime.TotalMilliseconds / fr)) * fr;
                            int end = SubtitleFormat.MillisecondsToFrames(paragraph.EndTime.TotalMilliseconds);
                            int dur = SubtitleFormat.MillisecondsToFrames(paragraph.Duration.TotalMilliseconds);
                            paragraph.StartTime.TotalMilliseconds = SubtitleFormat.FramesToMilliseconds(end - dur);
                        }
                    }

                    timeUpDownStartTime.TimeCode = paragraph.StartTime;
                    var durationInSeconds = (decimal)(paragraph.Duration.TotalSeconds);
                    if (durationInSeconds >= numericUpDownDuration.Minimum && durationInSeconds <= numericUpDownDuration.Maximum)
                    {
                        SetDurationInSeconds((double)durationInSeconds);
                        if (e.MouseDownParagraphType == AudioVisualizer.MouseDownParagraphType.Start)
                        {
                            paragraph.EndTime.TotalMilliseconds = e.BeforeParagraph.EndTime.TotalMilliseconds;
                        }
                    }

                    MovePrevNext(e, beforeParagraph, index);

                    if (original != null)
                    {
                        original.StartTime.TotalMilliseconds = paragraph.StartTime.TotalMilliseconds;
                        original.EndTime.TotalMilliseconds = paragraph.EndTime.TotalMilliseconds;
                    }
                }
                else if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible && Configuration.Settings.General.ShowOriginalAsPreviewIfAvailable)
                {
                    index = _subtitleAlternate.GetIndex(paragraph);
                    if (index >= 0)
                    {
                        // Make history item for rollback (change paragraph back for history + change again)
                        _subtitleAlternate.Paragraphs[index] = new Paragraph(beforeParagraph);
                        MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.VideoControls.BeforeChangingTimeInWaveformX, "#" + paragraph.Number + " " + paragraph.Text));
                        _subtitleAlternate.Paragraphs[index] = paragraph;
                        _makeHistoryPaused = true;

                        var current = Utilities.GetOriginalParagraph(index, beforeParagraph, _subtitle.Paragraphs);
                        if (current != null)
                        {
                            current.StartTime.TotalMilliseconds = paragraph.StartTime.TotalMilliseconds;
                            current.EndTime.TotalMilliseconds = paragraph.EndTime.TotalMilliseconds;

                            index = _subtitle.GetIndex(current);

                            SubtitleListview1.SetStartTimeAndDuration(index, paragraph, _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));

                            if (index == selectedIndex)
                            {
                                timeUpDownStartTime.TimeCode = paragraph.StartTime;
                                var durationInSeconds = (decimal)(paragraph.Duration.TotalSeconds);
                                if (durationInSeconds >= numericUpDownDuration.Minimum && durationInSeconds <= numericUpDownDuration.Maximum)
                                    SetDurationInSeconds((double)durationInSeconds);
                            }
                        }
                    }
                }
                else if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible)
                {
                    index = _subtitle.GetIndex(paragraph);
                    if (index >= 0)
                    {
                        // Make history item for rollback (change paragraph back for history + change again)
                        _subtitle.Paragraphs[index] = new Paragraph(beforeParagraph);
                        MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.VideoControls.BeforeChangingTimeInWaveformX, "#" + paragraph.Number + " " + paragraph.Text));
                        _subtitle.Paragraphs[index] = paragraph;
                        _makeHistoryPaused = true;

                        MovePrevNext(e, beforeParagraph, index);

                        var original = Utilities.GetOriginalParagraph(index, beforeParagraph, _subtitleAlternate.Paragraphs);
                        if (original != null)
                        {
                            original.StartTime.TotalMilliseconds = paragraph.StartTime.TotalMilliseconds;
                            original.EndTime.TotalMilliseconds = paragraph.EndTime.TotalMilliseconds;
                        }
                        SubtitleListview1.SetStartTimeAndDuration(index, paragraph, _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                    }
                }
                else
                {
                    if (index >= 0)
                    {
                        // Make history item for rollback (change paragraph back for history + change again)
                        _subtitle.Paragraphs[index] = new Paragraph(beforeParagraph);
                        MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.VideoControls.BeforeChangingTimeInWaveformX, "#" + paragraph.Number + " " + paragraph.Text));
                        _subtitle.Paragraphs[index] = paragraph;
                        _makeHistoryPaused = true;

                        MovePrevNext(e, beforeParagraph, index);

                        if (_subtitleAlternate != null)
                        {
                            var original = Utilities.GetOriginalParagraph(index, beforeParagraph, _subtitleAlternate.Paragraphs);
                            if (original != null)
                            {
                                original.StartTime.TotalMilliseconds = paragraph.StartTime.TotalMilliseconds;
                                original.EndTime.TotalMilliseconds = paragraph.EndTime.TotalMilliseconds;
                            }
                        }
                    }

                    SubtitleListview1.SetStartTimeAndDuration(index, paragraph, _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                }
                beforeParagraph.StartTime.TotalMilliseconds = paragraph.StartTime.TotalMilliseconds;
                beforeParagraph.EndTime.TotalMilliseconds = paragraph.EndTime.TotalMilliseconds;
                _makeHistoryPaused = false;

                if (Configuration.Settings.VideoControls.WaveformSetVideoPositionOnMoveStartEnd &&
                    (e.MouseDownParagraphType == AudioVisualizer.MouseDownParagraphType.Start ||
                     e.MouseDownParagraphType == AudioVisualizer.MouseDownParagraphType.End))
                {
                    mediaPlayer.CurrentPosition = e.Seconds;
                }
            }

            private void MovePrevNext(AudioVisualizer.ParagraphEventArgs e, Paragraph beforeParagraph, int index)
            {
                int curIdx = FirstSelectedIndex;
                if (e.MovePreviousOrNext && curIdx >= 0)
                {
                    if (e.MouseDownParagraphType == AudioVisualizer.MouseDownParagraphType.Start)
                    {
                        var prev = _subtitle.GetParagraphOrDefault(index - 1);
                        if (prev != null)
                        {
                            Paragraph originalPrev = null;
                            if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible)
                                originalPrev = Utilities.GetOriginalParagraph(index - 1, prev, _subtitleAlternate.Paragraphs);

                            prev.EndTime.TotalMilliseconds = prev.EndTime.TotalMilliseconds + (e.Paragraph.StartTime.TotalMilliseconds - beforeParagraph.StartTime.TotalMilliseconds);
                            SubtitleListview1.SetStartTimeAndDuration(index - 1, prev, _subtitle.GetParagraphOrDefault(index), _subtitle.GetParagraphOrDefault(index - 2));
                            audioVisualizer.Invalidate();

                            if (originalPrev != null)
                            {
                                originalPrev.EndTime.TotalMilliseconds = prev.EndTime.TotalMilliseconds;
                            }

                            if (curIdx == index - 1)
                            {
                                var durationInSeconds = (decimal)(prev.Duration.TotalSeconds);
                                if (durationInSeconds >= numericUpDownDuration.Minimum && durationInSeconds <= numericUpDownDuration.Maximum)
                                {
                                    SetDurationInSeconds((double)durationInSeconds);
                                }
                            }
                        }
                    }
                    else if (e.MouseDownParagraphType == AudioVisualizer.MouseDownParagraphType.End)
                    {
                        var next = _subtitle.GetParagraphOrDefault(index + 1);
                        if (next != null)
                        {
                            Paragraph originalNext = null;
                            if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible)
                                originalNext = Utilities.GetOriginalParagraph(index + 1, next, _subtitleAlternate.Paragraphs);

                            next.StartTime.TotalMilliseconds = next.StartTime.TotalMilliseconds + (e.Paragraph.EndTime.TotalMilliseconds - beforeParagraph.EndTime.TotalMilliseconds);
                            SubtitleListview1.SetStartTimeAndDuration(index + 1, next, _subtitle.GetParagraphOrDefault(index + 2), _subtitle.GetParagraphOrDefault(index));
                            audioVisualizer.Invalidate();

                            if (originalNext != null)
                            {
                                originalNext.StartTime.TotalMilliseconds = next.StartTime.TotalMilliseconds;
                            }

                            if (curIdx == index + 1)
                            {
                                timeUpDownStartTime.TimeCode = next.StartTime;
                                var durationInSeconds = (decimal)(next.Duration.TotalSeconds);
                                if (durationInSeconds >= numericUpDownDuration.Minimum && durationInSeconds <= numericUpDownDuration.Maximum)
                                {
                                    SetDurationInSeconds((double)durationInSeconds);
                                }
                            }
                        }
                    }
                }
            }

            private void AudioWaveform_OnPositionSelected(object sender, AudioVisualizer.ParagraphEventArgs e)
            {
                mediaPlayer.CurrentPosition = e.Seconds;
                if (e.Paragraph != null)
                    SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.GetIndex(e.Paragraph));
            }

            private void VideoPositionChanged(object sender, EventArgs e)
            {
                var tud = (TimeUpDown)sender;
                if (tud.Enabled)
                {
                    mediaPlayer.CurrentPosition = tud.TimeCode.TotalSeconds;
                }
            }

            private void Main_Load(object sender, EventArgs e)
            {
                splitContainer1.Panel1MinSize = 525;
                splitContainer1.Panel2MinSize = 250;
                splitContainerMain.Panel1MinSize = 200;
                splitContainerMain.Panel2MinSize = 220;

                if (Configuration.Settings.General.StartRememberPositionAndSize &&
                    !string.IsNullOrEmpty(Configuration.Settings.General.StartPosition))
                {
                    var parts = Configuration.Settings.General.StartPosition.Split(';');
                    if (parts.Length == 2)
                    {
                        int x;
                        int y;
                        if (int.TryParse(parts[0], out x) && int.TryParse(parts[1], out y))
                        {
                            if (x > -100 || y > -100)
                            {
                                Left = x;
                                Top = y;
                            }
                        }
                    }

                    if (Configuration.Settings.General.StartSize == "Maximized")
                    {
                        CenterFormOnCurrentScreen();
                        WindowState = FormWindowState.Maximized;
                        return;
                    }

                    parts = Configuration.Settings.General.StartSize.Split(';');
                    if (parts.Length == 2)
                    {
                        int x;
                        int y;
                        if (int.TryParse(parts[0], out x) && int.TryParse(parts[1], out y))
                        {
                            Width = x;
                            Height = y;
                        }
                    }

                    var ctrlScreen = Screen.FromControl(this);

                    if (ctrlScreen.Bounds.Width < Width)
                        Width = ctrlScreen.Bounds.Width;
                    if (ctrlScreen.Bounds.Height < Height)
                        Height = ctrlScreen.Bounds.Height;

                    // Fix main window coordinate (Multi-Monitor issue)
                    if ((ctrlScreen.Bounds.Right < Left) || (ctrlScreen.Bounds.Bottom < Top) ||
                        (ctrlScreen.Bounds.X > Right) || (ctrlScreen.Bounds.Y > Top))
                    {
                        CenterToScreen();
                    }
                }
                else
                {
                    CenterFormOnCurrentScreen();
                }
            }

            private void InitializeLanguage()
            {
                fileToolStripMenuItem.Text = _language.Menu.File.Title;
                newToolStripMenuItem.Text = _language.Menu.File.New;
                openToolStripMenuItem.Text = _language.Menu.File.Open;
                toolStripMenuItemOpenKeepVideo.Text = _language.Menu.File.OpenKeepVideo;
                reopenToolStripMenuItem.Text = _language.Menu.File.Reopen;
                saveToolStripMenuItem.Text = _language.Menu.File.Save;
                saveAsToolStripMenuItem.Text = _language.Menu.File.SaveAs;
                toolStripMenuItemRestoreAutoBackup.Text = _language.Menu.File.RestoreAutoBackup;
                openOriginalToolStripMenuItem.Text = _language.Menu.File.OpenOriginal;
                saveOriginalToolStripMenuItem.Text = _language.Menu.File.SaveOriginal;
                saveOriginalAstoolStripMenuItem.Text = _language.SaveOriginalSubtitleAs;
                removeOriginalToolStripMenuItem.Text = _language.Menu.File.CloseOriginal;

                toolStripMenuItemOpenContainingFolder.Text = _language.Menu.File.OpenContainingFolder;
                toolStripMenuItemCompare.Text = _language.Menu.File.Compare;
                toolStripMenuItemStatistics.Text = _language.Menu.File.Statistics;
                toolStripMenuItemPlugins.Text = _language.Menu.File.Plugins;
                toolStripMenuItemImportDvdSubtitles.Text = _language.Menu.File.ImportOcrFromDvd;
                toolStripMenuItemSubIdx.Text = _language.Menu.File.ImportOcrVobSubSubtitle;
                toolStripButtonGetFrameRate.ToolTipText = _language.GetFrameRateFromVideoFile;
                toolStripMenuItemImportBluRaySup.Text = _language.Menu.File.ImportBluRaySupFile;
                toolStripMenuItemImportXSub.Text = _language.Menu.File.ImportXSub;
                matroskaImportStripMenuItem.Text = _language.Menu.File.ImportSubtitleFromMatroskaFile;
                toolStripMenuItemManualAnsi.Text = _language.Menu.File.ImportSubtitleWithManualChosenEncoding;
                toolStripMenuItemImportText.Text = _language.Menu.File.ImportText;
                toolStripMenuItemImportImages.Text = _language.Menu.File.ImportImages;
                toolStripMenuItemImportTimeCodes.Text = _language.Menu.File.ImportTimecodes;
                toolStripMenuItemExport.Text = _language.Menu.File.Export;
                toolStripMenuItemExportPngXml.Text = _language.Menu.File.ExportBdnXml;
                bluraySupToolStripMenuItem.Text = _language.Menu.File.ExportBluRaySup;
                adobeEncoreFABImageScriptToolStripMenuItem.Text = _language.Menu.File.ExportAdobeEncoreFabImageScript;
                toolStripMenuItemTextTimeCodePair.Text = _language.Menu.File.ExportKoreanAtsFilePair;
                vobSubsubidxToolStripMenuItem.Text = _language.Menu.File.ExportVobSub;
                toolStripMenuItemCavena890.Text = _language.Menu.File.ExportCavena890;
                eBUSTLToolStripMenuItem.Text = _language.Menu.File.ExportEbu;
                pACScreenElectronicsToolStripMenuItem.Text = _language.Menu.File.ExportPac;
                plainTextToolStripMenuItem.Text = _language.Menu.File.ExportPlainText;
                toolStripMenuItemAvidStl.Text = _language.Menu.File.ExportAvidStl;
                toolStripMenuItemExportCapMakerPlus.Text = _language.Menu.File.ExportCapMakerPlus;
                toolStripMenuItemExportCaptionInc.Text = _language.Menu.File.ExportCaptionsInc;
                toolStripMenuItemExportCheetahCap.Text = _language.Menu.File.ExportCheetahCap;
                toolStripMenuItemExportUltech130.Text = _language.Menu.File.ExportUltech130;
                exportCustomTextFormatToolStripMenuItem.Text = _language.Menu.File.ExportCustomTextFormat;
                exitToolStripMenuItem.Text = _language.Menu.File.Exit;

                editToolStripMenuItem.Text = _language.Menu.Edit.Title;
                showHistoryforUndoToolStripMenuItem.Text = _language.Menu.Edit.ShowUndoHistory;
                toolStripMenuItemUndo.Text = _language.Menu.Edit.Undo;
                toolStripMenuItemRedo.Text = _language.Menu.Edit.Redo;

                toolStripMenuItemInsertUnicodeCharacter.Text = _language.Menu.Edit.InsertUnicodeSymbol;

                findToolStripMenuItem.Text = _language.Menu.Edit.Find;
                findNextToolStripMenuItem.Text = _language.Menu.Edit.FindNext;
                replaceToolStripMenuItem.Text = _language.Menu.Edit.Replace;
                multipleReplaceToolStripMenuItem.Text = _language.Menu.Edit.MultipleReplace;
                gotoLineNumberToolStripMenuItem.Text = _language.Menu.Edit.GoToSubtitleNumber;
                toolStripMenuItemRightToLeftMode.Text = _language.Menu.Edit.RightToLeftMode;

                toolStripMenuItemRtlUnicodeControlChars.Text = _language.Menu.Edit.FixTrlViaUnicodeControlCharacters;

                toolStripMenuItemReverseRightToLeftStartEnd.Text = _language.Menu.Edit.ReverseRightToLeftStartEnd;
                toolStripMenuItemModifySelection.Text = _language.Menu.Edit.ModifySelection;
                toolStripMenuItemInverseSelection.Text = _language.Menu.Edit.InverseSelection;
                editSelectAllToolStripMenuItem.Text = _language.Menu.ContextMenu.SelectAll;

                toolsToolStripMenuItem.Text = _language.Menu.Tools.Title;
                adjustDisplayTimeToolStripMenuItem.Text = _language.Menu.Tools.AdjustDisplayDuration;
                toolStripMenuItemApplyDurationLimits.Text = _language.Menu.Tools.ApplyDurationLimits;
                toolStripMenuItemDurationBridgeGaps.Text = _language.Menu.Tools.DurationsBridgeGap;
                fixToolStripMenuItem.Text = _language.Menu.Tools.FixCommonErrors;
                startNumberingFromToolStripMenuItem.Text = _language.Menu.Tools.StartNumberingFrom;
                removeTextForHearImpairedToolStripMenuItem.Text = _language.Menu.Tools.RemoveTextForHearingImpaired;
                ChangeCasingToolStripMenuItem.Text = _language.Menu.Tools.ChangeCasing;
                toolStripMenuItemChangeFrameRate2.Text = _language.Menu.Tools.ChangeFrameRate;
                changeSpeedInPercentToolStripMenuItem.Text = _language.Menu.Tools.ChangeSpeedInPercent;
                toolStripMenuItemAutoMergeShortLines.Text = _language.Menu.Tools.MergeShortLines;
                toolStripMenuItemMergeDuplicateText.Text = _language.Menu.Tools.MergeDuplicateText;
                toolStripMenuItemMergeLinesWithSameTimeCodes.Text = _language.Menu.Tools.MergeSameTimeCodes;
                toolStripMenuItemAutoSplitLongLines.Text = _language.Menu.Tools.SplitLongLines;
                setMinimumDisplayTimeBetweenParagraphsToolStripMenuItem.Text = _language.Menu.Tools.MinimumDisplayTimeBetweenParagraphs;
                toolStripMenuItem1.Text = _language.Menu.Tools.SortBy;
                toolStripButtonNetflixQualityCheck.Text = _language.Menu.Tools.NetflixQualityCheck;

                sortNumberToolStripMenuItem.Text = _language.Menu.Tools.Number;
                sortStartTimeToolStripMenuItem.Text = _language.Menu.Tools.StartTime;
                sortEndTimeToolStripMenuItem.Text = _language.Menu.Tools.EndTime;
                sortDisplayTimeToolStripMenuItem.Text = _language.Menu.Tools.Duration;

                descendingToolStripMenuItem.Text = _language.Menu.Tools.Descending;
                AscendingToolStripMenuItem.Text = _language.Menu.Tools.Ascending;

                sortTextAlphabeticallytoolStripMenuItem.Text = _language.Menu.Tools.TextAlphabetically;
                sortTextMaxLineLengthToolStripMenuItem.Text = _language.Menu.Tools.TextSingleLineMaximumLength;
                sortTextTotalLengthToolStripMenuItem.Text = _language.Menu.Tools.TextTotalLength;
                sortTextNumberOfLinesToolStripMenuItem.Text = _language.Menu.Tools.TextNumberOfLines;
                textCharssecToolStripMenuItem.Text = _language.Menu.Tools.TextNumberOfCharactersPerSeconds;
                textWordsPerMinutewpmToolStripMenuItem.Text = _language.Menu.Tools.WordsPerMinute;
                styleToolStripMenuItem.Text = _language.Menu.Tools.Style;
                actorToolStripMenuItem.Text = Configuration.Settings.Language.General.Actor;

                toolStripMenuItemShowOriginalInPreview.Text = _language.Menu.Edit.ShowOriginalTextInAudioAndVideoPreview;
                toolStripMenuItemMakeEmptyFromCurrent.Text = _language.Menu.Tools.MakeNewEmptyTranslationFromCurrentSubtitle;
                toolStripMenuItemBatchConvert.Text = _language.Menu.Tools.BatchConvert;
                generateDatetimeInfoFromVideoToolStripMenuItem.Text = _language.Menu.Tools.GenerateTimeAsText;
                toolStripMenuItemMeasurementConverter.Text = _language.Menu.Tools.MeasurementConverter;
                splitToolStripMenuItem.Text = _language.Menu.Tools.SplitSubtitle;
                appendTextVisuallyToolStripMenuItem.Text = _language.Menu.Tools.AppendSubtitle;
                joinSubtitlesToolStripMenuItem.Text = _language.Menu.Tools.JoinSubtitles;

                toolStripMenuItemVideo.Text = _language.Menu.Video.Title;
                openVideoToolStripMenuItem.Text = _language.Menu.Video.OpenVideo;
                toolStripMenuItemOpenDvd.Text = _language.Menu.Video.OpenDvd; // TODO: Remove in SE 3.4
                toolStripMenuItemSetAudioTrack.Text = _language.Menu.Video.ChooseAudioTrack;
                closeVideoToolStripMenuItem.Text = _language.Menu.Video.CloseVideo;

                smpteTimeModedropFrameToolStripMenuItem.Text = _language.Menu.Video.SmptTimeMode;
                toolStripMenuItemImportSceneChanges.Text = _language.Menu.Video.ImportSceneChanges;
                toolStripMenuItemRemoveSceneChanges.Text = _language.Menu.Video.RemoveSceneChanges;

                toolStripMenuItemAddWaveformBatch.Text = _language.Menu.Video.WaveformBatchGenerate;

                if (Configuration.Settings.VideoControls.GenerateSpectrogram)
                    showhideWaveformToolStripMenuItem.Text = _language.Menu.Video.ShowHideWaveformAndSpectrogram;
                else
                    showhideWaveformToolStripMenuItem.Text = _language.Menu.Video.ShowHideWaveform;

                showhideVideoToolStripMenuItem.Text = _language.Menu.Video.ShowHideVideo;
                undockVideoControlsToolStripMenuItem.Text = _language.Menu.Video.UnDockVideoControls;
                redockVideoControlsToolStripMenuItem.Text = _language.Menu.Video.ReDockVideoControls;

                toolStripMenuItemSpellCheckMain.Text = _language.Menu.SpellCheck.Title;
                spellCheckToolStripMenuItem.Text = _language.Menu.SpellCheck.SpellCheck;
                toolStripMenuItemSpellCheckFromCurrentLine.Text = _language.Menu.SpellCheck.SpellCheckFromCurrentLine;
                findDoubleWordsToolStripMenuItem.Text = _language.Menu.SpellCheck.FindDoubleWords;
                FindDoubleLinesToolStripMenuItem.Text = _language.Menu.SpellCheck.FindDoubleLines;
                GetDictionariesToolStripMenuItem.Text = _language.Menu.SpellCheck.GetDictionaries;
                addWordToNameListToolStripMenuItem.Text = _language.Menu.SpellCheck.AddToNameList;

                toolStripMenuItemSynchronization.Text = _language.Menu.Synchronization.Title;
                toolStripMenuItemAdjustAllTimes.Text = _language.Menu.Synchronization.AdjustAllTimes;
                visualSyncToolStripMenuItem.Text = _language.Menu.Synchronization.VisualSync;
                toolStripMenuItemPointSync.Text = _language.Menu.Synchronization.PointSync;
                pointSyncViaOtherSubtitleToolStripMenuItem.Text = _language.Menu.Synchronization.PointSyncViaOtherSubtitle;

                toolStripMenuItemAutoTranslate.Text = _language.Menu.AutoTranslate.Title;
                translateByGoogleToolStripMenuItem.Text = _language.Menu.AutoTranslate.TranslatePoweredByGoogle;
                translatepoweredByMicrosoftToolStripMenuItem.Text = _language.Menu.AutoTranslate.TranslatePoweredByMicrosoft;
                translatepoweredByMicrosoftToolStripMenuItem.Visible = !string.IsNullOrEmpty(Configuration.Settings.Tools.MicrosoftTranslatorApiKey);
                translateFromSwedishToDanishToolStripMenuItem.Text = _language.Menu.AutoTranslate.TranslateFromSwedishToDanish;

                optionsToolStripMenuItem.Text = _language.Menu.Options.Title;
                settingsToolStripMenuItem.Text = _language.Menu.Options.Settings;
                changeLanguageToolStripMenuItem.Text = _language.Menu.Options.ChooseLanguage + " [" + Configuration.Settings.Language.Name + "]";

                toolStripMenuItemNetworking.Text = _language.Menu.Networking.Title;
                startServerToolStripMenuItem.Text = _language.Menu.Networking.StartNewSession;
                joinSessionToolStripMenuItem.Text = _language.Menu.Networking.JoinSession;
                showSessionKeyLogToolStripMenuItem.Text = _language.Menu.Networking.ShowSessionInfoAndLog;
                chatToolStripMenuItem.Text = _language.Menu.Networking.Chat;
                leaveSessionToolStripMenuItem.Text = _language.Menu.Networking.LeaveSession;

                checkForUpdatesToolStripMenuItem.Text = _language.Menu.Help.CheckForUpdates;
                helpToolStripMenuItem.Text = _language.Menu.Help.Title;
                helpToolStripMenuItem1.Text = _language.Menu.Help.Help;
                aboutToolStripMenuItem.Text = _language.Menu.Help.About;

                toolStripButtonFileNew.ToolTipText = _language.Menu.ToolBar.New;
                toolStripButtonFileOpen.ToolTipText = _language.Menu.ToolBar.Open;
                toolStripButtonSave.ToolTipText = _language.Menu.ToolBar.Save;
                toolStripButtonSaveAs.ToolTipText = _language.Menu.ToolBar.SaveAs;
                toolStripButtonFind.ToolTipText = _language.Menu.ToolBar.Find;
                toolStripButtonReplace.ToolTipText = _language.Menu.ToolBar.Replace;
                toolStripButtonFixCommonErrors.ToolTipText = _language.Menu.ToolBar.FixCommonErrors;
                toolStripButtonRemoveTextForHi.ToolTipText = _language.Menu.ToolBar.RemoveTextForHi;
                toolStripButtonVisualSync.ToolTipText = _language.Menu.ToolBar.VisualSync;
                toolStripButtonSpellCheck.ToolTipText = _language.Menu.ToolBar.SpellCheck;
                toolStripButtonNetflixQualityCheck.ToolTipText = _language.Menu.ToolBar.NetflixQualityCheck;
                toolStripButtonSettings.ToolTipText = _language.Menu.ToolBar.Settings;
                toolStripButtonHelp.ToolTipText = _language.Menu.ToolBar.Help;
                toolStripButtonToggleWaveform.ToolTipText = _language.Menu.ToolBar.ShowHideWaveform;
                toolStripButtonToggleVideo.ToolTipText = _language.Menu.ToolBar.ShowHideVideo;

                toolStripMenuItemAssStyles.Text = _language.Menu.ContextMenu.SubStationAlphaStyles;
                setStylesForSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.SubStationAlphaSetStyle;
                setActorForSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.SetActor;

                toolStripMenuItemDelete.Text = _language.Menu.ContextMenu.Delete;
                insertLineToolStripMenuItem.Text = _language.Menu.ContextMenu.InsertFirstLine;
                toolStripMenuItemInsertBefore.Text = _language.Menu.ContextMenu.InsertBefore;
                toolStripMenuItemInsertAfter.Text = _language.Menu.ContextMenu.InsertAfter;
                toolStripMenuItemInsertSubtitle.Text = _language.Menu.ContextMenu.InsertSubtitleAfter;

                toolStripMenuItemCopySourceText.Text = _language.Menu.ContextMenu.CopyToClipboard;

                toolStripMenuItemColumn.Text = _language.Menu.ContextMenu.Column;
                columnDeleteTextOnlyToolStripMenuItem.Text = _language.Menu.ContextMenu.ColumnDeleteText;
                toolStripMenuItemColumnDeleteText.Text = _language.Menu.ContextMenu.ColumnDeleteTextAndShiftCellsUp;
                ShiftTextCellsDownToolStripMenuItem.Text = _language.Menu.ContextMenu.ColumnInsertEmptyTextAndShiftCellsDown;
                toolStripMenuItemInsertTextFromSub.Text = _language.Menu.ContextMenu.ColumnInsertTextFromSubtitle;
                toolStripMenuItemColumnImportText.Text = _language.Menu.ContextMenu.ColumnImportTextAndShiftCellsDown;
                toolStripMenuItemPasteSpecial.Text = _language.Menu.ContextMenu.ColumnPasteFromClipboard;
                moveTextUpToolStripMenuItem.Text = _language.Menu.ContextMenu.ColumnTextUp;
                moveTextDownToolStripMenuItem.Text = _language.Menu.ContextMenu.ColumnTextDown;
                copyOriginalTextToCurrentToolStripMenuItem.Text = _language.Menu.ContextMenu.ColumnCopyOriginalTextToCurrent;

                splitLineToolStripMenuItem.Text = _language.Menu.ContextMenu.Split;
                toolStripMenuItemMergeLines.Text = _language.Menu.ContextMenu.MergeSelectedLines;
                toolStripMenuItemMergeDialog.Text = _language.Menu.ContextMenu.MergeSelectedLinesAsDialog;
                mergeBeforeToolStripMenuItem.Text = _language.Menu.ContextMenu.MergeWithLineBefore;
                mergeAfterToolStripMenuItem.Text = _language.Menu.ContextMenu.MergeWithLineAfter;
                normalToolStripMenuItem.Text = _language.Menu.ContextMenu.Normal;
                boldToolStripMenuItem.Text = _languageGeneral.Bold;
                underlineToolStripMenuItem.Text = _language.Menu.ContextMenu.Underline;
                italicToolStripMenuItem.Text = _languageGeneral.Italic;
                colorToolStripMenuItem.Text = _language.Menu.ContextMenu.Color;
                toolStripMenuItemFont.Text = _language.Menu.ContextMenu.FontName;
                toolStripMenuItemAlignment.Text = _language.Menu.ContextMenu.Alignment;
                toolStripMenuItemAutoBreakLines.Text = _language.Menu.ContextMenu.AutoBalanceSelectedLines;
                toolStripMenuItemUnbreakLines.Text = _language.Menu.ContextMenu.RemoveLineBreaksFromSelectedLines;
                typeEffectToolStripMenuItem.Text = _language.Menu.ContextMenu.TypewriterEffect;
                karokeeEffectToolStripMenuItem.Text = _language.Menu.ContextMenu.KaraokeEffect;
                showSelectedLinesEarlierlaterToolStripMenuItem.Text = _language.Menu.ContextMenu.ShowSelectedLinesEarlierLater;
                visualSyncSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.VisualSyncSelectedLines;
                toolStripMenuItemGoogleMicrosoftTranslateSelLine.Text = _language.Menu.ContextMenu.GoogleAndMicrosoftTranslateSelectedLine;
                googleTranslateSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.GoogleTranslateSelectedLines;
                adjustDisplayTimeForSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.AdjustDisplayDurationForSelectedLines;
                fixCommonErrorsInSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.FixCommonErrorsInSelectedLines;
                changeCasingForSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.ChangeCasingForSelectedLines;
                toolStripMenuItemSaveSelectedLines.Text = _language.Menu.ContextMenu.SaveSelectedLines;

                // textbox context menu
                cutToolStripMenuItem.Text = _language.Menu.ContextMenu.Cut;
                copyToolStripMenuItem.Text = _language.Menu.ContextMenu.Copy;
                pasteToolStripMenuItem.Text = _language.Menu.ContextMenu.Paste;
                deleteToolStripMenuItem.Text = _language.Menu.ContextMenu.Delete;
                toolStripMenuItemSplitTextAtCursor.Text = _language.Menu.ContextMenu.SplitLineAtCursorPosition;
                toolStripMenuItemSplitViaWaveform.Text = _language.Menu.ContextMenu.SplitLineAtCursorAndWaveformPosition;
                selectAllToolStripMenuItem.Text = _language.Menu.ContextMenu.SelectAll;
                normalToolStripMenuItem1.Text = _language.Menu.ContextMenu.Normal;
                boldToolStripMenuItem1.Text = _languageGeneral.Bold;
                italicToolStripMenuItem1.Text = _languageGeneral.Italic;
                underlineToolStripMenuItem1.Text = _language.Menu.ContextMenu.Underline;
                colorToolStripMenuItem1.Text = _language.Menu.ContextMenu.Color;
                fontNameToolStripMenuItem.Text = _language.Menu.ContextMenu.FontName;
                toolStripMenuItemInsertUnicodeSymbol.Text = _language.Menu.Edit.InsertUnicodeSymbol;
                toolStripMenuItemInsertUnicodeControlCharacters.Text = _language.Menu.Edit.InsertUnicodeControlCharacters;
                leftToolStripMenuItem.Text = _language.Menu.Edit.InsertUnicodeControlCharactersLRM;
                righttoleftMarkToolStripMenuItem.Text = _language.Menu.Edit.InsertUnicodeControlCharactersRLM;
                startOfLefttorightEmbeddingLREToolStripMenuItem.Text = _language.Menu.Edit.InsertUnicodeControlCharactersLRE;
                startOfRighttoleftEmbeddingRLEToolStripMenuItem.Text = _language.Menu.Edit.InsertUnicodeControlCharactersRLE;
                startOfLefttorightOverrideLROToolStripMenuItem.Text = _language.Menu.Edit.InsertUnicodeControlCharactersLRO;
                startOfRighttoleftOverrideRLOToolStripMenuItem.Text = _language.Menu.Edit.InsertUnicodeControlCharactersRLO;

                // main controls
                SubtitleListview1.InitializeLanguage(_languageGeneral, Configuration.Settings);
                toolStripLabelSubtitleFormat.Text = _language.Controls.SubtitleFormat;
                toolStripLabelEncoding.Text = _language.Controls.FileEncoding;
                toolStripLabelFrameRate.Text = _languageGeneral.FrameRate;
                tabControlSubtitle.TabPages[TabControlSourceView].Text = _language.Controls.SourceView;
                tabControlSubtitle.TabPages[TabControlListView].Text = _language.Controls.ListView;
                labelStartTime.Text = _languageGeneral.StartTime;
                labelDuration.Text = _languageGeneral.Duration;
                labelText.Text = _languageGeneral.Text;
                UpdateListViewTextInfo(labelTextLineLengths, labelSingleLine, labelTextLineTotal, labelCharactersPerSecond, _subtitle?.GetParagraphOrDefault(_subtitleListViewIndex), textBoxListViewText);
                labelAlternateText.Text = _languageGeneral.OriginalText;
                UpdateListViewTextInfo(labelTextAlternateLineLengths, labelAlternateSingleLine, labelTextAlternateLineTotal, labelAlternateCharactersPerSecond, _subtitleAlternate?.GetParagraphOrDefault(_subtitleListViewIndex), textBoxListViewTextAlternate);
                buttonPrevious.Text = _language.Controls.Previous;
                buttonNext.Text = _language.Controls.Next;
                buttonAutoBreak.Text = _language.Controls.AutoBreak;
                buttonUnBreak.Text = _language.Controls.Unbreak;
                buttonSplitLine.Text = _languageGeneral.SplitLine;
                ShowSourceLineNumber();

                // video controls
                tabPageTranslate.Text = _language.VideoControls.Translate + "  ";
                tabPageCreate.Text = _language.VideoControls.Create + "  ";
                tabPageAdjust.Text = _language.VideoControls.Adjust + "  ";
                checkBoxSyncListViewWithVideoWhilePlaying.Text = _language.VideoControls.SelectCurrentElementWhilePlaying;
                if (_videoFileName == null)
                    labelVideoInfo.Text = _languageGeneral.NoVideoLoaded;
                toolStripButtonLockCenter.Text = _language.VideoControls.Center;
                toolStripSplitButtonPlayRate.Text = _language.VideoControls.PlayRate;
                toolStripMenuItemPlayRateSlow.Text = _language.VideoControls.Slow;
                toolStripMenuItemPlayRateNormal.Text = _language.VideoControls.Normal;
                toolStripMenuItemPlayRateFast.Text = _language.VideoControls.Fast;
                toolStripMenuItemPlayRateVeryFast.Text = _language.VideoControls.VeryFast;

                groupBoxAutoRepeat.Text = _language.VideoControls.AutoRepeat;
                checkBoxAutoRepeatOn.Text = _language.VideoControls.AutoRepeatOn;
                labelAutoRepeatCount.Text = _language.VideoControls.AutoRepeatCount;
                groupBoxAutoContinue.Text = _language.VideoControls.AutoContinue;
                checkBoxAutoContinue.Text = _language.VideoControls.AutoContinueOn;
                labelAutoContinueDelay.Text = _language.VideoControls.DelayInSeconds;
                buttonPlayPrevious.Text = _language.VideoControls.Previous;
                buttonPlayCurrent.Text = _language.VideoControls.PlayCurrent;
                buttonPlayNext.Text = _language.VideoControls.Next;
                buttonStop.Text = _language.VideoControls.Pause;
                groupBoxTranslateSearch.Text = _language.VideoControls.SearchTextOnline;
                buttonGoogleIt.Text = _language.VideoControls.GoogleIt;
                buttonGoogleTranslateIt.Text = _language.VideoControls.GoogleTranslate;
                labelTranslateTip.Text = _language.VideoControls.TranslateTip;

                buttonInsertNewText.Text = _language.VideoControls.InsertNewSubtitleAtVideoPosition;
                buttonBeforeText.Text = _language.VideoControls.PlayFromJustBeforeText;
                buttonGotoSub.Text = _language.VideoControls.GoToSubtitlePositionAndPause;
                buttonSetStartTime.Text = _language.VideoControls.SetStartTime;
                buttonSetEnd.Text = _language.VideoControls.SetEndTime;
                buttonSecBack1.Text = _language.VideoControls.SecondsBackShort;
                buttonSecBack2.Text = _language.VideoControls.SecondsBackShort;
                buttonForward1.Text = _language.VideoControls.SecondsForwardShort;
                buttonForward2.Text = _language.VideoControls.SecondsForwardShort;
                labelVideoPosition.Text = _language.VideoControls.VideoPosition;
                labelVideoPosition2.Text = _language.VideoControls.VideoPosition;
                labelCreateTip.Text = _language.VideoControls.CreateTip;

                buttonSetStartAndOffsetRest.Text = _language.VideoControls.SetstartTimeAndOffsetOfRest;
                buttonSetEndAndGoToNext.Text = _language.VideoControls.SetEndTimeAndGoToNext;
                buttonAdjustSetStartTime.Text = _language.VideoControls.SetStartTime;
                buttonAdjustSetEndTime.Text = _language.VideoControls.SetEndTime;
                buttonAdjustPlayBefore.Text = _language.VideoControls.PlayFromJustBeforeText;
                buttonAdjustGoToPosAndPause.Text = _language.VideoControls.GoToSubtitlePositionAndPause;
                buttonAdjustSecBack1.Text = _language.VideoControls.SecondsBackShort;
                buttonAdjustSecBack2.Text = _language.VideoControls.SecondsBackShort;
                buttonAdjustSecForward1.Text = _language.VideoControls.SecondsForwardShort;
                buttonAdjustSecForward2.Text = _language.VideoControls.SecondsForwardShort;
                labelAdjustTip.Text = _language.VideoControls.CreateTip;

                // waveform
                var languageWaveform = Configuration.Settings.Language.Waveform;
                addParagraphHereToolStripMenuItem.Text = languageWaveform.AddParagraphHere;
                addParagraphAndPasteToolStripMenuItem.Text = languageWaveform.AddParagraphHereAndPasteText;
                deleteParagraphToolStripMenuItem.Text = languageWaveform.DeleteParagraph;
                toolStripMenuItemFocusTextbox.Text = languageWaveform.FocusTextBox;

                splitToolStripMenuItem1.Text = languageWaveform.Split;
                mergeWithPreviousToolStripMenuItem.Text = languageWaveform.MergeWithPrevious;
                mergeWithNextToolStripMenuItem.Text = languageWaveform.MergeWithNext;
                toolStripMenuItemWaveformPlaySelection.Text = languageWaveform.PlaySelection;
                showWaveformAndSpectrogramToolStripMenuItem.Text = languageWaveform.ShowWaveformAndSpectrogram;
                showOnlyWaveformToolStripMenuItem.Text = languageWaveform.ShowWaveformOnly;
                showOnlySpectrogramToolStripMenuItem.Text = languageWaveform.ShowSpectrogramOnly;
                seekSilenceToolStripMenuItem.Text = languageWaveform.SeekSilence;
                insertSubtitleHereToolStripMenuItem.Text = languageWaveform.InsertSubtitleHere;
                guessTimeCodesToolStripMenuItem.Text = languageWaveform.GuessTimeCodes;
                removeSceneChangeToolStripMenuItem.Text = languageWaveform.RemoveSceneChange;
                addSceneChangeToolStripMenuItem.Text = languageWaveform.AddSceneChange;

                toolStripButtonWaveformZoomOut.ToolTipText = languageWaveform.ZoomOut;
                toolStripButtonWaveformZoomIn.ToolTipText = languageWaveform.ZoomIn;

                if (Configuration.Settings.VideoControls.GenerateSpectrogram)
                    audioVisualizer.WaveformNotLoadedText = languageWaveform.ClickToAddWaveformAndSpectrogram;
                else
                    audioVisualizer.WaveformNotLoadedText = languageWaveform.ClickToAddWaveform;

                // clear cached language names
                DvdSubtitleLanguage.Initialize();
            }

            private void SetFormatTo(string subtitleFormatName)
            {
                SetFormatTo(FormatNameToFormat(subtitleFormatName));
            }

            private void SetFormatTo(SubtitleFormat subtitleFormat)
            {
                comboBoxSubtitleFormats.SelectedIndexChanged -= ComboBoxSubtitleFormatsSelectedIndexChanged;
                UiUtil.InitializeSubtitleFormatComboBox(comboBoxSubtitleFormats, subtitleFormat.FriendlyName);
                comboBoxSubtitleFormats.SelectedIndexChanged += ComboBoxSubtitleFormatsSelectedIndexChanged;
            }

            private int FirstSelectedIndex
            {
                get
                {
                    if (SubtitleListview1.SelectedItems.Count == 0)
                        return -1;
                    return SubtitleListview1.SelectedItems[0].Index;
                }
            }

            private int FirstVisibleIndex
            {
                get
                {
                    if (SubtitleListview1.Items.Count == 0 || SubtitleListview1.TopItem == null)
                        return -1;
                    return SubtitleListview1.TopItem.Index;
                }
            }

            private bool ContinueNewOrExit()
            {
                string currentSubtitleHash = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                if (_changeSubtitleToString != currentSubtitleHash && _lastDoNotPrompt != currentSubtitleHash && _subtitle?.Paragraphs.Count > 0)
                {
                    string promptText = _language.SaveChangesToUntitled;
                    if (!string.IsNullOrEmpty(_fileName))
                        promptText = string.Format(_language.SaveChangesToX, _fileName);

                    var dr = MessageBox.Show(this, promptText, Title, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);

                    if (dr == DialogResult.Cancel)
                        return false;

                    if (dr == DialogResult.Yes)
                    {
                        if (string.IsNullOrEmpty(_fileName))
                        {
                            if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                                saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;
                            saveFileDialog1.Title = _language.SaveSubtitleAs;
                            if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                            {
                                openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                                _fileName = saveFileDialog1.FileName;
                                SetTitle();
                                Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                                Configuration.Settings.Save();
                            }
                            else
                            {
                                return false;
                            }
                        }
                        if (SaveSubtitle(GetCurrentSubtitleFormat()) != DialogResult.OK)
                            return false;
                    }
                }

                return ContinueNewOrExitAlternate();
            }

            private bool ContinueNewOrExitAlternate()
            {
                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0 && _changeAlternateSubtitleToString != _subtitleAlternate.ToText(new SubRip()).Trim())
                {
                    string promptText = _language.SaveChangesToUntitledOriginal;
                    if (!string.IsNullOrEmpty(_subtitleAlternateFileName))
                        promptText = string.Format(_language.SaveChangesToOriginalX, _subtitleAlternateFileName);

                    var dr = MessageBox.Show(this, promptText, Title, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);

                    if (dr == DialogResult.Cancel)
                        return false;

                    if (dr == DialogResult.Yes)
                    {
                        if (string.IsNullOrEmpty(_subtitleAlternateFileName))
                        {
                            if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                                saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;
                            saveFileDialog1.Title = _language.SaveOriginalSubtitleAs;
                            if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                            {
                                openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                                _subtitleAlternateFileName = saveFileDialog1.FileName;
                            }
                            else
                            {
                                return false;
                            }
                        }
                        if (SaveOriginalSubtitle(GetCurrentSubtitleFormat()) != DialogResult.OK)
                            return false;
                    }
                }
                _lastDoNotPrompt = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                return true;
            }

            private void ExitToolStripMenuItemClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                Application.Exit();
            }

            private void AboutToolStripMenuItemClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                using (var about = new About())
                {
                    about.Initialize();
                    about.ShowDialog(this);
                }
            }

            private void VisualSyncToolStripMenuItemClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                ShowVisualSync(false);
            }

            public void MakeHistoryForUndo(string description, bool resetTextUndo)
            {
                if (_makeHistoryPaused)
                    return;

                if (resetTextUndo)
                {
                    _listViewTextUndoLast = null;
                    _listViewAlternateTextUndoLast = null;
                }

                if (_undoIndex == -1)
                {
                    _subtitle.HistoryItems.Clear();
                }
                else
                {
                    // remove items for redo
                    while (_subtitle.HistoryItems.Count > _undoIndex + 1)
                        _subtitle.HistoryItems.RemoveAt(_subtitle.HistoryItems.Count - 1);
                }

                _subtitle.FileName = _fileName;
                _subtitle.MakeHistoryForUndo(description, GetCurrentSubtitleFormat(), _fileDateTime, _subtitleAlternate, _subtitleAlternateFileName, _subtitleListViewIndex, textBoxListViewText.SelectionStart, textBoxListViewTextAlternate.SelectionStart);
                _undoIndex++;

                if (_undoIndex > Subtitle.MaximumHistoryItems)
                    _undoIndex--;
            }

            public void MakeHistoryForUndo(string description)
            {
                MakeHistoryForUndo(description, true);
            }

            /// <summary>
            /// Add undo history - but only if last entry is older than 500 ms
            /// </summary>
            /// <param name="description">Undo description</param>
            public void MakeHistoryForUndoOnlyIfNotResent(string description)
            {
                if (_makeHistoryPaused)
                    return;

                if ((DateTime.UtcNow.Ticks - _lastHistoryTicks) > 10000 * 500) // only if last change was longer ago than 500 milliseconds
                {
                    MakeHistoryForUndo(description);
                    _lastHistoryTicks = DateTime.UtcNow.Ticks;
                }
            }

            private bool IsSubtitleLoaded
            {
                get
                {
                    return _subtitle != null && (_subtitle.Paragraphs.Count > 1 || (_subtitle.Paragraphs.Count == 1 && !string.IsNullOrWhiteSpace(_subtitle.Paragraphs[0].Text)));
                }
            }

            private void ShowVisualSync(bool onlySelectedLines)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                using (var visualSync = new VisualSync())
                {
                    visualSync.VideoFileName = _videoFileName;
                    visualSync.AudioTrackNumber = _videoAudioTrackNumber;

                    SaveSubtitleListviewIndices();
                    if (onlySelectedLines)
                    {
                        var selectedLines = new Subtitle { WasLoadedWithFrameNumbers = _subtitle.WasLoadedWithFrameNumbers };
                        Subtitle selectedLinesAlternate = null;
                        if (_subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                        {
                            selectedLinesAlternate = new Subtitle { WasLoadedWithFrameNumbers = _subtitle.WasLoadedWithFrameNumbers };
                        }

                        foreach (int index in SubtitleListview1.SelectedIndices)
                        {
                            var p = _subtitle.Paragraphs[index];
                            selectedLines.Paragraphs.Add(p);
                            if (selectedLinesAlternate != null)
                            {
                                var original = Utilities.GetOriginalParagraph(index, p, _subtitleAlternate.Paragraphs);
                                if (original != null)
                                {
                                    selectedLinesAlternate.Paragraphs.Add(original);
                                }
                            }
                        }
                        visualSync.Initialize(toolStripButtonVisualSync.Image as Bitmap, selectedLines, selectedLinesAlternate, _fileName, _language.VisualSyncSelectedLines, CurrentFrameRate);
                    }
                    else
                    {
                        visualSync.Initialize(toolStripButtonVisualSync.Image as Bitmap, _subtitle, _subtitleAlternate, _fileName, _language.VisualSyncTitle, CurrentFrameRate);
                    }

                    _endSeconds = -1;
                    mediaPlayer.Pause();
                    if (visualSync.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeVisualSync);

                        if (onlySelectedLines)
                        { // we only update selected lines
                            int i = 0;
                            foreach (int index in SubtitleListview1.SelectedIndices)
                            {
                                _subtitle.Paragraphs[index] = visualSync.Paragraphs[i];
                                i++;
                            }
                            ShowStatus(_language.VisualSyncPerformedOnSelectedLines);
                        }
                        else
                        {
                            _subtitle.Paragraphs.Clear();
                            foreach (var p in visualSync.Paragraphs)
                                _subtitle.Paragraphs.Add(new Paragraph(p));

                            if (_subtitleAlternate != null && visualSync.ParagraphsAlternate != null)
                            {
                                _subtitleAlternate.Paragraphs.Clear();
                                foreach (var p in visualSync.ParagraphsAlternate)
                                    _subtitleAlternate.Paragraphs.Add(new Paragraph(p));
                            }

                            ShowStatus(_language.VisualSyncPerformed);
                        }
                        if (visualSync.FrameRateChanged)
                            toolStripComboBoxFrameRate.Text = string.Format("{0:0.###}", visualSync.FrameRate);
                        if (IsFramesRelevant && CurrentFrameRate > 0)
                        {
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                            if (_subtitleAlternate != null)
                                _subtitleAlternate.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                            if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                                ShowSource();
                        }
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                        if (onlySelectedLines && SubtitleListview1.SelectedItems.Count > 0)
                        {
                            SubtitleListview1.EnsureVisible(SubtitleListview1.SelectedItems[SubtitleListview1.SelectedItems.Count - 1].Index);
                        }
                    }
                    _videoFileName = visualSync.VideoFileName;
                }
            }

            private void OpenToolStripMenuItemClick(object sender, EventArgs e)
            {
                openToolStripMenuItem.Enabled = false;
                ReloadFromSourceView();
                OpenNewFile();
                openToolStripMenuItem.Enabled = true;
            }

            private void OpenNewFile()
            {
                if (_openFileDialogOn)
                    return;
                _openFileDialogOn = true;
                _lastDoNotPrompt = string.Empty;
                if (!ContinueNewOrExit())
                {
                    _openFileDialogOn = false;
                    return;
                }
                openFileDialog1.Title = _languageGeneral.OpenSubtitle;
                openFileDialog1.FileName = string.Empty;
                openFileDialog1.Filter = UiUtil.SubtitleExtensionFilter.Value;
                if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    RemoveAlternate(true);

                    // try to open via recent files
                    var rfe = Configuration.Settings.RecentFiles.Files.FirstOrDefault(p => p.FileName.Equals(openFileDialog1.FileName, StringComparison.OrdinalIgnoreCase));
                    if (rfe != null)
                    {
                        OpenSubtitle(rfe.FileName, null, rfe.VideoFileName, rfe.OriginalFileName);
                        Configuration.Settings.General.CurrentVideoOffsetInMs = rfe.VideoOffsetInMs;
                        if (rfe.VideoOffsetInMs > 0)
                        {
                            _subtitle.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(-Configuration.Settings.General.CurrentVideoOffsetInMs));
                            _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                            SubtitleListview1.Fill(_subtitle);
                        }
                        GotoSubPosAndPause();
                        SetRecentIndices(openFileDialog1.FileName);
                        SubtitleListview1.EndUpdate();
                        if (!string.IsNullOrEmpty(rfe.VideoFileName))
                        {
                            var p = _subtitle.GetParagraphOrDefault(rfe.FirstSelectedIndex);
                            if (p != null)
                            {
                                mediaPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                            }
                        }
                        _openFileDialogOn = false;
                        return;
                    }

                    OpenSubtitle(openFileDialog1.FileName, null);
                }
                _openFileDialogOn = false;
            }

            public double CurrentFrameRate
            {
                get
                {
                    double f;
                    if (double.TryParse(toolStripComboBoxFrameRate.Text, out f))
                        return f;
                    return Configuration.Settings.General.DefaultFrameRate;
                }
            }

            private void OpenSubtitle(string fileName, Encoding encoding)
            {
                OpenSubtitle(fileName, encoding, null, null);
            }

            private void ResetHistory()
            {
                _undoIndex = -1;
                _subtitle.HistoryItems.Clear();
            }

            private void OpenSubtitle(string fileName, Encoding encoding, string videoFileName, string originalFileName)
            {
                if (File.Exists(fileName))
                {
                    bool videoFileLoaded = false;
                    var file = new FileInfo(fileName);
                    var ext = file.Extension.ToLowerInvariant();

                    // save last first visible index + first selected index from listview
                    if (!string.IsNullOrEmpty(_fileName))
                        Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, originalFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                    Configuration.Settings.General.CurrentVideoOffsetInMs = 0;

                    openFileDialog1.InitialDirectory = file.DirectoryName;

                    if (ext == ".idx")
                    {
                        var subFileName = fileName.Substring(0, fileName.Length - 3) + "sub";
                        if (File.Exists(subFileName) && FileUtil.IsVobSub(subFileName))
                        {
                            ext = ".sub";
                            fileName = subFileName;
                        }
                    }
                    if (ext == ".sub" && IsVobSubFile(fileName, false))
                    {
                        ImportAndOcrVobSubSubtitleNew(fileName, _loading);
                        return;
                    }

                    if (ext == ".sup")
                    {
                        if (FileUtil.IsBluRaySup(fileName))
                        {
                            ImportAndOcrBluRaySup(fileName, _loading);
                            return;
                        }
                        if (FileUtil.IsSpDvdSup(fileName))
                        {
                            ImportAndOcrSpDvdSup(fileName, _loading);
                            return;
                        }
                    }

                    if (ext == ".mkv" || ext == ".mks")
                    {
                        ImportSubtitleFromMatroskaFile(fileName);
                        return;
                    }

                    if (ext == ".divx" || ext == ".avi")
                    {
                        if (ImportSubtitleFromDivX(fileName))
                            return;
                    }

                    if ((ext == ".ts" || ext == ".rec" || ext == ".mpeg" || ext == ".mpg") && file.Length > 10000 && FileUtil.IsTransportStream(fileName))
                    {
                        ImportSubtitleFromTransportStream(fileName);
                        return;
                    }

                    if (((ext == ".m2ts" || ext == ".ts") && file.Length > 10000 && FileUtil.IsM2TransportStream(fileName)) ||
                        (ext == ".textst" && FileUtil.IsMpeg2PrivateStream2(fileName)))
                    {
                        bool isTextSt = false;
                        if (file.Length < 2000000)
                        {
                            var textSt = new TextST();
                            isTextSt = textSt.IsMine(null, fileName);
                        }

                        if (!isTextSt)
                        {
                            ImportSubtitleFromTransportStream(fileName);
                            return;
                        }
                    }

                    if ((ext == ".mp4" || ext == ".m4v" || ext == ".3gp") && file.Length > 10000)
                    {
                        if (!new IsmtDfxp().IsMine(null, fileName))
                        {
                            if (ImportSubtitleFromMp4(fileName) && !Configuration.Settings.General.DisableVideoAutoLoading)
                                OpenVideo(fileName);
                            return;
                        }
                    }

                    if (ext == ".mxf" && FileUtil.IsMaterialExchangeFormat(fileName))
                    {
                        var parser = new MxfParser(fileName);
                        if (parser.IsValid)
                        {
                            var subtitles = parser.GetSubtitles();
                            if (subtitles.Count > 0)
                            {
                                SetEncoding(Configuration.Settings.General.DefaultEncoding);
                                var list = new List<string>(subtitles[0].SplitToLines());
                                _subtitle = new Subtitle();
                                var mxfFormat = _subtitle.ReloadLoadSubtitle(list, null, null);
                                SetCurrentFormat(mxfFormat);
                                _fileName = Path.GetFileNameWithoutExtension(fileName);
                                SetTitle();
                                ShowStatus(string.Format(_language.LoadedSubtitleX, _fileName));
                                _sourceViewChange = false;
                                _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                                ResetHistory();
                                SetUndockedWindowsTitle();
                                _converted = true;
                                ShowStatus(string.Format(_language.LoadedSubtitleX, _fileName) + " - " + string.Format(_language.ConvertedToX, mxfFormat.FriendlyName));

                                ShowSource();
                                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                                _subtitleListViewIndex = -1;
                                SubtitleListview1.FirstVisibleIndex = -1;
                                SubtitleListview1.SelectIndexAndEnsureVisible(0);

                                return;
                            }
                            MessageBox.Show("No subtitles found!");
                            return;
                        }
                    }

                    if (file.Length > Subtitle.MaxFileSize)
                    {
                        // retry Blu-ray sup (file with wrong extension)
                        if (FileUtil.IsBluRaySup(fileName))
                        {
                            ImportAndOcrBluRaySup(fileName, _loading);
                            return;
                        }

                        // retry vobsub (file with wrong extension)
                        if (IsVobSubFile(fileName, false))
                        {
                            ImportAndOcrVobSubSubtitleNew(fileName, _loading);
                            return;
                        }

                        var text = string.Format(_language.FileXIsLargerThan10MB + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, fileName);
                        if (MessageBox.Show(this, text, Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                            return;
                    }

                    var tempSubtitle = new Subtitle(_subtitle, false);
                    if (_subtitle.HistoryItems.Count > 0 || _subtitle.Paragraphs.Count > 0)
                        MakeHistoryForUndo(string.Format(_language.BeforeLoadOf, Path.GetFileName(fileName)));

                    string subtitleHash = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                    bool hasChanged = (_changeSubtitleToString != subtitleHash) && (_lastDoNotPrompt != subtitleHash);

                    SubtitleFormat format = _subtitle.LoadSubtitle(fileName, out encoding, encoding);
                    if (format == null)
                        _subtitle = tempSubtitle;

                    if (!hasChanged)
                        _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);

                    ShowHideTextBasedFeatures(format);

                    bool justConverted = false;
                    if (format == null)
                    {
                        var ebu = new Ebu();
                        if (ebu.IsMine(null, fileName))
                        {
                            ebu.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = ebu;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var pac = new Pac();
                        if (pac.IsMine(null, fileName))
                        {
                            pac.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = pac;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (ext == ".m2ts" || ext == ".textst")
                    {
                        var textST = new TextST();
                        if (textST.IsMine(null, fileName))
                        {
                            textST.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = textST;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var pns = new Pns();
                        if (pns.IsMine(null, fileName))
                        {
                            pns.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = pns;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var cavena890 = new Cavena890();
                        if (cavena890.IsMine(null, fileName))
                        {
                            cavena890.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = cavena890;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var spt = new Spt();
                        if (spt.IsMine(null, fileName))
                        {
                            spt.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = spt;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null && ext == ".wsb")
                    {
                        var wsb = new Wsb();
                        var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                        if (wsb.IsMine(list, fileName))
                        {
                            wsb.LoadSubtitle(_subtitle, list, fileName);
                            _oldSubtitleFormat = wsb;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var cheetahCaption = new CheetahCaption();
                        if (cheetahCaption.IsMine(null, fileName))
                        {
                            cheetahCaption.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = cheetahCaption;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var cheetahCaption = new CheetahCaptionOld();
                        if (cheetahCaption.IsMine(null, fileName))
                        {
                            cheetahCaption.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = cheetahCaption;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var capMakerPlus = new CapMakerPlus();
                        if (capMakerPlus.IsMine(null, fileName))
                        {
                            capMakerPlus.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = capMakerPlus;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var captionsInc = new CaptionsInc();
                        if (captionsInc.IsMine(null, fileName))
                        {
                            captionsInc.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = captionsInc;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var ultech130 = new Ultech130();
                        if (ultech130.IsMine(null, fileName))
                        {
                            ultech130.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = ultech130;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var nciCaption = new NciCaption();
                        if (nciCaption.IsMine(null, fileName))
                        {
                            nciCaption.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = nciCaption;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var tsb4 = new TSB4();
                        if (tsb4.IsMine(null, fileName))
                        {
                            tsb4.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = tsb4;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var avidStl = new AvidStl();
                        if (avidStl.IsMine(null, fileName))
                        {
                            avidStl.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = avidStl;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var chk = new Chk();
                        if (chk.IsMine(null, fileName))
                        {
                            chk.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = chk;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var ayato = new Ayato();
                        if (ayato.IsMine(null, fileName))
                        {
                            ayato.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = ayato;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var pacUnicode = new PacUnicode();
                        if (pacUnicode.IsMine(null, fileName))
                        {
                            pacUnicode.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = pacUnicode;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var iai = new IaiSub();
                        if (iai.IsMine(null, fileName))
                        {
                            iai.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = iai;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var f = new DlDd();
                        var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                        if (f.IsMine(list, fileName))
                        {
                            f.LoadSubtitle(_subtitle, list, fileName);
                            _oldSubtitleFormat = f;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var f = new Ted20();
                        if (f.IsMine(null, fileName))
                        {
                            f.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = f;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var f = new TimeCodesOnly1();
                        var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                        if (f.IsMine(list, fileName))
                        {
                            f.LoadSubtitle(_subtitle, list, fileName);
                            _oldSubtitleFormat = f;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var f = new TimeCodesOnly2();
                        var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                        if (f.IsMine(list, fileName))
                        {
                            f.LoadSubtitle(_subtitle, list, fileName);
                            _oldSubtitleFormat = f;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var f = new JsonTypeOnlyLoad1();
                        var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                        if (f.IsMine(list, fileName))
                        {
                            f.LoadSubtitle(_subtitle, list, fileName);
                            _oldSubtitleFormat = f;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        try
                        {
                            var bdnXml = new BdnXml();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (bdnXml.IsMine(list, fileName))
                            {
                                if (ContinueNewOrExit())
                                {
                                    ImportAndOcrBdnXml(fileName, bdnXml, list);
                                }
                                return;
                            }
                        }
                        catch
                        {
                            // ignore
                        }
                    }

                    if (format == null)
                    {
                        try
                        {
                            var fcpImage = new FinalCutProImage();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (fcpImage.IsMine(list, fileName))
                            {
                                if (ContinueNewOrExit())
                                {
                                    ImportAndOcrDost(fileName, fcpImage, list);
                                }
                                return;
                            }
                        }
                        catch
                        {
                            // ignore
                        }
                    }

                    if (format == null)
                    {
                        try
                        {
                            var imageFormat = new SpuImage();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (imageFormat.IsMine(list, fileName))
                            {
                                if (ContinueNewOrExit())
                                {
                                    ImportAndOcrDost(fileName, imageFormat, list);
                                }
                                return;
                            }
                        }
                        catch
                        {
                            format = null;
                        }
                    }

                    if (format == null)
                    {
                        var elr = new ELRStudioClosedCaption();
                        if (elr.IsMine(null, fileName))
                        {
                            elr.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = elr;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var asc = new TimeLineAscii();
                        if (asc.IsMine(null, fileName))
                        {
                            asc.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = asc;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var asc = new TimeLineFootageAscii();
                        if (asc.IsMine(null, fileName))
                        {
                            asc.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = asc;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var mtv = new TimeLineMvt();
                        if (mtv.IsMine(null, fileName))
                        {
                            mtv.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = mtv;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var arib = new AribB36();
                        if (arib.IsMine(null, fileName))
                        {
                            arib.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = arib;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (ext == ".dost")
                    {
                        try
                        {
                            var dost = new Dost();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (dost.IsMine(list, fileName))
                            {
                                if (ContinueNewOrExit())
                                    ImportAndOcrDost(fileName, dost, list);
                                return;
                            }
                        }
                        catch
                        {
                            format = null;
                        }
                    }

                    if (format == null)
                    {
                        try
                        {
                            var timedtextImage = new TimedTextImage();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (timedtextImage.IsMine(list, fileName))
                            {
                                if (ContinueNewOrExit())
                                    ImportAndOcrDost(fileName, timedtextImage, list);
                                return;
                            }
                        }
                        catch
                        {
                            format = null;
                        }
                    }

                    if (format == null)
                    {
                        try
                        {
                            var seImageHtmlIndex = new SeImageHtmlIndex();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (seImageHtmlIndex.IsMine(list, fileName))
                            {
                                if (ContinueNewOrExit())
                                    ImportAndOcrDost(fileName, seImageHtmlIndex, list);
                                return;
                            }
                        }
                        catch
                        {
                            format = null;
                        }
                    }

                    if (format == null)
                    {
                        try
                        {
                            var cmaf = new Cmaft();
                            if (cmaf.IsMine(null, fileName))
                            {
                                cmaf.LoadSubtitle(_subtitle, null, fileName);
                                SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                                SetEncoding(Configuration.Settings.General.DefaultEncoding);
                                encoding = GetCurrentEncoding();
                                justConverted = true;
                                format = GetCurrentSubtitleFormat();
                            }
                        }
                        catch
                        {
                            // ignore
                        }
                    }

                    if (format == null || format.Name == Scenarist.NameOfFormat)
                    {
                        try
                        {
                            var son = new Son();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (son.IsMine(list, fileName))
                            {
                                if (ContinueNewOrExit())
                                    ImportAndOcrSon(fileName, son, list);
                                return;
                            }
                        }
                        catch
                        {
                            format = null;
                        }
                    }

                    if (format == null || format.Name == SubRip.NameOfFormat)
                    {
                        if (_subtitle.Paragraphs.Count > 1)
                        {
                            int imageCount = 0;
                            foreach (var p in _subtitle.Paragraphs)
                            {
                                string s = p.Text.ToLowerInvariant();
                                if (s.EndsWith(".bmp", StringComparison.Ordinal) || s.EndsWith(".png", StringComparison.Ordinal) || s.EndsWith(".jpg", StringComparison.Ordinal) || s.EndsWith(".tif", StringComparison.Ordinal))
                                {
                                    imageCount++;
                                }
                            }
                            if (imageCount > 2 && imageCount >= _subtitle.Paragraphs.Count - 2)
                            {
                                if (ContinueNewOrExit())
                                    ImportAndOcrSrt(_subtitle);
                                return;
                            }
                        }
                    }

                    if (format == null)
                    {
                        try
                        {
                            var satBoxPng = new SatBoxPng();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (satBoxPng.IsMine(list, fileName))
                            {
                                var subtitle = new Subtitle();
                                satBoxPng.LoadSubtitle(subtitle, list, fileName);
                                if (ContinueNewOrExit())
                                    ImportAndOcrSrt(subtitle);
                                return;
                            }
                        }
                        catch
                        {
                            format = null;
                        }
                    }

                    if (format == null || format.Name == Scenarist.NameOfFormat)
                    {
                        try
                        {
                            var sst = new SonicScenaristBitmaps();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (sst.IsMine(list, fileName))
                            {
                                if (ContinueNewOrExit())
                                    ImportAndOcrSst(fileName, sst, list);
                                return;
                            }
                        }
                        catch
                        {
                            format = null;
                        }
                    }

                    if (format == null)
                    {
                        try
                        {
                            var htmlSamiArray = new HtmlSamiArray();
                            var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                            if (htmlSamiArray.IsMine(list, fileName))
                            {
                                htmlSamiArray.LoadSubtitle(_subtitle, list, fileName);
                                _oldSubtitleFormat = htmlSamiArray;
                                SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                                SetEncoding(Configuration.Settings.General.DefaultEncoding);
                                encoding = GetCurrentEncoding();
                                justConverted = true;
                                format = GetCurrentSubtitleFormat();
                            }
                        }
                        catch
                        {
                            format = null;
                        }
                    }

                    if (format == null)
                    {
                        var f = new WinCaps32();
                        if (f.IsMine(null, fileName))
                        {
                            f.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = f;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    if (format == null)
                    {
                        var f = new IsmtDfxp();
                        if (f.IsMine(null, fileName))
                        {
                            f.LoadSubtitle(_subtitle, null, fileName);
                            _oldSubtitleFormat = f;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                        }
                    }

                    // retry vobsub (file with wrong extension)
                    if (format == null && file.Length > 500 && IsVobSubFile(fileName, false))
                    {
                        ImportAndOcrVobSubSubtitleNew(fileName, _loading);
                        return;
                    }

                    // retry Blu-ray (file with wrong extension)
                    if (format == null && file.Length > 500 && FileUtil.IsBluRaySup(fileName))
                    {
                        ImportAndOcrBluRaySup(fileName, _loading);
                        return;
                    }

                    // retry SP DVD (file with wrong extension)
                    if (format == null && file.Length > 500 && FileUtil.IsSpDvdSup(fileName))
                    {
                        ImportAndOcrSpDvdSup(fileName, _loading);
                        return;
                    }

                    // retry Matroska (file with wrong extension)
                    if (format == null && !string.IsNullOrWhiteSpace(fileName))
                    {
                        using (var matroska = new MatroskaFile(fileName))
                        {
                            if (matroska.IsValid)
                            {
                                var subtitleList = matroska.GetTracks(true);
                                if (subtitleList.Count > 0)
                                {
                                    ImportSubtitleFromMatroskaFile(fileName);
                                    return;
                                }
                            }
                        }
                    }

                    // check for idx file
                    if (format == null && file.Length > 100 && ext == ".idx")
                    {
                        MessageBox.Show(_language.ErrorLoadIdx);
                        return;
                    }

                    // check for .rar file
                    if (format == null && file.Length > 100 && FileUtil.IsRar(fileName))
                    {
                        MessageBox.Show(_language.ErrorLoadRar);
                        return;
                    }

                    // check for .zip file
                    if (format == null && file.Length > 100 && FileUtil.IsZip(fileName))
                    {
                        MessageBox.Show(_language.ErrorLoadZip);
                        return;
                    }

                    // check for .7z file
                    if (format == null && file.Length > 100 && FileUtil.Is7Zip(fileName))
                    {
                        MessageBox.Show(_language.ErrorLoad7Zip);
                        return;
                    }

                    // check for .png file
                    if (format == null && file.Length > 100 && FileUtil.IsPng(fileName))
                    {
                        MessageBox.Show(_language.ErrorLoadPng);
                        return;
                    }

                    // check for .jpg file
                    if (format == null && file.Length > 100 && FileUtil.IsJpg(fileName))
                    {
                        MessageBox.Show(_language.ErrorLoadJpg);
                        return;
                    }

                    // check for .srr file
                    if (format == null && file.Length > 100 && ext == ".srr" && FileUtil.IsSrr(fileName))
                    {
                        MessageBox.Show(_language.ErrorLoadSrr);
                        return;
                    }

                    // check for Torrent file
                    if (format == null && file.Length > 50 && FileUtil.IsTorrentFile(fileName))
                    {
                        MessageBox.Show(_language.ErrorLoadTorrent);
                        return;
                    }

                    // check for all binary zeroes (I've heard about this a few times... perhaps related to crashes?)
                    if (format == null && file.Length > 50 && FileUtil.IsSubtitleFileAllBinaryZeroes(fileName))
                    {
                        MessageBox.Show(_language.ErrorLoadBinaryZeroes);
                        return;
                    }

                    if (format == null && file.Length < 100 * 1000000 && TransportStreamParser.IsDvbSup(fileName))
                    {
                        ImportSubtitleFromDvbSupFile(fileName);
                        return;
                    }

                    if (format == null && file.Length < 1000000)
                    {
                        // check for valid timed text
                        if (ext == ".xml" || ext == ".dfxp")
                        {
                            var sb = new StringBuilder();
                            foreach (var line in File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)))
                                sb.AppendLine(line);
                            var xmlAsString = sb.ToString().Trim();

                            if (xmlAsString.Contains("http://www.w3.org/ns/ttml") && xmlAsString.Contains("<?xml version=") ||
                                xmlAsString.Contains("http://www.w3.org/") && xmlAsString.Contains("/ttaf1"))
                            {
                                var xml = new System.Xml.XmlDocument();
                                try
                                {
                                    xml.LoadXml(xmlAsString);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Timed text is not valid (xml is not well-formed): " + ex.Message);
                                    return;
                                }
                            }
                        }

                        // Try to use a generic subtitle format parser (guessing subtitle format)
                        try
                        {
                            var enc = LanguageAutoDetect.GetEncodingFromFile(fileName);
                            var s = File.ReadAllText(fileName, enc);

                            // check for RTF file
                            if (ext == ".rtf" && s.TrimStart().StartsWith("{\\rtf", StringComparison.Ordinal))
                            {
                                using (var rtb = new RichTextBox { Rtf = s })
                                {
                                    s = rtb.Text;
                                }
                            }
                            var uknownFormatImporter = new UknownFormatImporter { UseFrames = true };
                            var genericParseSubtitle = uknownFormatImporter.AutoGuessImport(s.SplitToLines());
                            if (genericParseSubtitle.Paragraphs.Count > 1)
                            {
                                _subtitle = genericParseSubtitle;
                                SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                                SetEncoding(Configuration.Settings.General.DefaultEncoding);
                                encoding = GetCurrentEncoding();
                                justConverted = true;
                                format = GetCurrentSubtitleFormat();
                                ShowStatus("Guessed subtitle format via generic subtitle parser!");
                            }
                        }
                        catch
                        {
                        }
                    }

                    if (format == null && (FileUtil.IsPlainText(fileName) || new Tx3GTextOnly().IsMine(null, fileName)))
                    {
                        ImportPlainText(fileName);
                        return;
                    }

                    if (format == null)
                    {
                        var fd = new FinalDraftTemplate2();
                        var list = new List<string>(File.ReadAllLines(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName)));
                        if (fd.IsMine(list, fileName))
                        {
                            ImportPlainText(fileName);
                            return;
                        }
                    }

                    _fileDateTime = File.GetLastWriteTime(fileName);

                    if (format != null && format.IsFrameBased)
                        _subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                    else
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                    if (format != null)
                    {
                        if (Configuration.Settings.General.RemoveBlankLinesWhenOpening)
                        {
                            _subtitle.RemoveEmptyLines();
                        }

                        if (Configuration.Settings.General.RemoveBadCharsWhenOpening)
                        {
                            foreach (var p in _subtitle.Paragraphs)
                            {
                                // Replace U+0456 (CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I) by U+0069 (LATIN SMALL LETTER I)
                                p.Text = p.Text.Replace("<і>", "<i>").Replace("</і>", "</i>");

                                // remove control characters (e.g. binary zero)
                                p.Text = p.Text.RemoveControlCharactersButWhiteSpace();
                            }
                        }

                        _subtitleListViewIndex = -1;
                        Configuration.Settings.General.CurrentVideoOffsetInMs = 0;

                        var oldSaveFormat = Configuration.Settings.General.LastSaveAsFormat;
                        SetCurrentFormat(format);
                        Configuration.Settings.General.LastSaveAsFormat = oldSaveFormat;

                        _subtitleAlternateFileName = null;
                        if (LoadAlternateSubtitleFile(originalFileName))
                            _subtitleAlternateFileName = originalFileName;

                        // Seungki begin
                        _splitDualSami = false;
                        if (Configuration.Settings.SubtitleSettings.SamiDisplayTwoClassesAsTwoSubtitles && format.GetType() == typeof(Sami) && Sami.GetStylesFromHeader(_subtitle.Header).Count == 2)
                        {
                            var classes = Sami.GetStylesFromHeader(_subtitle.Header);
                            var s1 = new Subtitle(_subtitle);
                            var s2 = new Subtitle(_subtitle);
                            s1.Paragraphs.Clear();
                            s2.Paragraphs.Clear();
                            foreach (var p in _subtitle.Paragraphs)
                            {
                                if (p.Extra != null && p.Extra.Equals(classes[0], StringComparison.OrdinalIgnoreCase))
                                    s1.Paragraphs.Add(p);
                                else
                                    s2.Paragraphs.Add(p);
                            }
                            if (s1.Paragraphs.Count == 0 || s2.Paragraphs.Count == 0)
                                return;

                            _subtitle = s1;
                            _subtitleAlternate = s2;
                            _subtitleAlternateFileName = _fileName;
                            SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Extra);
                            SubtitleListview1.ShowAlternateTextColumn(classes[1]);
                            _splitDualSami = true;
                        }
                        // Seungki end

                        textBoxSource.Text = _subtitle.ToText(format);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        if (SubtitleListview1.Items.Count > 0)
                        {
                            SubtitleListview1.Items[0].Selected = true;
                            SubtitleListview1.Items[0].Focused = true;
                        }
                        _findHelper = null;
                        _spellCheckForm = null;

                        if (_resetVideo && ModifierKeys != Keys.Shift)
                        {
                            _videoFileName = null;
                            _videoInfo = null;
                            _videoAudioTrackNumber = -1;
                            labelVideoInfo.Text = _languageGeneral.NoVideoLoaded;
                            audioVisualizer.WavePeaks = null;
                            audioVisualizer.Spectrogram = null;
                            audioVisualizer.SceneChanges = new List<double>();
                        }

                        if (Configuration.Settings.General.ShowVideoPlayer || Configuration.Settings.General.ShowAudioVisualizer)
                        {
                            if (!Configuration.Settings.General.DisableVideoAutoLoading)
                            {
                                if (!string.IsNullOrEmpty(videoFileName) && File.Exists(videoFileName))
                                {
                                    OpenVideo(videoFileName);
                                }
                                else if (!string.IsNullOrEmpty(fileName) && (toolStripButtonToggleVideo.Checked || toolStripButtonToggleWaveform.Checked))
                                {
                                    TryToFindAndOpenVideoFile(Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName)));
                                }
                                if (_videoFileName == null)
                                {
                                    CloseVideoToolStripMenuItemClick(this, null);
                                }
                            }
                        }
                        videoFileLoaded = _videoFileName != null;

                        if (Configuration.Settings.RecentFiles.Files.Count > 0 &&
                            Configuration.Settings.RecentFiles.Files[0].FileName == fileName)
                        {
                        }
                        else
                        {
                            Configuration.Settings.RecentFiles.Add(fileName, _videoFileName, _subtitleAlternateFileName);
                            Configuration.Settings.Save();
                            UpdateRecentFilesUI();
                        }
                        _fileName = fileName;
                        SetTitle();
                        ShowStatus(string.Format(_language.LoadedSubtitleX, _fileName));
                        _sourceViewChange = false;
                        _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                        _converted = false;
                        ResetHistory();

                        SetUndockedWindowsTitle();

                        if (justConverted)
                        {
                            _converted = true;
                            ShowStatus(string.Format(_language.LoadedSubtitleX, _fileName) + " - " + string.Format(_language.ConvertedToX, format.FriendlyName));
                        }
                        if (Configuration.Settings.General.AutoConvertToUtf8)
                            encoding = Encoding.UTF8;
                        SetEncoding(encoding);

                        var formatType = format.GetType();
                        if (formatType == typeof(SubStationAlpha))
                        {
                            string errors = AdvancedSubStationAlpha.CheckForErrors(_subtitle.Header);
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            errors = (format as SubStationAlpha).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(AdvancedSubStationAlpha))
                        {
                            string errors = AdvancedSubStationAlpha.CheckForErrors(_subtitle.Header);
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            errors = (format as AdvancedSubStationAlpha).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(SubRip))
                        {
                            string errors = (format as SubRip).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(MicroDvd))
                        {
                            string errors = (format as MicroDvd).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(DCinemaSmpte2007))
                        {
                            format.ToText(_subtitle, string.Empty);
                            string errors = (format as DCinemaSmpte2007).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(DCinemaSmpte2010))
                        {
                            format.ToText(_subtitle, string.Empty);
                            string errors = (format as DCinemaSmpte2010).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(CsvNuendo))
                        {
                            if (_subtitle.Paragraphs.Any(p => !string.IsNullOrEmpty(p.Actor)))
                            {
                                bool wasVisible = SubtitleListview1.ColumnIndexActor >= 0;
                                SubtitleListview1.ShowActorColumn(Configuration.Settings.Language.General.Character);
                                if (!wasVisible)
                                {
                                    SaveSubtitleListviewIndices();
                                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                                    RestoreSubtitleListviewIndices();
                                }
                            }
                        }
                    }
                    else
                    {
                        if (file.Length < 50)
                        {
                            _findHelper = null;
                            _spellCheckForm = null;
                            _videoFileName = null;
                            _videoInfo = null;
                            _videoAudioTrackNumber = -1;
                            labelVideoInfo.Text = _languageGeneral.NoVideoLoaded;
                            audioVisualizer.WavePeaks = null;
                            audioVisualizer.Spectrogram = null;
                            audioVisualizer.SceneChanges = new List<double>();

                            Configuration.Settings.RecentFiles.Add(fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                            Configuration.Settings.Save();
                            UpdateRecentFilesUI();
                            _fileName = fileName;
                            SetTitle();
                            ShowStatus(string.Format(_language.LoadedEmptyOrShort, _fileName));
                            _sourceViewChange = false;
                            _converted = false;

                            MessageBox.Show(_language.FileIsEmptyOrShort);
                        }
                        else
                        {
                            ShowUnknownSubtitle();
                            return;
                        }
                    }

                    if (!videoFileLoaded && mediaPlayer.VideoPlayer != null)
                    {
                        mediaPlayer.PauseAndDisposePlayer();
                        timer1.Stop();
                    }
                    ResetShowEarlierOrLater();
                    FixRightToLeftDependingOnLanguage();
                }
                else
                {
                    MessageBox.Show(string.Format(_language.FileNotFound, fileName));
                }
            }

            private void ShowHideTextBasedFeatures(SubtitleFormat format)
            {
                textBoxSource.Enabled = format?.IsTextBased == true;
            }

            private void SetUndockedWindowsTitle()
            {
                string title = _languageGeneral.NoVideoLoaded;
                if (!string.IsNullOrEmpty(_videoFileName))
                    title = Path.GetFileNameWithoutExtension(_videoFileName);

                if (_videoControlsUndocked != null && !_videoControlsUndocked.IsDisposed)
                    _videoControlsUndocked.Text = string.Format(_languageGeneral.ControlsWindowTitle, title);

                if (_videoPlayerUndocked != null && !_videoPlayerUndocked.IsDisposed)
                    _videoPlayerUndocked.Text = string.Format(_languageGeneral.VideoWindowTitle, title);

                if (_waveformUndocked != null && !_waveformUndocked.IsDisposed)
                    _waveformUndocked.Text = string.Format(_languageGeneral.AudioWindowTitle, title);
            }

            private void ImportAndOcrBdnXml(string fileName, BdnXml bdnXml, List<string> list)
            {
                using (var formSubOcr = new VobSubOcr())
                {
                    var bdnSubtitle = new Subtitle();
                    bdnXml.LoadSubtitle(bdnSubtitle, list, fileName);
                    bdnSubtitle.FileName = fileName;
                    formSubOcr.Initialize(bdnSubtitle, Configuration.Settings.VobSubOcr, false);
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingBdnXml);
                        FileNew();
                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.ChangeExtension(formSubOcr.FileName, new SubRip().Extension);
                        SetTitle();
                        _converted = true;
                    }
                }
            }

            private void ImportAndOcrSon(string fileName, Son format, List<string> list)
            {
                using (var formSubOcr = new VobSubOcr())
                {
                    var sub = new Subtitle();
                    format.LoadSubtitle(sub, list, fileName);
                    sub.FileName = fileName;
                    formSubOcr.Initialize(sub, Configuration.Settings.VobSubOcr, true);
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingBdnXml);
                        FileNew();
                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.ChangeExtension(formSubOcr.FileName, new SubRip().Extension);
                        SetTitle();
                        _converted = true;
                    }
                }
            }

            private void ImportAndOcrDost(string fileName, SubtitleFormat format, List<string> list)
            {
                using (var formSubOcr = new VobSubOcr())
                {
                    var sub = new Subtitle();
                    format.LoadSubtitle(sub, list, fileName);
                    sub.FileName = fileName;
                    formSubOcr.Initialize(sub, Configuration.Settings.VobSubOcr, false);
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingBdnXml);
                        FileNew();
                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.ChangeExtension(formSubOcr.FileName, new SubRip().Extension);
                        SetTitle();
                        _converted = true;
                    }
                }
            }

            private void ImportAndOcrSst(string fileName, SonicScenaristBitmaps format, List<string> list)
            {
                using (var formSubOcr = new VobSubOcr())
                {
                    var sub = new Subtitle();
                    format.LoadSubtitle(sub, list, fileName);
                    sub.FileName = fileName;
                    formSubOcr.Initialize(sub, Configuration.Settings.VobSubOcr, true);
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingBdnXml);
                        FileNew();
                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.ChangeExtension(formSubOcr.FileName, new SubRip().Extension);
                        SetTitle();
                        _converted = true;
                    }
                }
            }

            private void ImportAndOcrSrt(Subtitle subtitle)
            {
                using (var formSubOcr = new VobSubOcr())
                {
                    formSubOcr.Initialize(subtitle, Configuration.Settings.VobSubOcr, false);
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingBdnXml);
                        FileNew();
                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.ChangeExtension(formSubOcr.FileName, new SubRip().Extension);
                        SetTitle();
                        _converted = true;
                    }
                }
            }

            private void ShowUnknownSubtitle()
            {
                using (var unknownSubtitle = new UnknownSubtitle())
                {
                    unknownSubtitle.Initialize(Title);
                    unknownSubtitle.ShowDialog(this);
                }
            }

            private void UpdateRecentFilesUI()
            {
                reopenToolStripMenuItem.DropDownItems.Clear();
                if (Configuration.Settings.General.ShowRecentFiles && Configuration.Settings.RecentFiles.Files.Count > 0)
                {
                    reopenToolStripMenuItem.Visible = true;
                    foreach (var file in Configuration.Settings.RecentFiles.Files)
                    {
                        if (File.Exists(file.FileName))
                        {
                            reopenToolStripMenuItem.DropDownItems.Add(file.FileName, null, ReopenSubtitleToolStripMenuItemClick);
                            UiUtil.FixFonts(reopenToolStripMenuItem.DropDownItems[reopenToolStripMenuItem.DropDownItems.Count - 1]);
                        }
                    }
                }
                else
                {
                    Configuration.Settings.RecentFiles.Files.Clear();
                    reopenToolStripMenuItem.Visible = false;
                }
            }

            private void ReopenSubtitleToolStripMenuItemClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                var item = sender as ToolStripItem;

                if (ContinueNewOrExit())
                {
                    RecentFileEntry rfe = null;
                    foreach (var file in Configuration.Settings.RecentFiles.Files)
                    {
                        if (file.FileName == item.Text)
                            rfe = file;
                    }
                    SubtitleListview1.BeginUpdate();
                    if (rfe == null)
                    {
                        OpenSubtitle(item.Text, null);
                    }
                    else
                    {
                        OpenSubtitle(rfe.FileName, null, rfe.VideoFileName, rfe.OriginalFileName);
                        Configuration.Settings.General.CurrentVideoOffsetInMs = rfe.VideoOffsetInMs;
                        if (rfe.VideoOffsetInMs > 0)
                        {
                            _subtitle.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(-Configuration.Settings.General.CurrentVideoOffsetInMs));
                            _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                            SubtitleListview1.Fill(_subtitle);
                        }
                    }
                    GotoSubPosAndPause();
                    SetRecentIndices(item.Text);
                    SubtitleListview1.EndUpdate();
                    if (rfe != null && !string.IsNullOrEmpty(rfe.VideoFileName))
                    {
                        var p = _subtitle.GetParagraphOrDefault(rfe.FirstSelectedIndex);
                        if (p != null)
                        {
                            mediaPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                        }
                    }
                }
            }

            private void GotoSubPosAndPause()
            {
                if (!string.IsNullOrEmpty(_videoFileName))
                {
                    _videoLoadedGoToSubPosAndPause = true;
                }
                else
                {
                    mediaPlayer.SubtitleText = string.Empty;
                }
            }

            private void SetRecentIndices(string fileName)
            {
                if (!Configuration.Settings.General.RememberSelectedLine)
                {
                    return;
                }

                ShowSubtitleTimer.Stop();
                Application.DoEvents();
                foreach (var x in Configuration.Settings.RecentFiles.Files)
                {
                    if (fileName.Equals(x.FileName, StringComparison.OrdinalIgnoreCase))
                    {
                        int sIndex = x.FirstSelectedIndex;
                        if (sIndex >= 0 && sIndex < SubtitleListview1.Items.Count)
                        {
                            SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                            SubtitleListview1.SelectIndexAndEnsureVisible(sIndex, true);
                            _subtitleListViewIndex = -1;
                            SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                        }

                        int topIndex = x.FirstVisibleIndex;
                        if (topIndex >= 0 && topIndex < SubtitleListview1.Items.Count)
                        {
                            // to fix bug in .net framework we have to set topitem 3 times... wtf!?
                            SubtitleListview1.TopItem = SubtitleListview1.Items[topIndex];
                            SubtitleListview1.TopItem = SubtitleListview1.Items[topIndex];
                            SubtitleListview1.TopItem = SubtitleListview1.Items[topIndex];
                        }
                        RefreshSelectedParagraph();
                        break;
                    }
                }
                if (!_loading)
                    ShowSubtitleTimer.Start();
            }

            private void SaveToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    return;
                }

                ReloadFromSourceView();
                _saveAsCalled = false;
                SaveSubtitle(GetCurrentSubtitleFormat());
            }

            private void SaveAsToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    return;
                }

                ReloadFromSourceView();
                FileSaveAs(true);
            }

            private DialogResult FileSaveAs(bool allowUsingLastSaveAsFormat)
            {
                SubtitleFormat currentFormat = null;
                if (allowUsingLastSaveAsFormat && !string.IsNullOrEmpty(Configuration.Settings.General.LastSaveAsFormat))
                    currentFormat = Utilities.GetSubtitleFormatByFriendlyName(Configuration.Settings.General.LastSaveAsFormat);
                if (currentFormat == null)
                    currentFormat = GetCurrentSubtitleFormat();

                UiUtil.SetSaveDialogFilter(saveFileDialog1, currentFormat);

                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + currentFormat.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                if (!string.IsNullOrWhiteSpace(_fileName) && File.Exists(_fileName) && !string.IsNullOrEmpty(_videoFileName))
                {
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                    saveFileDialog1.InitialDirectory = Path.GetDirectoryName(_videoFileName);
                }
                else if (!string.IsNullOrWhiteSpace(_fileName))
                {
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);
                    saveFileDialog1.InitialDirectory = Path.GetDirectoryName(_fileName);
                }
                else if (!string.IsNullOrEmpty(_videoFileName))
                {
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                    saveFileDialog1.InitialDirectory = Path.GetDirectoryName(_videoFileName);
                }
                else
                {
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);
                }

                var result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    _converted = false;
                    _fileName = saveFileDialog1.FileName;
                    _fileDateTime = File.GetLastWriteTime(_fileName);
                    SetTitle();
                    MakeHistoryForUndo(_language.Menu.File.SaveAs);
                    Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                    Configuration.Settings.Save();

                    int index = 0;
                    foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
                    {
                        if (saveFileDialog1.FilterIndex == index + 1)
                        {
                            // only allow current extension or ".txt"
                            string ext = Path.GetExtension(_fileName).ToLowerInvariant();
                            bool extOk = ext.Equals(format.Extension, StringComparison.OrdinalIgnoreCase) || format.AlternateExtensions.Contains(ext) || ext == ".txt";
                            if (!extOk)
                            {
                                if (_fileName.EndsWith('.'))
                                    _fileName = _fileName.Substring(0, _fileName.Length - 1);
                                _fileName += format.Extension;
                            }
                            _saveAsCalled = true;
                            if (SaveSubtitle(format) == DialogResult.OK)
                            {
                                Configuration.Settings.General.LastSaveAsFormat = format.Name;
                                SetCurrentFormat(format);
                            }
                            break;
                        }
                        index++;
                    }
                    _converted = false;
                }
                return result;
            }

            private DialogResult SaveSubtitle(SubtitleFormat format)
            {
                if (string.IsNullOrEmpty(_fileName) || _converted)
                    return FileSaveAs(false);

                try
                {
                    var sub = GetSaveSubtitle(_subtitle);

                    if (format != null && !format.IsTextBased)
                    {
                        var ebu = format as Ebu;
                        if (ebu != null)
                        {
                            var header = new Ebu.EbuGeneralSubtitleInformation();
                            if (_subtitle != null && _subtitle.Header != null && (_subtitle.Header.Contains("STL2") || _subtitle.Header.Contains("STL3")))
                            {
                                header = Ebu.ReadHeader(Encoding.UTF8.GetBytes(_subtitle.Header));
                            }
                            if (ebu.Save(_fileName, sub, !_saveAsCalled, header))
                            {
                                _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                                Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                                Configuration.Settings.Save();
                            }
                        }
                        return DialogResult.OK;
                    }

                    string allText = sub.ToText(format);

                    // Seungki begin
                    if (_splitDualSami && _subtitleAlternate?.Paragraphs.Count > 0)
                    {
                        var s = new Subtitle(_subtitle);
                        foreach (var p in _subtitleAlternate.Paragraphs)
                            s.Paragraphs.Add(p);
                        allText = s.ToText(format);
                    }
                    // Seungki end

                    var currentEncoding = GetCurrentEncoding();
                    bool isUnicode = currentEncoding == Encoding.Unicode || currentEncoding == Encoding.UTF32 || currentEncoding == Encoding.GetEncoding(12001) || currentEncoding == Encoding.UTF7 || currentEncoding == Encoding.UTF8;
                    if (!isUnicode && (allText.Contains(new[] { '♪', '♫', '♥', '—', '―', '…' }))) // ANSI & music/unicode symbols
                    {
                        if (MessageBox.Show(string.Format(_language.UnicodeMusicSymbolsAnsiWarning), Title, MessageBoxButtons.YesNo) == DialogResult.No)
                            return DialogResult.No;
                    }

                    if (!isUnicode)
                    {
                        allText = NormalizeUnicode(allText);
                    }

                    bool containsNegativeTime = false;
                    foreach (var p in sub.Paragraphs)
                    {
                        if (p.StartTime.TotalMilliseconds < 0 || p.EndTime.TotalMilliseconds < 0)
                        {
                            containsNegativeTime = true;
                            break;
                        }
                    }
                    if (containsNegativeTime)
                    {
                        if (MessageBox.Show(_language.NegativeTimeWarning, Title, MessageBoxButtons.YesNo) == DialogResult.No)
                            return DialogResult.No;
                    }

                    if (File.Exists(_fileName))
                    {
                        var fileInfo = new FileInfo(_fileName);
                        var fileOnDisk = fileInfo.LastWriteTime;
                        if (_fileDateTime != fileOnDisk && _fileDateTime != new DateTime())
                        {
                            if (MessageBox.Show(string.Format(_language.OverwriteModifiedFile,
                                _fileName, fileOnDisk.ToShortDateString(), fileOnDisk.ToString("HH:mm:ss"),
                                Environment.NewLine, _fileDateTime.ToShortDateString(), _fileDateTime.ToString("HH:mm:ss")),
                                Title + " - " + _language.FileOnDiskModified, MessageBoxButtons.YesNo) == DialogResult.No)
                                return DialogResult.No;
                        }
                        if (fileInfo.IsReadOnly)
                        {
                            MessageBox.Show(string.Format(_language.FileXIsReadOnly, _fileName));
                            return DialogResult.No;
                        }
                    }

                    if ((format.GetType() == typeof(WebVTT) || format.GetType() == typeof(WebVTTFileWithLineNumber)))
                    {
                        SetEncoding(Encoding.UTF8);
                        currentEncoding = Encoding.UTF8;
                    }
                    if (format.Extension == ".rtf")
                    {
                        currentEncoding = Encoding.ASCII;
                    }

                    if (ModifierKeys == (Keys.Control | Keys.Shift))
                        allText = allText.Replace("\r\n", "\n");

                    if (format.GetType() == typeof(ItunesTimedText) || format.GetType() == typeof(ScenaristClosedCaptions) || format.GetType() == typeof(ScenaristClosedCaptionsDropFrame))
                    {
                        var outputEnc = new UTF8Encoding(false); // create encoding with no BOM
                        using (var file = new StreamWriter(_fileName, false, outputEnc)) // open file with encoding
                        {
                            file.Write(allText);
                        }
                    }
                    else if (Equals(currentEncoding, Encoding.UTF8) && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml)))
                    {
                        var outputEnc = new UTF8Encoding(false); // create encoding with no BOM
                        using (var file = new StreamWriter(_fileName, false, outputEnc)) // open file with encoding
                        {
                            file.Write(allText);
                        }
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(allText))
                        {
                            MessageBox.Show(string.Format(_language.UnableToSaveSubtitleX, _fileName), String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            return DialogResult.Cancel;
                        }
                        if (Equals(currentEncoding, Encoding.UTF8) && !Configuration.Settings.General.WriteUtf8Bom)
                        {
                            var outputEnc = new UTF8Encoding(false); // create encoding with no BOM
                            using (var file = new StreamWriter(_fileName, false, outputEnc)) // open file with encoding
                            {
                                file.Write(allText);
                            }
                        }
                        else
                        {
                            // create file - includes BOM for Unicode formats
                            using (var fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write, FileShare.Read))
                            using (var sw = new StreamWriter(fs, currentEncoding))
                            {
                                sw.Write(allText);
                            }
                        }
                    }
                    Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                    Configuration.Settings.Save();
                    _fileDateTime = File.GetLastWriteTime(_fileName);
                    ShowStatus(string.Format(_language.SavedSubtitleX, _fileName));
                    if (format.GetType() == typeof(NetflixTimedText))
                    {
                        NetflixGlyphCheck(true);
                    }
                    _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                    return DialogResult.OK;
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                    return DialogResult.Cancel;
                }
            }

            private DialogResult SaveOriginalSubtitle(SubtitleFormat format)
            {
                try
                {
                    var subAlt = GetSaveSubtitle(_subtitleAlternate);

                    bool containsNegativeTime = false;
                    foreach (var p in subAlt.Paragraphs)
                    {
                        if (p.StartTime.TotalMilliseconds < 0 || p.EndTime.TotalMilliseconds < 0)
                        {
                            containsNegativeTime = true;
                            break;
                        }
                    }
                    if (containsNegativeTime)
                    {
                        if (MessageBox.Show(_language.NegativeTimeWarning, Title, MessageBoxButtons.YesNo) == DialogResult.No)
                            return DialogResult.No;
                    }

                    if (format != null && !format.IsTextBased)
                    {
                        var ebu = format as Ebu;
                        if (ebu != null)
                        {
                            if (ebu.Save(_subtitleAlternateFileName, subAlt))
                            {
                                Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                                Configuration.Settings.Save();
                                ShowStatus(string.Format(_language.SavedOriginalSubtitleX, _subtitleAlternateFileName));
                                _changeAlternateSubtitleToString = _subtitleAlternate.ToText(new SubRip()).Trim();
                                return DialogResult.OK;
                            }
                            return DialogResult.No;
                        }
                        MessageBox.Show("Ups - save original does not support this format - please go to Github and create an issue!");
                    }

                    string allText = subAlt.ToText(format).Trim();
                    var currentEncoding = GetCurrentEncoding();
                    bool isUnicode = currentEncoding != null && (currentEncoding == Encoding.Unicode || currentEncoding == Encoding.UTF32 || currentEncoding == Encoding.UTF7 || currentEncoding == Encoding.UTF8);
                    if (!isUnicode && (allText.Contains(new[] { '♪', '♫', '♥', '—', '―', '…' }))) // ANSI & music/unicode symbols
                    {
                        if (MessageBox.Show(string.Format(_language.UnicodeMusicSymbolsAnsiWarning), Title, MessageBoxButtons.YesNo) == DialogResult.No)
                            return DialogResult.No;
                    }

                    if (!isUnicode)
                    {
                        allText = NormalizeUnicode(allText);
                    }

                    File.WriteAllText(_subtitleAlternateFileName, allText, currentEncoding);
                    ShowStatus(string.Format(_language.SavedOriginalSubtitleX, _subtitleAlternateFileName));
                    _changeAlternateSubtitleToString = _subtitleAlternate.ToText(new SubRip()).Trim();
                    return DialogResult.OK;
                }
                catch
                {
                    MessageBox.Show(string.Format(_language.UnableToSaveSubtitleX, _fileName));
                    return DialogResult.Cancel;
                }
            }

            public string NormalizeUnicode(string text)
            {
                const char defHyphen = '-'; // - Hyphen-minus (\u002D) (Basic Latin)
                const char defColon = ':'; // : Colon (\u003A) (Basic Latin)

                // Hyphens
                text = text.Replace('\u2043', defHyphen); // ⁃ Hyphen bullet (\u2043)
                text = text.Replace('\u2010', defHyphen); // ‐ Hyphen (\u2010)
                text = text.Replace('\u2012', defHyphen); // ‒ Figure dash (\u2012)
                text = text.Replace('\u2013', defHyphen); // – En dash (\u2013)
                text = text.Replace('\u2014', defHyphen); // — Em dash (\u2014)
                text = text.Replace('\u2015', defHyphen); // ― Horizontal bar (\u2015)

                // Colons:
                text = text.Replace('\u02F8', defColon); // ˸ Modifier Letter Raised Colon (\u02F8)
                text = text.Replace('\uFF1A', defColon); // ： Fullwidth Colon (\uFF1A)
                text = text.Replace('\uFE13', defColon); // ︓ Presentation Form for Vertical Colon (\uFE13)

                // Others
                text = text.Replace("…", "...");
                text = text.Replace('♪', '#');
                text = text.Replace('♫', '#');
                text = text.Replace("⇒", "=>");

                // Spaces
                text = text.Replace('\u00A0', ' '); // No-Break Space
                text = text.Replace("\u200B", string.Empty); // Zero Width Space
                text = text.Replace("\uFEFF", string.Empty); // Zero Width No-Break Space

                // Intellectual property
                text = text.Replace("\u00A9", "(Copyright)"); // © copyright
                text = text.Replace("\u2117", "(Sound-recording Copyright)"); // ℗ sound-recording copyright
                text = text.Replace("\u00AE", "(Registered Trademark)"); // ® registered trademark
                text = text.Replace("\u2120", "(Service Mark)"); // ℠ service mark
                text = text.Replace("\u2122", "(Trademark)"); // ™ trademark

                return text;
            }

            private void NewToolStripMenuItemClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                FileNew();
            }

            private void ResetSubtitle(bool forceVideoReload = false)
            {
                SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);

                labelStartTimeWarning.Text = string.Empty;
                labelDurationWarning.Text = string.Empty;

                Configuration.Settings.General.CurrentVideoOffsetInMs = 0;
                _subtitle = new Subtitle(_subtitle.HistoryItems);
                _changeAlternateSubtitleToString = string.Empty;
                _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                _subtitleAlternateFileName = null;
                textBoxSource.Text = string.Empty;
                SubtitleListview1.Items.Clear();
                _fileName = string.Empty;
                _fileDateTime = new DateTime();
                Text = Title;
                _oldSubtitleFormat = null;
                labelSingleLine.Text = string.Empty;
                RemoveAlternate(true);
                _splitDualSami = false;

                SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Extra);

                ComboBoxSubtitleFormatsSelectedIndexChanged(null, null);

                toolStripComboBoxFrameRate.Text = Configuration.Settings.General.DefaultFrameRate.ToString();

                SetEncoding(Configuration.Settings.General.DefaultEncoding);

                toolStripComboBoxFrameRate.Text = Configuration.Settings.General.DefaultFrameRate.ToString();
                _findHelper = null;
                _spellCheckForm = null;

                if (ModifierKeys != Keys.Shift || forceVideoReload)
                {
                    _videoFileName = null;
                    _videoInfo = null;
                    _videoAudioTrackNumber = -1;
                    labelVideoInfo.Text = _languageGeneral.NoVideoLoaded;
                    audioVisualizer.WavePeaks = null;
                    audioVisualizer.Spectrogram = null;
                    audioVisualizer.SceneChanges = new List<double>();
                    if (mediaPlayer.VideoPlayer != null)
                    {
                        mediaPlayer.PauseAndDisposePlayer();
                    }
                }

                _sourceViewChange = false;

                _subtitleListViewIndex = -1;
                textBoxListViewText.Text = string.Empty;
                textBoxListViewTextAlternate.Text = string.Empty;
                textBoxListViewText.Enabled = false;
                labelTextLineLengths.Text = string.Empty;
                labelCharactersPerSecond.Text = string.Empty;
                labelTextLineTotal.Text = string.Empty;

                _listViewTextUndoLast = null;
                _listViewAlternateTextUndoLast = null;
                _listViewTextUndoIndex = -1;

                _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                _converted = false;

                SetUndockedWindowsTitle();
                mediaPlayer.SubtitleText = string.Empty;
                labelNextWord.Visible = false;
                ShowStatus(_language.New);

                ResetShowEarlierOrLater();

                // Set default RTL or LTR
                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    textBoxListViewTextAlternate.RightToLeft = Configuration.Settings.General.RightToLeftMode ? RightToLeft.Yes : RightToLeft.No;
                }
                if (Configuration.Settings.General.RightToLeftMode)
                {
                    textBoxListViewText.RightToLeft = RightToLeft.Yes;
                    textBoxSource.RightToLeft = RightToLeft.Yes;
                }
                else
                {
                    textBoxListViewText.RightToLeft = RightToLeft.No;
                    textBoxSource.RightToLeft = RightToLeft.No;
                }
            }

            private void ResetShowEarlierOrLater()
            {
                try
                {
                    if (_showEarlierOrLater != null && !_showEarlierOrLater.IsDisposed)
                    {
                        _showEarlierOrLater.ResetTotalAdjustment();
                    }
                }
                catch
                {
                    // form closing or alike
                }
            }

            private void FileNew()
            {
                if (ContinueNewOrExit())
                {
                    MakeHistoryForUndo(_language.BeforeNew);
                    ResetSubtitle(true);
                }
            }

            private void ComboBoxSubtitleFormatsSelectedIndexChanged(object sender, EventArgs e)
            {
                _converted = true;
                SubtitleFormat format = GetCurrentSubtitleFormat();
                if (_oldSubtitleFormat == null)
                {
                    if (!_loading)
                        MakeHistoryForUndo(string.Format(_language.BeforeConvertingToX, format.FriendlyName));
                }
                else
                {
                    _subtitle.MakeHistoryForUndo(string.Format(_language.BeforeConvertingToX, format.FriendlyName), _oldSubtitleFormat, _fileDateTime, _subtitleAlternate, _subtitleAlternateFileName, _subtitleListViewIndex, textBoxListViewText.SelectionStart, textBoxListViewTextAlternate.SelectionStart);
                    _oldSubtitleFormat.RemoveNativeFormatting(_subtitle, format);
                    SaveSubtitleListviewIndices();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    RestoreSubtitleListviewIndices();

                    if (_oldSubtitleFormat.HasStyleSupport)
                    {
                        SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Extra);
                    }
                    if (_networkSession == null)
                    {
                        SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Network);
                    }
                    // Recalculate time.
                    if (!_oldSubtitleFormat.IsFrameBased && format.IsFrameBased)
                    {
                        _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate); // Milliseconds to frames
                    }
                    else if (_oldSubtitleFormat.IsFrameBased && !format.IsFrameBased)
                    {
                        _subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate); // Frame to Milliseconds.
                    }
                }
                ShowSource();
                if (format != null)
                {
                    var formatType = format.GetType();
                    ShowStatus(string.Format(_language.ConvertedToX, format.FriendlyName));
                    _oldSubtitleFormat = format;
                    Configuration.Settings.General.LastSaveAsFormat = format.Name;

                    if ((formatType == typeof(AdvancedSubStationAlpha) ||
                        formatType == typeof(SubStationAlpha) ||
                        formatType == typeof(CsvNuendo)) && (_subtitle.Paragraphs.Any(p => !string.IsNullOrEmpty(p.Actor)) ||
                        Configuration.Settings.Tools.ListViewShowColumnActor))
                    {
                        bool wasVisible = SubtitleListview1.ColumnIndexActor >= 0;
                        if (formatType == typeof(CsvNuendo))
                        {
                            SubtitleListview1.ShowActorColumn(Configuration.Settings.Language.General.Character);
                        }
                        else
                        {
                            SubtitleListview1.ShowActorColumn(Configuration.Settings.Language.General.Actor);
                        }
                        if (!wasVisible)
                        {
                            SaveSubtitleListviewIndices();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            RestoreSubtitleListviewIndices();
                        }
                    }
                    else
                    {
                        SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Actor);
                    }

                    if (formatType == typeof(TimedText10) && Configuration.Settings.Tools.ListViewShowColumnRegion)
                    {
                        SubtitleListview1.ShowRegionColumn(Configuration.Settings.Language.General.Region);
                    }
                    else
                    {
                        SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Region);
                    }

                    if (format.HasStyleSupport)
                    {
                        var styles = new List<string>();
                        if (formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha))
                            styles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header);
                        else if (formatType == typeof(TimedText10) || formatType == typeof(ItunesTimedText))
                            styles = TimedText10.GetStylesFromHeader(_subtitle.Header);
                        else if (formatType == typeof(Sami) || formatType == typeof(SamiModern))
                            styles = Sami.GetStylesFromHeader(_subtitle.Header);
                        else if (format.Name == "Nuendo")
                            styles = GetNuendoStyles();

                        if (styles.Count > 0)
                        {
                            foreach (var p in _subtitle.Paragraphs)
                            {
                                if (string.IsNullOrEmpty(p.Extra))
                                    p.Extra = styles[0];
                            }
                        }

                        if (formatType == typeof(Sami) || formatType == typeof(SamiModern))
                            SubtitleListview1.ShowExtraColumn(_languageGeneral.Class);
                        else if (formatType == typeof(TimedText10) || formatType == typeof(ItunesTimedText))
                            SubtitleListview1.ShowExtraColumn(_languageGeneral.StyleLanguage);
                        else if (format.Name == "Nuendo")
                            SubtitleListview1.ShowExtraColumn(_languageGeneral.Character);
                        else
                            SubtitleListview1.ShowExtraColumn(_languageGeneral.Style);

                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    }
                }
                ShowHideTextBasedFeatures(format);

                UpdateNetflixGlyphCheckToolsVisibility();
            }

            private static List<string> GetNuendoStyles()
            {
                if (!string.IsNullOrEmpty(Configuration.Settings.SubtitleSettings.NuendoCharacterListFile) && File.Exists(Configuration.Settings.SubtitleSettings.NuendoCharacterListFile))
                {
                    return NuendoProperties.LoadCharacters(Configuration.Settings.SubtitleSettings.NuendoCharacterListFile);
                }
                return new List<string>();
            }

            private void ComboBoxSubtitleFormatsEnter(object sender, EventArgs e)
            {
                SubtitleFormat format = GetCurrentSubtitleFormat();
                if (format != null)
                    _oldSubtitleFormat = format;
            }

            private SubtitleFormat GetCurrentSubtitleFormat()
            {
                return Utilities.GetSubtitleFormatByFriendlyName(comboBoxSubtitleFormats.SelectedItem.ToString());
            }

            private void ShowSource()
            {
                if (_subtitle != null && _subtitle.Paragraphs.Count > 0)
                {
                    SubtitleFormat format = GetCurrentSubtitleFormat();
                    if (format != null)
                    {
                        if (format.IsFrameBased)
                            _subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                        else
                            _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                        textBoxSource.TextChanged -= TextBoxSourceTextChanged;
                        textBoxSource.Text = GetSaveSubtitle(_subtitle).ToText(format);
                        textBoxSource.TextChanged += TextBoxSourceTextChanged;
                        return;
                    }
                }
                textBoxSource.TextChanged -= TextBoxSourceTextChanged;
                textBoxSource.Text = string.Empty;
                textBoxSource.TextChanged += TextBoxSourceTextChanged;
            }

            private void SettingsToolStripMenuItemClick(object sender, EventArgs e)
            {
                ShowSettings();
            }

            private void ShowSettings()
            {
                string oldVideoPlayer = Configuration.Settings.General.VideoPlayer;
                string oldMpvVideoOutput = Configuration.Settings.General.MpvVideoOutput;
                string oldListViewLineSeparatorString = Configuration.Settings.General.ListViewLineSeparatorString;
                var oldCpsWhiteSpaceSetting = Configuration.Settings.General.CharactersPerSecondsIgnoreWhiteSpace;
                string oldSubtitleFontSettings = Configuration.Settings.General.SubtitleFontName +
                                                 Configuration.Settings.General.SubtitleFontBold +
                                                 Configuration.Settings.General.CenterSubtitleInTextBox +
                                                 Configuration.Settings.General.SubtitleFontSize +
                                                 Configuration.Settings.General.SubtitleFontColor.ToArgb() +
                                                 Configuration.Settings.General.SubtitleBackgroundColor.ToArgb();
                bool oldUseTimeFormatHHMMSSFF = Configuration.Settings.General.UseTimeFormatHHMMSSFF;

                string oldSyntaxColoring = Configuration.Settings.Tools.ListViewSyntaxColorDurationSmall.ToString() +
                                           Configuration.Settings.Tools.ListViewSyntaxColorDurationBig +
                                           Configuration.Settings.Tools.ListViewSyntaxColorLongLines +
                                           Configuration.Settings.Tools.ListViewSyntaxColorOverlap +
                                           Configuration.Settings.Tools.ListViewSyntaxMoreThanXLines +
                                           Configuration.Settings.Tools.ListViewSyntaxMoreThanXLinesX +
                                           Configuration.Settings.Tools.ListViewSyntaxErrorColor.ToArgb();

                var oldAllowEditOfOriginalSubtitle = Configuration.Settings.General.AllowEditOfOriginalSubtitle;
                var oldShowColumnEndTime = Configuration.Settings.Tools.ListViewShowColumnEndTime;
                var oldShowcolumnDuration = Configuration.Settings.Tools.ListViewShowColumnDuration;
                var oldShowColumnCharsPerSec = Configuration.Settings.Tools.ListViewShowColumnCharsPerSec;
                var oldShowWordsMinColumn = Configuration.Settings.Tools.ListViewShowColumnWordsPerMin;
                using (var settings = new Settings())
                {
                    settings.Initialize(Icon, toolStripButtonFileNew.Image, toolStripButtonFileOpen.Image, toolStripButtonSave.Image, toolStripButtonSaveAs.Image, toolStripButtonFind.Image,
                                        toolStripButtonReplace.Image, toolStripButtonFixCommonErrors.Image, toolStripButtonRemoveTextForHi.Image, toolStripButtonVisualSync.Image,
                                        toolStripButtonSpellCheck.Image, toolStripButtonNetflixQualityCheck.Image, toolStripButtonSettings.Image, toolStripButtonHelp.Image);
                    settings.ShowDialog(this);
                }

                try
                { // can have some problems with fonts...
                    UiUtil.InitializeSubtitleFont(textBoxSource);
                    UiUtil.InitializeSubtitleFont(textBoxListViewText);
                    UiUtil.InitializeSubtitleFont(textBoxListViewTextAlternate);
                    UiUtil.InitializeSubtitleFont(SubtitleListview1);
                    InitializeToolbar();
                }
                catch (Exception exception)
                {
                    System.Diagnostics.Debug.WriteLine(exception.Message + Environment.NewLine + exception.StackTrace);
                }
                UpdateRecentFilesUI();
                buttonCustomUrl1.Text = Configuration.Settings.VideoControls.CustomSearchText1;
                buttonCustomUrl1.Visible = Configuration.Settings.VideoControls.CustomSearchUrl1.Length > 1;
                buttonCustomUrl2.Text = Configuration.Settings.VideoControls.CustomSearchText2;
                buttonCustomUrl2.Visible = Configuration.Settings.VideoControls.CustomSearchUrl2.Length > 1;

                audioVisualizer.ShowGridLines = Configuration.Settings.VideoControls.WaveformDrawGrid;
                audioVisualizer.GridColor = Configuration.Settings.VideoControls.WaveformGridColor;
                audioVisualizer.SelectedColor = Configuration.Settings.VideoControls.WaveformSelectedColor;
                audioVisualizer.Color = Configuration.Settings.VideoControls.WaveformColor;
                audioVisualizer.BackgroundColor = Configuration.Settings.VideoControls.WaveformBackgroundColor;
                audioVisualizer.TextColor = Configuration.Settings.VideoControls.WaveformTextColor;
                audioVisualizer.TextSize = Configuration.Settings.VideoControls.WaveformTextSize;
                audioVisualizer.TextBold = Configuration.Settings.VideoControls.WaveformTextBold;
                audioVisualizer.MouseWheelScrollUpIsForward = Configuration.Settings.VideoControls.WaveformMouseWheelScrollUpIsForward;
                audioVisualizer.AllowOverlap = Configuration.Settings.VideoControls.WaveformAllowOverlap;
                audioVisualizer.ClosenessForBorderSelection = Configuration.Settings.VideoControls.WaveformBorderHitMs;

                string newSyntaxColoring = Configuration.Settings.Tools.ListViewSyntaxColorDurationSmall.ToString() +
                                           Configuration.Settings.Tools.ListViewSyntaxColorDurationBig +
                                           Configuration.Settings.Tools.ListViewSyntaxColorLongLines +
                                           Configuration.Settings.Tools.ListViewSyntaxColorOverlap +
                                           Configuration.Settings.Tools.ListViewSyntaxMoreThanXLines +
                                           Configuration.Settings.Tools.ListViewSyntaxMoreThanXLinesX +
                                           Configuration.Settings.Tools.ListViewSyntaxErrorColor.ToArgb();

                if (oldSubtitleFontSettings != Configuration.Settings.General.SubtitleFontName +
                    Configuration.Settings.General.SubtitleFontBold +
                    Configuration.Settings.General.CenterSubtitleInTextBox +
                    Configuration.Settings.General.SubtitleFontSize +
                    Configuration.Settings.General.SubtitleFontColor.ToArgb() +
                    Configuration.Settings.General.SubtitleBackgroundColor.ToArgb() ||
                    oldSyntaxColoring != newSyntaxColoring ||
                    oldShowColumnEndTime != Configuration.Settings.Tools.ListViewShowColumnEndTime ||
                    oldShowcolumnDuration != Configuration.Settings.Tools.ListViewShowColumnDuration ||
                    oldShowColumnCharsPerSec != Configuration.Settings.Tools.ListViewShowColumnCharsPerSec ||
                    oldShowWordsMinColumn != Configuration.Settings.Tools.ListViewShowColumnWordsPerMin)
                {
                    if (Configuration.Settings.Tools.ListViewShowColumnEndTime)
                        SubtitleListview1.ShowEndColumn(Configuration.Settings.Language.General.EndTime);
                    else
                        SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.End);

                    if (Configuration.Settings.Tools.ListViewShowColumnDuration)
                        SubtitleListview1.ShowDurationColumn(Configuration.Settings.Language.General.Duration);
                    else
                        SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Duration);

                    if (Configuration.Settings.Tools.ListViewShowColumnCharsPerSec)
                        SubtitleListview1.ShowCharsSecColumn(Configuration.Settings.Language.General.CharsPerSec);
                    else
                        SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.CharactersPerSeconds);

                    if (Configuration.Settings.Tools.ListViewShowColumnWordsPerMin)
                        SubtitleListview1.ShowWordsMinColumn(Configuration.Settings.Language.General.WordsPerMin);
                    else
                        SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.WordsPerMinute);

                    try
                    { // can have some problems with fonts...
                        UiUtil.InitializeSubtitleFont(textBoxListViewText);
                        UiUtil.InitializeSubtitleFont(textBoxListViewTextAlternate);
                        UiUtil.InitializeSubtitleFont(textBoxSource);
                        SubtitleListview1.SubtitleFontName = Configuration.Settings.General.SubtitleFontName;
                        SubtitleListview1.SubtitleFontBold = Configuration.Settings.General.SubtitleFontBold;
                        SubtitleListview1.SubtitleFontSize = Configuration.Settings.General.SubtitleFontSize;
                    }
                    catch (Exception exception)
                    {
                        System.Diagnostics.Debug.WriteLine(exception.Message + Environment.NewLine + exception.StackTrace);
                    }

                    SubtitleListview1.ForeColor = Configuration.Settings.General.SubtitleFontColor;
                    SubtitleListview1.BackColor = Configuration.Settings.General.SubtitleBackgroundColor;
                    if (Configuration.Settings.General.CenterSubtitleInTextBox)
                    {
                        textBoxListViewText.TextAlign = HorizontalAlignment.Center;
                        textBoxListViewTextAlternate.TextAlign = HorizontalAlignment.Center;
                    }
                    else if (textBoxListViewText.TextAlign == HorizontalAlignment.Center)
                    {
                        textBoxListViewText.TextAlign = HorizontalAlignment.Left;
                        textBoxListViewTextAlternate.TextAlign = HorizontalAlignment.Left;
                    }

                    SaveSubtitleListviewIndices();
                    UiUtil.InitializeSubtitleFont(SubtitleListview1);
                    SubtitleListview1.AutoSizeAllColumns(this);
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    RestoreSubtitleListviewIndices();
                    mediaPlayer.SetSubtitleFont();
                    ShowSubtitle();
                }
                mediaPlayer.SetSubtitleFont();
                mediaPlayer.ShowStopButton = Configuration.Settings.General.VideoPlayerShowStopButton;
                mediaPlayer.ShowMuteButton = Configuration.Settings.General.VideoPlayerShowMuteButton;
                mediaPlayer.ShowFullscreenButton = Configuration.Settings.General.VideoPlayerShowFullscreenButton;

                if (oldListViewLineSeparatorString != Configuration.Settings.General.ListViewLineSeparatorString ||
                    oldCpsWhiteSpaceSetting != Configuration.Settings.General.CharactersPerSecondsIgnoreWhiteSpace)
                {
                    SubtitleListview1.InitializeLanguage(_languageGeneral, Configuration.Settings);
                    SaveSubtitleListviewIndices();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    RestoreSubtitleListviewIndices();
                }

                if (oldAllowEditOfOriginalSubtitle != Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    if (Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                    {
                        AddAlternate();
                    }
                    else
                    {
                        RemoveAlternate(false);
                    }
                    Main_Resize(null, null);
                }
                textBoxListViewTextAlternate.Enabled = Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleListViewIndex >= 0;

                SetShortcuts();

                translatepoweredByMicrosoftToolStripMenuItem.Visible = !string.IsNullOrEmpty(Configuration.Settings.Tools.MicrosoftTranslatorApiKey);

                _timerAutoSave.Stop();

                CheckAndGetNewlyDownloadedMpvDlls();

                if (!string.IsNullOrEmpty(_videoFileName) && oldVideoPlayer != Configuration.Settings.General.VideoPlayer && mediaPlayer.VideoPlayer != null ||
                    (oldMpvVideoOutput != Configuration.Settings.General.MpvVideoOutput && Configuration.Settings.General.VideoPlayer.Equals("MPV", StringComparison.OrdinalIgnoreCase)))
                {
                    string vfn = _videoFileName;
                    CloseVideoToolStripMenuItemClick(null, null);
                    OpenVideo(vfn);
                }

                if (Configuration.Settings.General.AutoBackupSeconds > 0)
                {
                    _timerAutoSave.Interval = 1000 * Configuration.Settings.General.AutoBackupSeconds; // take backup every x second if changes were made
                    _timerAutoSave.Start();
                }
                SetTitle();
                if (Configuration.Settings.VideoControls.GenerateSpectrogram)
                {
                    audioVisualizer.WaveformNotLoadedText = Configuration.Settings.Language.Waveform.ClickToAddWaveformAndSpectrogram;
                    showhideWaveformToolStripMenuItem.Text = _language.Menu.Video.ShowHideWaveformAndSpectrogram;
                }
                else
                {
                    audioVisualizer.WaveformNotLoadedText = Configuration.Settings.Language.Waveform.ClickToAddWaveform;
                    showhideWaveformToolStripMenuItem.Text = _language.Menu.Video.ShowHideWaveform;
                }
                audioVisualizer.Invalidate();

                if (oldUseTimeFormatHHMMSSFF != Configuration.Settings.General.UseTimeFormatHHMMSSFF)
                    RefreshTimeCodeMode();

                SubtitleListview1.SyntaxColorAllLines(_subtitle);
                mediaPlayer.LastParagraph = null;
                Application.DoEvents();
                UiUtil.ShowSubtitle(_subtitle, mediaPlayer);
                mediaPlayer.VideoPlayerContainerResize(null, null);
            }

            private void CheckAndGetNewlyDownloadedMpvDlls()
            {
                if (_videoFileName == null || Configuration.Settings.General.VideoPlayer != "MPV" || mediaPlayer.VideoPlayer == null)
                    return;

                var newMpvFiles = Directory.GetFiles(Configuration.DataDirectory, "*.dll.new-mpv");
                if (newMpvFiles.Length <= 0)
                    return;

                var mpv = mediaPlayer.VideoPlayer as LibMpvDynamic;
                mediaPlayer.VideoPlayer = null;
                mpv?.HardDispose();

                foreach (string newDllFileName in newMpvFiles)
                {
                    if (File.Exists(newDllFileName)) // dll was in use, so unload + copy new dll + load
                    {
                        try
                        {
                            string targetFileName = newDllFileName.Replace(".dll.new-mpv", ".dll");
                            File.Copy(newDllFileName, targetFileName, true);
                            File.Delete(newDllFileName);
                        }
                        catch (Exception)
                        {
                            // ignore
                        }
                    }
                }
                UiUtil.InitializeVideoPlayerAndContainer(_videoFileName, _videoInfo, mediaPlayer, VideoLoaded, VideoEnded);
            }

            private void AddAlternate()
            {
                buttonUnBreak.Visible = false;
                buttonAutoBreak.Visible = false;
                buttonSplitLine.Visible = false;
                textBoxListViewTextAlternate.Visible = true;
                labelAlternateText.Visible = true;
                labelAlternateCharactersPerSecond.Visible = true;
                labelTextAlternateLineLengths.Visible = true;
                labelAlternateSingleLine.Visible = true;
                labelTextAlternateLineTotal.Visible = true;
            }

            private int ShowSubtitle()
            {
                if (_splitDualSami)
                    return UiUtil.ShowSubtitle(_subtitle, _subtitleAlternate, mediaPlayer);
                if (SubtitleListview1.IsAlternateTextColumnVisible && Configuration.Settings.General.ShowOriginalAsPreviewIfAvailable)
                    return UiUtil.ShowSubtitle(_subtitleAlternate, mediaPlayer);
                return UiUtil.ShowSubtitle(_subtitle, mediaPlayer);
            }

            private static void TryLoadIcon(ToolStripButton button, string iconName)
            {
                string fullPath = Configuration.IconsDirectory + iconName + ".png";
                if (File.Exists(fullPath))
                    button.Image = new Bitmap(fullPath);
            }

            private void InitializeToolbar()
            {
                var gs = Configuration.Settings.General;

                TryLoadIcon(toolStripButtonFileNew, "New");
                TryLoadIcon(toolStripButtonFileOpen, "Open");
                TryLoadIcon(toolStripButtonSave, "Save");
                TryLoadIcon(toolStripButtonSaveAs, "SaveAs");
                TryLoadIcon(toolStripButtonFind, "Find");
                TryLoadIcon(toolStripButtonReplace, "Replace");
                TryLoadIcon(toolStripButtonFixCommonErrors, "FixCommonErrors");
                TryLoadIcon(toolStripButtonRemoveTextForHi, "RemoveTextForHi");
                TryLoadIcon(toolStripButtonVisualSync, "VisualSync");
                TryLoadIcon(toolStripButtonSpellCheck, "SpellCheck");
                TryLoadIcon(toolStripButtonNetflixQualityCheck, "NetflixGlyphCheck");
                TryLoadIcon(toolStripButtonSettings, "Settings");
                TryLoadIcon(toolStripButtonHelp, "Help");

                TryLoadIcon(toolStripButtonToggleWaveform, "WaveformToggle");
                TryLoadIcon(toolStripButtonToggleVideo, "VideoToggle");

                toolStripButtonFileNew.Visible = gs.ShowToolbarNew;
                toolStripButtonFileOpen.Visible = gs.ShowToolbarOpen;
                toolStripButtonSave.Visible = gs.ShowToolbarSave;
                toolStripButtonSaveAs.Visible = gs.ShowToolbarSaveAs;
                toolStripButtonFind.Visible = gs.ShowToolbarFind;
                toolStripButtonReplace.Visible = gs.ShowToolbarReplace;
                toolStripButtonFixCommonErrors.Visible = gs.ShowToolbarFixCommonErrors;
                toolStripButtonRemoveTextForHi.Visible = gs.ShowToolbarRemoveTextForHi;

                toolStripButtonVisualSync.Visible = gs.ShowToolbarVisualSync;
                toolStripButtonSpellCheck.Visible = gs.ShowToolbarSpellCheck;
                toolStripButtonNetflixQualityCheck.Visible = gs.ShowToolbarNetflixGlyphCheck;
                toolStripButtonSettings.Visible = gs.ShowToolbarSettings;
                toolStripButtonHelp.Visible = gs.ShowToolbarHelp;

                toolStripSeparatorFrameRate.Visible = gs.ShowFrameRate;
                toolStripLabelFrameRate.Visible = gs.ShowFrameRate;
                toolStripComboBoxFrameRate.Visible = gs.ShowFrameRate;
                toolStripButtonGetFrameRate.Visible = gs.ShowFrameRate;

                toolStripSeparatorFindReplace.Visible = gs.ShowToolbarFind || gs.ShowToolbarReplace;
                toolStripSeparatorFixSyncSpell.Visible = gs.ShowToolbarFixCommonErrors || gs.ShowToolbarVisualSync || gs.ShowToolbarSpellCheck || gs.ShowToolbarSettings;
                toolStripSeparatorHelp.Visible = gs.ShowToolbarHelp;

                toolStrip1.Visible = gs.ShowToolbarNew || gs.ShowToolbarOpen || gs.ShowToolbarSave || gs.ShowToolbarSaveAs || gs.ShowToolbarFind || gs.ShowToolbarReplace ||
                                     gs.ShowToolbarFixCommonErrors || gs.ShowToolbarVisualSync || gs.ShowToolbarSpellCheck || gs.ShowToolbarNetflixGlyphCheck ||
                                     gs.ShowToolbarSettings || gs.ShowToolbarHelp;

                UpdateNetflixGlyphCheckToolsVisibility();
            }

            private void ToolStripButtonFileNewClick(object sender, EventArgs e)
            {
                _lastDoNotPrompt = string.Empty;
                ReloadFromSourceView();
                FileNew();
                ShowHideTextBasedFeatures(GetCurrentSubtitleFormat());
            }

            private void ToolStripButtonFileOpenClick(object sender, EventArgs e)
            {
                toolStripButtonFileOpen.Enabled = false;
                ReloadFromSourceView();
                OpenNewFile();
                toolStripButtonFileOpen.Enabled = true;
            }

            private void ToolStripButtonSaveClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    return;
                }

                ReloadFromSourceView();
                var enc = GetCurrentEncoding().BodyName;
                bool oldChange = _changeSubtitleToString != _subtitle.GetFastHashCode(enc);
                _saveAsCalled = false;
                SaveSubtitle(GetCurrentSubtitleFormat());

                if (_subtitleAlternate != null && _changeAlternateSubtitleToString != _subtitleAlternate.ToText(new SubRip()).Trim() && Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    SaveOriginalToolStripMenuItemClick(null, null);
                    if (oldChange && _changeSubtitleToString == _subtitle.GetFastHashCode(enc) && _changeAlternateSubtitleToString == _subtitleAlternate.ToText(new SubRip()).Trim())
                        ShowStatus(string.Format(_language.SavedSubtitleX, Path.GetFileName(_fileName)) + " + " +
                                   string.Format(_language.SavedOriginalSubtitleX, Path.GetFileName(_subtitleAlternateFileName)));
                }
            }

            private void ToolStripButtonSaveAsClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                FileSaveAs(true);
            }

            private void ToolStripButtonFindClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                Find();
            }

            private void ToolStripButtonVisualSyncClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                ShowVisualSync(false);
            }

            private void ToolStripButtonSettingsClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                ShowSettings();
            }

            private void TextBoxSourceClick(object sender, EventArgs e)
            {
                ShowSourceLineNumber();
            }

            private void TextBoxSourceKeyDown(object sender, KeyEventArgs e)
            {
                ShowSourceLineNumber();
                if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
                {
                    textBoxSource.SelectAll();
                    e.SuppressKeyPress = true;
                }
                if (e.Modifiers == Keys.Control && e.KeyCode == Keys.D)
                {
                    textBoxSource.SelectionLength = 0;
                    e.SuppressKeyPress = true;
                }
            }

            private void textBoxSource_KeyUp(object sender, KeyEventArgs e)
            {
                ShowSourceLineNumber();
            }

            private void TextBoxSourceTextChanged(object sender, EventArgs e)
            {
                ShowSourceLineNumber();
                _sourceViewChange = true;
                labelStatus.Text = string.Empty;
            }

            private void ShowSourceLineNumber()
            {
                if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                {
                    toolStripSelected.Text = string.Format(_language.LineNumberX, textBoxSource.GetLineFromCharIndex(textBoxSource.SelectionStart) + 1);
                }
            }

            private void ButtonGetFrameRateClick(object sender, EventArgs e)
            {
                openFileDialog1.Title = _language.OpenVideoFile;
                openFileDialog1.FileName = string.Empty;
                openFileDialog1.Filter = Utilities.GetVideoFileFilter(false);
                if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    _videoFileName = openFileDialog1.FileName;
                    var info = UiUtil.GetVideoInfo(openFileDialog1.FileName);
                    if (info != null && info.Success)
                    {
                        string oldFrameRate = toolStripComboBoxFrameRate.Text;
                        toolStripComboBoxFrameRate.Text = string.Format("{0:0.###}", info.FramesPerSecond);

                        if (oldFrameRate != toolStripComboBoxFrameRate.Text)
                        {
                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);

                            SubtitleFormat format = Utilities.GetSubtitleFormatByFriendlyName(comboBoxSubtitleFormats.SelectedItem.ToString());
                            if (_subtitle.WasLoadedWithFrameNumbers && format.IsTimeBased)
                            {
                                MessageBox.Show(string.Format(_language.NewFrameRateUsedToCalculateTimeCodes, info.FramesPerSecond));
                            }
                            else if (!_subtitle.WasLoadedWithFrameNumbers && format.IsFrameBased)
                            {
                                MessageBox.Show(string.Format(_language.NewFrameRateUsedToCalculateFrameNumbers, info.FramesPerSecond));
                            }
                        }
                    }
                }
            }

            private void FindToolStripMenuItemClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                Find();
            }

            private void Find()
            {
                string selectedText;
                if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                {
                    selectedText = textBoxSource.SelectedText;
                }
                else
                {
                    if (textBoxListViewTextAlternate.Focused)
                        selectedText = textBoxListViewTextAlternate.SelectedText;
                    else
                        selectedText = textBoxListViewText.SelectedText;
                }

                if (selectedText.Length == 0 && _findHelper != null)
                {
                    if (_clearLastFind)
                    {
                        _clearLastFind = false;
                        _findHelper.FindReplaceType.FindType = _clearLastFindType;
                        selectedText = _clearLastFindText;
                    }
                    else
                    {
                        selectedText = _findHelper.FindText;
                    }
                }

                using (var findDialog = new FindDialog(_subtitle))
                {
                    findDialog.SetIcon(toolStripButtonFind.Image as Bitmap);
                    findDialog.Initialize(selectedText, _findHelper);
                    if (findDialog.ShowDialog(this) != DialogResult.OK)
                    {
                        return;
                    }

                    _findHelper = findDialog.GetFindDialogHelper(_subtitleListViewIndex);
                    if (!string.IsNullOrWhiteSpace(_findHelper.FindText))
                    {
                        if (Configuration.Settings.Tools.FindHistory.Count == 0 || Configuration.Settings.Tools.FindHistory[0] != _findHelper.FindText)
                            Configuration.Settings.Tools.FindHistory.Insert(0, _findHelper.FindText);
                    }
                    ShowStatus(string.Format(_language.SearchingForXFromLineY, _findHelper.FindText, _subtitleListViewIndex + 1));
                    if (tabControlSubtitle.SelectedIndex == TabControlListView)
                    {
                        var tb = GetFindRepaceTextBox();
                        int startPos = tb.SelectedText.Length > 0 ? tb.SelectionStart + 1 : tb.SelectionStart;
                        bool found = _findHelper.Find(_subtitle, _subtitleAlternate, _subtitleListViewIndex, startPos);
                        tb = GetFindRepaceTextBox();
                        //if we fail to find the text, we might want to start searching from the top of the file.
                        if (!found && _findHelper.StartLineIndex >= 1)
                        {
                            if (MessageBox.Show(_language.FindContinue, _language.FindContinueTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                found = _findHelper.Find(_subtitle, _subtitleAlternate, -1);
                            }
                        }
                        if (found)
                        {
                            SubtitleListview1.SelectIndexAndEnsureVisible(_findHelper.SelectedIndex, true);
                            tb.Focus();
                            tb.SelectionStart = _findHelper.SelectedPosition;
                            tb.SelectionLength = _findHelper.FindTextLength;
                            ShowStatus(string.Format(_language.XFoundAtLineNumberY, _findHelper.FindText, _findHelper.SelectedIndex + 1));
                            _findHelper.SelectedPosition++;
                        }
                        else
                        {
                            ShowStatus(string.Format(_language.XNotFound, _findHelper.FindText));
                        }
                    }
                    else if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                    {
                        if (_findHelper.Find(textBoxSource, textBoxSource.SelectionStart))
                        {
                            textBoxSource.SelectionStart = _findHelper.SelectedIndex;
                            textBoxSource.SelectionLength = _findHelper.FindTextLength;
                            textBoxSource.ScrollToCaret();
                            ShowStatus(string.Format(_language.XFoundAtLineNumberY, _findHelper.FindText, textBoxSource.GetLineFromCharIndex(textBoxSource.SelectionStart)));
                        }
                        else
                        {
                            ShowStatus(string.Format(_language.XNotFound, _findHelper.FindText));
                        }
                    }
                }
            }

            private void FindNextToolStripMenuItemClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                FindNext();
            }

            private TextBox GetFindRepaceTextBox()
            {
                return _findHelper.MatchInOriginal ? textBoxListViewTextAlternate : textBoxListViewText;
            }

            private void FindNext()
            {
                if (_findHelper != null)
                {
                    TextBox tb = GetFindRepaceTextBox();
                    if (tabControlSubtitle.SelectedIndex == TabControlListView)
                    {
                        int selectedIndex = -1;
                        if (SubtitleListview1.SelectedItems.Count > 0)
                            selectedIndex = SubtitleListview1.SelectedItems[0].Index;

                        int textBoxStart = tb.SelectionStart;
                        if (_findHelper.SelectedPosition - 1 == tb.SelectionStart && tb.SelectionLength > 0)
                        {
                            textBoxStart = tb.SelectionStart + 1;
                        }

                        if (_findHelper.FindNext(_subtitle, _subtitleAlternate, selectedIndex, textBoxStart, Configuration.Settings.General.AllowEditOfOriginalSubtitle))
                        {
                            tb = GetFindRepaceTextBox();
                            SubtitleListview1.SelectIndexAndEnsureVisible(_findHelper.SelectedIndex, true);
                            ShowStatus(string.Format(_language.XFoundAtLineNumberY, _findHelper.FindText, _findHelper.SelectedIndex + 1));
                            tb.Focus();
                            tb.SelectionStart = _findHelper.SelectedPosition;
                            tb.SelectionLength = _findHelper.FindTextLength;
                            _findHelper.SelectedPosition++;
                        }
                        else
                        {
                            if (_findHelper.StartLineIndex >= 1)
                            {
                                if (MessageBox.Show(_language.FindContinue, _language.FindContinueTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    _findHelper.StartLineIndex = 0;
                                    if (_findHelper.Find(_subtitle, _subtitleAlternate, 0))
                                    {
                                        SubtitleListview1.SelectIndexAndEnsureVisible(_findHelper.SelectedIndex, true);
                                        tb.Focus();
                                        tb.SelectionStart = _findHelper.SelectedPosition;
                                        tb.SelectionLength = _findHelper.FindTextLength;
                                        ShowStatus(string.Format(_language.XFoundAtLineNumberY, _findHelper.FindText, _findHelper.SelectedIndex + 1));
                                        _findHelper.SelectedPosition++;
                                        return;
                                    }
                                }
                            }
                            ShowStatus(string.Format(_language.XNotFound, _findHelper.FindText));
                        }
                    }
                    else if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                    {
                        if (_findHelper.FindNext(textBoxSource.Text, textBoxSource.SelectionStart))
                        {
                            textBoxSource.SelectionStart = _findHelper.SelectedIndex;
                            textBoxSource.SelectionLength = _findHelper.FindTextLength;
                            textBoxSource.ScrollToCaret();
                            ShowStatus(string.Format(_language.XFoundAtLineNumberY, _findHelper.FindText, textBoxSource.GetLineFromCharIndex(textBoxSource.SelectionStart)));
                        }
                        else
                        {
                            ShowStatus(string.Format(_language.XNotFound, _findHelper.FindText));
                        }
                    }
                }
                else
                {
                    Find();
                }
            }

            private void ToolStripButtonReplaceClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                Replace(null);
            }

            private void ReplaceToolStripMenuItemClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                Replace(null);
            }

            private void ReplaceSourceView(ReplaceDialog replaceDialog)
            {
                bool isFirst = true;
                string selectedText = textBoxSource.SelectedText;
                if (selectedText.Length == 0 && _findHelper != null)
                    selectedText = _findHelper.FindText;

                if (replaceDialog == null)
                {
                    replaceDialog = new ReplaceDialog();
                    replaceDialog.SetIcon(toolStripButtonReplace.Image as Bitmap);
                    _findHelper = _findHelper ?? replaceDialog.GetFindDialogHelper(_subtitleListViewIndex);
                }
                else
                    isFirst = false;

                replaceDialog.Initialize(selectedText, _findHelper);
                if (replaceDialog.ShowDialog(this) == DialogResult.OK)
                {
                    _findHelper = replaceDialog.GetFindDialogHelper(_subtitleListViewIndex);
                    ShowStatus(string.Format(_language.SearchingForXFromLineY, _findHelper.FindText, _subtitleListViewIndex + 1));
                    if (replaceDialog.ReplaceAll)
                    {
                        SourceListReplaceAll(replaceDialog, _findHelper);
                        return;
                    }
                    int replaceCount = 0;
                    bool searchStringFound = true;
                    if (searchStringFound)
                    {
                        searchStringFound = false;
                        int start = textBoxSource.SelectionStart;
                        if (isFirst)
                        {
                            MakeHistoryForUndo(string.Format(_language.BeforeReplace, _findHelper.FindText));
                            isFirst = false;
                            _makeHistoryPaused = true;
                            if (start >= 0)
                                start--;
                        }
                        else
                        {
                            if (textBoxSource.SelectionLength > 0 && start > 0 && !replaceDialog.FindOnly)
                                start--;
                        }

                        if (_findHelper.FindNext(textBoxSource.Text, start))
                        {
                            textBoxSource.SelectionStart = _findHelper.SelectedIndex;
                            textBoxSource.SelectionLength = _findHelper.FindTextLength;
                            if (!replaceDialog.FindOnly)
                                textBoxSource.SelectedText = _findHelper.ReplaceText;
                            textBoxSource.ScrollToCaret();

                            replaceCount++;
                            searchStringFound = true;

                            if (!replaceDialog.FindOnly)
                            {
                                if (_findHelper.FindNext(textBoxSource.Text, start))
                                {
                                    textBoxSource.SelectionStart = _findHelper.SelectedIndex;
                                    textBoxSource.SelectionLength = _findHelper.FindTextLength;
                                    textBoxSource.ScrollToCaret();
                                }
                                Replace(replaceDialog);
                                return;
                            }
                        }
                        if (replaceDialog.FindOnly)
                        {
                            if (searchStringFound)
                                ShowStatus(string.Format(_language.MatchFoundX, _findHelper.FindText));
                            else
                                ShowStatus(string.Format(_language.NoMatchFoundX, _findHelper.FindText));

                            Replace(replaceDialog);
                            return;
                        }
                    }
                    ReloadFromSourceView();
                    if (replaceCount == 0)
                        ShowStatus(_language.FoundNothingToReplace);
                    else
                        ShowStatus(string.Format(_language.ReplaceCountX, replaceCount));
                }
                if (_makeHistoryPaused)
                    RestartHistory();
                replaceDialog.Dispose();
            }

            private void SourceListReplaceAll(ReplaceDialog replaceDialog, FindReplaceDialogHelper findHelper)
            {
                int replaceCount = 0;
                bool searchStringFound = true;
                int start = textBoxSource.SelectionStart;
                bool isFirst = true;
                string text = textBoxSource.Text;
                while (searchStringFound)
                {
                    searchStringFound = false;
                    if (isFirst)
                    {
                        MakeHistoryForUndo(string.Format(_language.BeforeReplace, _findHelper.FindText));
                        isFirst = false;
                        _makeHistoryPaused = true;
                        if (start >= 0)
                            start--;
                    }
                    else
                    {
                        start--;
                    }

                    if (_findHelper.FindNext(text, start))
                    {
                        text = text.Remove(findHelper.SelectedIndex, findHelper.FindTextLength).Insert(findHelper.SelectedIndex, findHelper.ReplaceText);
                        start = findHelper.SelectedIndex + findHelper.FindTextLength;
                        replaceCount++;
                        searchStringFound = true;
                    }
                }
                textBoxSource.Text = text;
                ReloadFromSourceView();
                if (replaceCount == 0)
                    ShowStatus(_language.FoundNothingToReplace);
                else
                    ShowStatus(string.Format(_language.ReplaceCountX, replaceCount));

                if (_makeHistoryPaused)
                    RestartHistory();
                replaceDialog.Dispose();
            }

            private void ReplaceListView(ReplaceDialog replaceDialog)
            {
                SaveSubtitleListviewIndices();
                int firstIndex = FirstSelectedIndex;
                bool isFirst = true;
                string selectedText;
                if (textBoxListViewTextAlternate.Focused)
                    selectedText = textBoxListViewTextAlternate.SelectedText;
                else
                    selectedText = textBoxListViewText.SelectedText;

                if (selectedText.Length == 0 && _findHelper != null)
                    selectedText = _findHelper.FindText;

                if (replaceDialog == null)
                {
                    replaceDialog = new ReplaceDialog();
                    replaceDialog.SetIcon(toolStripButtonReplace.Image as Bitmap);
                    _findHelper = _findHelper ?? replaceDialog.GetFindDialogHelper(_subtitleListViewIndex);
                    int index = 0;

                    if (SubtitleListview1.SelectedItems.Count > 0)
                        index = SubtitleListview1.SelectedItems[0].Index;

                    _findHelper.SelectedIndex = index;
                    _findHelper.SelectedPosition = index;
                    _replaceStartLineIndex = index;
                }
                else
                {
                    isFirst = false;
                    if (_findHelper != null)
                        selectedText = _findHelper.FindText;
                }
                replaceDialog.Initialize(selectedText, _findHelper);
                if (replaceDialog.ShowDialog(this) == DialogResult.OK)
                {
                    if (_findHelper == null)
                    {
                        _findHelper = replaceDialog.GetFindDialogHelper(_subtitleListViewIndex);
                    }
                    else
                    {
                        int line = _findHelper.SelectedIndex;
                        int pos = _findHelper.SelectedPosition;
                        bool success = _findHelper.Success;
                        var matchInOriginal = _findHelper.MatchInOriginal;
                        _findHelper = replaceDialog.GetFindDialogHelper(_subtitleListViewIndex);
                        _findHelper.SelectedIndex = line;
                        _findHelper.SelectedPosition = pos;
                        _findHelper.Success = success;
                        _findHelper.MatchInOriginal = matchInOriginal;
                    }
                    ShowStatus(string.Format(_language.SearchingForXFromLineY, _findHelper.FindText, _subtitleListViewIndex + 1));
                    int replaceCount = 0;
                    bool searchStringFound = true;
                    while (searchStringFound)
                    {
                        searchStringFound = false;
                        if (isFirst)
                        {
                            MakeHistoryForUndo(string.Format(_language.BeforeReplace, _findHelper.FindText));
                            isFirst = false;
                            _makeHistoryPaused = true;
                        }

                        if (replaceDialog.ReplaceAll)
                        {
                            if (_findHelper.FindNext(_subtitle, _subtitleAlternate, _findHelper.SelectedIndex, _findHelper.SelectedPosition, Configuration.Settings.General.AllowEditOfOriginalSubtitle))
                            {
                                textBoxListViewText.Visible = false;
                                SetTextForFindAndReplace(true);
                                _findHelper.SelectedPosition += _findHelper.ReplaceText.Length;
                                searchStringFound = true;
                                replaceCount++;
                            }
                            else
                            {
                                textBoxListViewText.Visible = true;
                                _subtitleListViewIndex = -1;
                                if (firstIndex >= 0 && firstIndex < SubtitleListview1.Items.Count)
                                {
                                    SubtitleListview1.Items[firstIndex].Selected = true;
                                    SubtitleListview1.Items[firstIndex].Focused = true;
                                    SubtitleListview1.Focus();
                                    textBoxListViewText.Text = _subtitle.Paragraphs[firstIndex].Text;
                                    if (_subtitleAlternate != null && textBoxListViewTextAlternate.Visible)
                                    {
                                        var orginial = Utilities.GetOriginalParagraph(_findHelper.SelectedIndex, _subtitle.Paragraphs[_findHelper.SelectedIndex], _subtitleAlternate.Paragraphs);
                                        if (orginial != null)
                                            textBoxListViewTextAlternate.Text = orginial.Text;
                                    }
                                }
                                else
                                {
                                    SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                                }
                                ShowStatus(string.Format(_language.NoMatchFoundX, _findHelper.FindText));

                                if (_replaceStartLineIndex >= 1) // Prompt for start over
                                {
                                    _replaceStartLineIndex = 0;
                                    string msgText = _language.ReplaceContinueNotFound;
                                    if (replaceCount > 0)
                                        msgText = string.Format(_language.ReplaceXContinue, replaceCount);
                                    if (MessageBox.Show(msgText, _language.ReplaceContinueTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                                    {
                                        _findHelper.StartLineIndex = 0;
                                        _findHelper.SelectedIndex = 0;
                                        _findHelper.SelectedPosition = 0;
                                        SetTextForFindAndReplace(false);

                                        if (_findHelper.FindNext(_subtitle, _subtitleAlternate, _findHelper.SelectedIndex, _findHelper.SelectedPosition, Configuration.Settings.General.AllowEditOfOriginalSubtitle))
                                        {
                                            SetTextForFindAndReplace(true);
                                            _findHelper.SelectedPosition += _findHelper.ReplaceText.Length;
                                            searchStringFound = true;
                                            replaceCount++;
                                        }
                                    }
                                }
                            }
                        }
                        else if (replaceDialog.FindOnly)
                        {
                            if (_findHelper.FindNext(_subtitle, _subtitleAlternate, _findHelper.SelectedIndex, _findHelper.SelectedPosition, Configuration.Settings.General.AllowEditOfOriginalSubtitle))
                            {
                                var tb = GetFindRepaceTextBox();
                                SubtitleListview1.SelectIndexAndEnsureVisible(_findHelper.SelectedIndex, true);
                                tb.Focus();
                                tb.SelectionStart = _findHelper.SelectedPosition;
                                tb.SelectionLength = _findHelper.FindTextLength;
                                _findHelper.SelectedPosition += _findHelper.FindTextLength;
                                ShowStatus(string.Format(_language.NoXFoundAtLineY, _findHelper.SelectedIndex + 1, _findHelper.FindText));
                                Replace(replaceDialog);
                                if (replaceDialog != null && !replaceDialog.IsDisposed)
                                {
                                    replaceDialog.Dispose();
                                    replaceDialog = null;
                                }
                                return;
                            }
                            if (_replaceStartLineIndex >= 1) // Prompt for start over
                            {
                                _replaceStartLineIndex = 0;
                                if (MessageBox.Show(_language.FindContinue, _language.FindContinueTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                                    _findHelper.StartLineIndex = 0;
                                    _findHelper.SelectedIndex = 0;
                                    _findHelper.SelectedPosition = 0;
                                    if (_findHelper.FindNext(_subtitle, _subtitleAlternate, _findHelper.SelectedIndex, _findHelper.SelectedPosition, Configuration.Settings.General.AllowEditOfOriginalSubtitle))
                                    {
                                        var tb = GetFindRepaceTextBox();
                                        SubtitleListview1.SelectIndexAndEnsureVisible(_findHelper.SelectedIndex, true);
                                        tb.Focus();
                                        tb.SelectionStart = _findHelper.SelectedPosition;
                                        tb.SelectionLength = _findHelper.FindTextLength;
                                        _findHelper.SelectedPosition += _findHelper.FindTextLength;
                                        ShowStatus(string.Format(_language.NoXFoundAtLineY, _findHelper.SelectedIndex + 1, _findHelper.FindText));
                                        Replace(replaceDialog);
                                        if (replaceDialog != null)
                                        {
                                            replaceDialog.Dispose();
                                            replaceDialog = null;
                                        }
                                        return;
                                    }
                                }
                                else
                                {
                                    if (replaceDialog != null && !replaceDialog.IsDisposed)
                                    {
                                        replaceDialog.Dispose();
                                        replaceDialog = null;
                                    }
                                    return;
                                }
                            }
                            ShowStatus(string.Format(_language.NoMatchFoundX, _findHelper.FindText));
                        }
                        else if (!replaceDialog.FindOnly) // replace once only
                        {
                            var tb = GetFindRepaceTextBox();
                            string msg = string.Empty;
                            if (_findHelper.FindReplaceType.FindType == FindType.RegEx && _findHelper.Success)
                            {
                                if (_findHelper.FindReplaceType.FindType == FindType.RegEx)
                                {
                                    ReplaceViaRegularExpression(tb);
                                }
                                else
                                {
                                    tb.SelectedText = _findHelper.ReplaceText;
                                }
                                msg = _language.OneReplacementMade + " ";
                            }
                            else if (tb.SelectionLength == _findHelper.FindTextLength)
                            {
                                tb.SelectedText = _findHelper.ReplaceText;
                                msg = _language.OneReplacementMade + " ";
                            }

                            if (_findHelper.FindNext(_subtitle, _subtitleAlternate, _findHelper.SelectedIndex, _findHelper.SelectedPosition, Configuration.Settings.General.AllowEditOfOriginalSubtitle))
                            {
                                SubtitleListview1.SelectIndexAndEnsureVisible(_findHelper.SelectedIndex, true);
                                tb = GetFindRepaceTextBox();
                                tb.Focus();
                                tb.SelectionStart = _findHelper.SelectedPosition;
                                tb.SelectionLength = _findHelper.FindTextLength;
                                if (_findHelper.FindReplaceType.FindType == FindType.RegEx)
                                {
                                    _findHelper.SelectedPosition += _findHelper.FindTextLength;
                                }
                                else
                                {
                                    _findHelper.SelectedPosition += _findHelper.ReplaceText.Length;
                                }
                                ShowStatus(string.Format(msg + _language.XFoundAtLineNumberY, _findHelper.FindText, _findHelper.SelectedIndex + 1));
                            }
                            else
                            {
                                ShowStatus(msg + string.Format(_language.XNotFound, _findHelper.FindText));

                                // Prompt for start over
                                if (_replaceStartLineIndex >= 1)
                                {
                                    _replaceStartLineIndex = 0;
                                    if (MessageBox.Show(_language.FindContinue, _language.FindContinueTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                                    {
                                        SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                                        _findHelper.StartLineIndex = 0;
                                        _findHelper.SelectedIndex = 0;
                                        _findHelper.SelectedPosition = 0;

                                        if (_findHelper.FindNext(_subtitle, _subtitleAlternate, _findHelper.SelectedIndex, _findHelper.SelectedPosition, Configuration.Settings.General.AllowEditOfOriginalSubtitle))
                                        {
                                            SubtitleListview1.SelectIndexAndEnsureVisible(_findHelper.SelectedIndex, true);
                                            tb = GetFindRepaceTextBox();
                                            tb.Focus();
                                            tb.SelectionStart = _findHelper.SelectedPosition;
                                            tb.SelectionLength = _findHelper.FindTextLength;
                                            _findHelper.SelectedPosition += _findHelper.ReplaceText.Length;
                                            ShowStatus(string.Format(msg + _language.XFoundAtLineNumberY, _findHelper.FindText, _findHelper.SelectedIndex + 1));
                                        }
                                    }
                                    else
                                    {
                                        if (replaceDialog != null && !replaceDialog.IsDisposed)
                                        {
                                            replaceDialog.Dispose();
                                            replaceDialog = null;
                                        }
                                        return;
                                    }
                                }
                            }
                            Replace(replaceDialog);
                            if (replaceDialog != null && !replaceDialog.IsDisposed)
                            {
                                replaceDialog.Dispose();
                                replaceDialog = null;
                            }
                            return;
                        }
                    }

                    ShowSource();
                    if (replaceCount == 0)
                        ShowStatus(_language.FoundNothingToReplace);
                    else
                        ShowStatus(string.Format(_language.ReplaceCountX, replaceCount));
                }
                RestoreSubtitleListviewIndices();
                if (_makeHistoryPaused)
                    RestartHistory();
                replaceDialog.Dispose();
            }

            private void ReplaceViaRegularExpression(TextBox tb)
            {
                var r = new Regex(_findHelper.FindText, RegexOptions.Multiline);
                string result = RegexUtils.ReplaceNewLineSafe(r, tb.Text, _findHelper.ReplaceText);
                if (result != tb.Text)
                {
                    tb.Text = result;
                }
            }

            private void SetTextForFindAndReplace(bool replace)
            {
                _subtitleListViewIndex = _findHelper.SelectedIndex;
                textBoxListViewText.Text = _subtitle.Paragraphs[_findHelper.SelectedIndex].Text;
                if (_subtitleAlternate != null && textBoxListViewTextAlternate.Visible)
                {
                    var orginial = Utilities.GetOriginalParagraph(_findHelper.SelectedIndex, _subtitle.Paragraphs[_findHelper.SelectedIndex], _subtitleAlternate.Paragraphs);
                    if (orginial != null)
                        textBoxListViewTextAlternate.Text = orginial.Text;
                }

                if (replace)
                {
                    var tb = GetFindRepaceTextBox();
                    if (_findHelper.MatchInOriginal)
                    {
                        textBoxListViewTextAlternate.SelectionStart = _findHelper.SelectedPosition;
                        textBoxListViewTextAlternate.SelectionLength = _findHelper.FindTextLength;
                        textBoxListViewTextAlternate.SelectedText = _findHelper.ReplaceText;
                    }
                    else
                    {
                        tb.SelectionStart = _findHelper.SelectedPosition;
                        tb.SelectionLength = _findHelper.FindTextLength;
                        if (_findHelper.FindReplaceType.FindType == FindType.RegEx)
                        {
                            ReplaceViaRegularExpression(tb);
                            _findHelper.SelectedPosition += _findHelper.FindTextLength;
                        }
                        else
                        {
                            tb.SelectedText = _findHelper.ReplaceText;
                            _findHelper.SelectedPosition += _findHelper.ReplaceText.Length;
                        }
                    }
                }
            }

            private void Replace(ReplaceDialog replaceDialog)
            {
                if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                {
                    ReplaceSourceView(replaceDialog);
                }
                else
                {
                    ReplaceListView(replaceDialog);
                }
            }

            public void ShowStatus(string message)
            {
                labelStatus.Text = message.Replace("&", "&&");
                statusStrip1.Refresh();
                if (!string.IsNullOrEmpty(message))
                {
                    _timerClearStatus.Stop();
                    _statusLog.Add(string.Format("{0:0000}-{1:00}-{2:00} {3}: {4}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.ToLongTimeString(), message));
                    _timerClearStatus.Start();
                }
                ShowSourceLineNumber();
                ShowLineInformationListView();
            }

            private void ReloadFromSourceView()
            {
                if (_sourceViewChange)
                {
                    SaveSubtitleListviewIndices();
                    if (!string.IsNullOrWhiteSpace(textBoxSource.Text))
                    {
                        SubtitleFormat format = GetCurrentSubtitleFormat();
                        var list = textBoxSource.Lines.ToList();
                        format = new Subtitle().ReloadLoadSubtitle(list, null, format);
                        if (format == null)
                        {
                            MessageBox.Show(_language.UnableToParseSourceView);
                            return;
                        }
                        _sourceViewChange = false;
                        MakeHistoryForUndo(_language.BeforeChangesMadeInSourceView);
                        _subtitle.ReloadLoadSubtitle(list, null, format);
                        if (format.IsFrameBased)
                            _subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                        int index = 0;
                        foreach (object obj in comboBoxSubtitleFormats.Items)
                        {
                            if (obj.ToString() == format.FriendlyName)
                                comboBoxSubtitleFormats.SelectedIndex = index;
                            index++;
                        }

                        if (Configuration.Settings.General.CurrentVideoOffsetInMs > 0)
                        {
                            _subtitle.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(-Configuration.Settings.General.CurrentVideoOffsetInMs));
                        }

                        var formatType = format.GetType();
                        if (formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha))
                        {
                            string errors = AdvancedSubStationAlpha.CheckForErrors(_subtitle.Header);
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(SubRip))
                        {
                            string errors = (format as SubRip).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(MicroDvd))
                        {
                            string errors = (format as MicroDvd).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(DCinemaSmpte2007))
                        {
                            format.ToText(_subtitle, string.Empty);
                            string errors = (format as DCinemaSmpte2007).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (formatType == typeof(DCinemaSmpte2010))
                        {
                            format.ToText(_subtitle, string.Empty);
                            string errors = (format as DCinemaSmpte2010).Errors;
                            if (!string.IsNullOrEmpty(errors))
                                MessageBox.Show(errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else
                    {
                        _sourceViewChange = false;
                        MakeHistoryForUndo(_language.BeforeChangesMadeInSourceView);
                        _sourceViewChange = false;
                        _subtitle.Paragraphs.Clear();
                    }
                    _subtitleListViewIndex = -1;
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    RestoreSubtitleListviewIndices();
                }
            }

            private void HelpToolStripMenuItem1Click(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                Utilities.ShowHelp(string.Empty);
            }

            private void ToolStripButtonHelpClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                Utilities.ShowHelp(string.Empty);
            }

            private void GotoLineNumberToolStripMenuItemClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                using (var goToLine = new GoToLine())
                {
                    if (tabControlSubtitle.SelectedIndex == TabControlListView)
                    {
                        goToLine.Initialize(1, SubtitleListview1.Items.Count);
                    }
                    else if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                    {
                        goToLine.Initialize(1, textBoxSource.Lines.Length);
                    }
                    if (goToLine.ShowDialog(this) == DialogResult.OK)
                    {
                        if (tabControlSubtitle.SelectedIndex == TabControlListView)
                        {
                            SubtitleListview1.SelectNone();

                            SubtitleListview1.Items[goToLine.LineNumber - 1].Selected = true;
                            SubtitleListview1.Items[goToLine.LineNumber - 1].EnsureVisible();
                            SubtitleListview1.Items[goToLine.LineNumber - 1].Focused = true;
                            ShowStatus(string.Format(_language.GoToLineNumberX, goToLine.LineNumber));
                        }
                        else if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                        {
                            textBoxSource.SelectionStart = textBoxSource.GetFirstCharIndexFromLine(goToLine.LineNumber - 1);
                            textBoxSource.SelectionLength = textBoxSource.Lines[goToLine.LineNumber - 1].Length;
                            textBoxSource.ScrollToCaret();
                            ShowSourceLineNumber();
                        }
                    }
                }
            }

            private void TextBoxSourceLeave(object sender, EventArgs e)
            {
                ReloadFromSourceView();
            }

            private void AdjustDisplayTimeToolStripMenuItemClick(object sender, EventArgs e)
            {
                AdjustDisplayTime(false);
            }

            private void AdjustDisplayTime(bool onlySelectedLines)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var adjustDisplayTime = new AdjustDisplayDuration())
                {
                    List<int> selectedIndices = null;
                    if (onlySelectedLines)
                    {
                        adjustDisplayTime.Text += " - " + _language.SelectedLines;
                        selectedIndices = new List<int>();
                        foreach (int item in SubtitleListview1.SelectedIndices)
                        {
                            selectedIndices.Add(item);
                        }
                    }

                    if (adjustDisplayTime.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeDisplayTimeAdjustment);
                        if (adjustDisplayTime.AdjustUsingPercent)
                        {
                            double percent = double.Parse(adjustDisplayTime.AdjustValue);
                            _subtitle.AdjustDisplayTimeUsingPercent(percent, selectedIndices);
                            ShowStatus(string.Format(_language.DisplayTimesAdjustedX, double.Parse(adjustDisplayTime.AdjustValue, CultureInfo.InvariantCulture) + "%"));
                        }
                        else if (adjustDisplayTime.AdjustUsingSeconds)
                        {
                            double seconds = double.Parse(adjustDisplayTime.AdjustValue, CultureInfo.InvariantCulture);
                            _subtitle.AdjustDisplayTimeUsingSeconds(seconds, selectedIndices);
                            ShowStatus(string.Format(_language.DisplayTimesAdjustedX, double.Parse(adjustDisplayTime.AdjustValue, CultureInfo.InvariantCulture)));
                        }
                        else
                        { // recalculate durations!!!
                            double maxCharSeconds = (double)(adjustDisplayTime.MaxCharactersPerSecond);
                            _subtitle.RecalculateDisplayTimes(maxCharSeconds, selectedIndices);
                            ShowStatus(string.Format(_language.DisplayTimesAdjustedX, adjustDisplayTime.AdjustValue));
                        }
                        SaveSubtitleListviewIndices();
                        if (IsFramesRelevant && CurrentFrameRate > 0)
                        {
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                            if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                                ShowSource();
                        }
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private bool IsFramesRelevant
            {
                get { return _subtitle.WasLoadedWithFrameNumbers || GetCurrentSubtitleFormat().IsFrameBased; }
            }

            private void FixToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (_networkSession == null)
                    FixCommonErrors(false);
            }

            private void FixCommonErrors(bool onlySelectedLines)
            {
                if (IsSubtitleLoaded)
                {
                    ReloadFromSourceView();
                    SaveSubtitleListviewIndices();
                    using (var fixErrors = new FixCommonErrors())
                    {
                        if (onlySelectedLines)
                        {
                            var selectedLines = new Subtitle { WasLoadedWithFrameNumbers = _subtitle.WasLoadedWithFrameNumbers };
                            foreach (int index in SubtitleListview1.SelectedIndices)
                                selectedLines.Paragraphs.Add(_subtitle.Paragraphs[index]);
                            fixErrors.Initialize(selectedLines, GetCurrentSubtitleFormat(), GetCurrentEncoding());
                        }
                        else
                        {
                            fixErrors.Initialize(_subtitle, GetCurrentSubtitleFormat(), GetCurrentEncoding());
                        }

                        if (fixErrors.ShowDialog(this) == DialogResult.OK)
                        {
                            MakeHistoryForUndo(_language.BeforeCommonErrorFixes);
                            _subtitle.Renumber();
                            if (onlySelectedLines)
                            {
                                // we only update selected lines
                                if (_networkSession != null)
                                {
                                    var deletes = new List<int>();
                                    _networkSession.TimerStop();
                                    foreach (int index in SubtitleListview1.SelectedIndices)
                                    {
                                        var pOld = _subtitle.Paragraphs[index];
                                        var p = fixErrors.FixedSubtitle.GetParagraphOrDefaultById(pOld.ID);
                                        if (p == null)
                                        {
                                            deletes.Add(index);
                                        }
                                        else
                                        {
                                            _subtitle.Paragraphs[index] = p;
                                            SubtitleListview1.SetTimeAndText(index, p, _subtitle.GetParagraphOrDefault(index + 1));
                                        }
                                    }
                                    NetworkGetSendUpdates(deletes, 0, null);
                                }
                                else
                                {
                                    for (int index = SubtitleListview1.SelectedIndices.Count - 1; index >= 0; index--)
                                    {
                                        var idx = SubtitleListview1.SelectedIndices[index];
                                        var pOld = _subtitle.Paragraphs[idx];
                                        var p = fixErrors.FixedSubtitle.GetParagraphOrDefaultById(pOld.ID);
                                        if (p == null)
                                        {
                                            _subtitle.Paragraphs.RemoveAt(idx);
                                        }
                                        else
                                        {
                                            _subtitle.Paragraphs[idx] = p;
                                        }
                                    }
                                }
                                ShowStatus(_language.CommonErrorsFixedInSelectedLines);
                            }
                            else
                            {
                                _subtitle.Paragraphs.Clear();
                                foreach (var p in fixErrors.FixedSubtitle.Paragraphs)
                                    _subtitle.Paragraphs.Add(p);
                                ShowStatus(_language.CommonErrorsFixed);
                            }
                            _subtitle.Renumber();
                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            RestoreSubtitleListviewIndices();
                        }
                        Configuration.Settings.CommonErrors.StartSize = fixErrors.Width + ";" + fixErrors.Height;
                        Configuration.Settings.CommonErrors.StartPosition = fixErrors.Left + ";" + fixErrors.Top;
                    }
                }
                else
                {
                    DisplaySubtitleNotLoadedMessage();
                }
                ShowInTaskbar = true;
            }

            private void StartNumberingFromToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var startNumberingFrom = new StartNumberingFrom())
                {
                    if (startNumberingFrom.ShowDialog(this) == DialogResult.OK)
                    {
                        SaveSubtitleListviewIndices();
                        MakeHistoryForUndo(_language.BeforeRenumbering);
                        ShowStatus(string.Format(_language.RenumberedStartingFromX, startNumberingFrom.StartFromNumber));
                        _subtitle.Renumber(startNumberingFrom.StartFromNumber);
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            internal void ReloadFromSubtitle(Subtitle subtitle, string messageForUndo)
            {
                MakeHistoryForUndo(messageForUndo);
                _subtitle.Paragraphs.Clear();
                _subtitle.Paragraphs.AddRange(subtitle.Paragraphs);
                _subtitleListViewIndex = -1;
                ShowSource();
                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                if (_subtitle.Paragraphs.Count > 0)
                    SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
            }

            private void RemoveTextForHearImpairedToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var removeTextFromHearImpaired = new FormRemoveTextForHearImpaired(this, _subtitle))
                {
                    removeTextFromHearImpaired.Initialize(_subtitle);
                    if (removeTextFromHearImpaired.ShowDialog(this) == DialogResult.OK)
                    {
                        int count = removeTextFromHearImpaired.TotalFixes;
                        if (count == 1)
                            ShowStatus(_language.TextingForHearingImpairedRemovedOneLine);
                        else if (count > 1)
                            ShowStatus(string.Format(_language.TextingForHearingImpairedRemovedXLines, count));
                    }
                }
            }

            private void SplitToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                double lengthInSeconds = 0;
                if (mediaPlayer.VideoPlayer != null)
                    lengthInSeconds = mediaPlayer.Duration;

                if (Configuration.Settings.Tools.SplitAdvanced)
                {
                    using (var split = new Split())
                    {
                        split.Initialize(_subtitle, _fileName, GetCurrentSubtitleFormat());
                        if (split.ShowDialog(this) == DialogResult.OK)
                        {
                            ShowStatus(_language.SubtitleSplitted);
                        }
                        else if (split.ShowBasic)
                        {
                            Configuration.Settings.Tools.SplitAdvanced = false;
                            SplitToolStripMenuItemClick(null, null);
                        }
                    }
                }
                else
                {
                    using (var splitSubtitle = new SplitSubtitle())
                    {
                        splitSubtitle.Initialize(_subtitle, _fileName, GetCurrentSubtitleFormat(), GetCurrentEncoding(), lengthInSeconds);
                        if (splitSubtitle.ShowDialog(this) == DialogResult.OK)
                        {
                            ShowStatus(_language.SubtitleSplitted);
                        }
                        else if (splitSubtitle.ShowAdvanced)
                        {
                            Configuration.Settings.Tools.SplitAdvanced = true;
                            SplitToolStripMenuItemClick(null, null);
                        }
                    }
                }
            }

            private void AppendTextVisuallyToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();

                if (MessageBox.Show(_language.SubtitleAppendPrompt, _language.SubtitleAppendPromptTitle, MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
                {
                    openFileDialog1.Title = _language.OpenSubtitleToAppend;
                    openFileDialog1.FileName = string.Empty;
                    openFileDialog1.Filter = UiUtil.SubtitleExtensionFilter.Value;
                    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                    {
                        bool success = false;
                        string fileName = openFileDialog1.FileName;
                        if (File.Exists(fileName))
                        {
                            var fileInfo = new FileInfo(fileName);
                            var subtitleToAppend = new Subtitle();
                            SubtitleFormat format = null;

                            // do not allow blu-ray/vobsub
                            string extension = Path.GetExtension(fileName).ToLowerInvariant();
                            if (extension == ".sub" && (IsVobSubFile(fileName, false) || FileUtil.IsSpDvdSup(fileName)))
                            {
                                format = null;
                            }
                            else if (extension == ".sup" && FileUtil.IsBluRaySup(fileName))
                            {
                                format = null;
                            }
                            else if (fileInfo.Length < Subtitle.MaxFileSize)
                            {
                                Encoding encoding;
                                format = subtitleToAppend.LoadSubtitle(fileName, out encoding, null);

                                if (format == null)
                                {
                                    var ebu = new Ebu();
                                    if (ebu.IsMine(null, fileName))
                                    {
                                        ebu.LoadSubtitle(subtitleToAppend, null, fileName);
                                        format = ebu;
                                    }
                                }
                                if (format == null)
                                {
                                    var pac = new Pac();
                                    if (pac.IsMine(null, fileName))
                                    {
                                        pac.LoadSubtitle(subtitleToAppend, null, fileName);
                                        format = pac;
                                    }
                                }
                                if (format == null)
                                {
                                    var cavena890 = new Cavena890();
                                    if (cavena890.IsMine(null, fileName))
                                    {
                                        cavena890.LoadSubtitle(subtitleToAppend, null, fileName);
                                        format = cavena890;
                                    }
                                }

                                if (GetCurrentSubtitleFormat().IsFrameBased)
                                    subtitleToAppend.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                                else
                                    subtitleToAppend.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                            }
                            else
                            {
                                MessageBox.Show(string.Format(_language.FileXIsLargerThan10MB, fileName));
                                return;
                            }

                            if (format != null && subtitleToAppend.Paragraphs.Count > 1)
                            {
                                using (var visualSync = new VisualSync())
                                {
                                    visualSync.Initialize(toolStripButtonVisualSync.Image as Bitmap, subtitleToAppend, null, _fileName, _language.AppendViaVisualSyncTitle, CurrentFrameRate);
                                    visualSync.ShowDialog(this);
                                    if (visualSync.OkPressed)
                                    {
                                        if (MessageBox.Show(_language.AppendSynchronizedSubtitlePrompt, _language.SubtitleAppendPromptTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            int start = _subtitle.Paragraphs.Count + 1;
                                            var fr = CurrentFrameRate;
                                            MakeHistoryForUndo(_language.BeforeAppend);
                                            foreach (var p in visualSync.Paragraphs)
                                            {
                                                if (format.IsFrameBased)
                                                    p.CalculateFrameNumbersFromTimeCodes(fr);
                                                _subtitle.Paragraphs.Add(new Paragraph(p));
                                            }
                                            if (format.GetType() == typeof(AdvancedSubStationAlpha) && GetCurrentSubtitleFormat().GetType() == typeof(AdvancedSubStationAlpha))
                                            {
                                                var currentStyles = new List<string>();
                                                if (_subtitle.Header != null)
                                                    currentStyles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header);
                                                foreach (var styleName in AdvancedSubStationAlpha.GetStylesFromHeader(subtitleToAppend.Header))
                                                {
                                                    bool alreadyExists = false;
                                                    foreach (var currentStyleName in currentStyles)
                                                    {
                                                        if (currentStyleName.Trim().Equals(styleName.Trim(), StringComparison.OrdinalIgnoreCase))
                                                            alreadyExists = true;
                                                    }
                                                    if (!alreadyExists)
                                                    {
                                                        var newStyle = AdvancedSubStationAlpha.GetSsaStyle(styleName, subtitleToAppend.Header);
                                                        _subtitle.Header = AdvancedSubStationAlpha.AddSsaStyle(newStyle, _subtitle.Header);
                                                    }
                                                }
                                            }

                                            _subtitle.Renumber();

                                            ShowSource();
                                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);

                                            // select appended lines
                                            for (int i = start; i < _subtitle.Paragraphs.Count; i++)
                                                SubtitleListview1.Items[i].Selected = true;
                                            SubtitleListview1.EnsureVisible(start);

                                            ShowStatus(string.Format(_language.SubtitleAppendedX, fileName));
                                            success = true;
                                        }
                                    }
                                }
                            }
                        }
                        if (!success)
                            ShowStatus(_language.SubtitleNotAppended);
                    }
                }
            }

            private void TranslateByGoogleToolStripMenuItemClick(object sender, EventArgs e)
            {
                TranslateViaGoogle(false, true);
            }

            private void TranslateViaGoogle(bool onlySelectedLines, bool useGoogle)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                bool isAlternateVisible = SubtitleListview1.IsAlternateTextColumnVisible;
                ReloadFromSourceView();
                using (var googleTranslate = new GoogleTranslate())
                {
                    SaveSubtitleListviewIndices();
                    string title = _language.GoogleTranslate;
                    if (!useGoogle)
                        title = _language.MicrosoftTranslate;
                    if (onlySelectedLines)
                    {
                        var selectedLines = new Subtitle { WasLoadedWithFrameNumbers = _subtitle.WasLoadedWithFrameNumbers };
                        foreach (int index in SubtitleListview1.SelectedIndices)
                            selectedLines.Paragraphs.Add(_subtitle.Paragraphs[index]);
                        title += " - " + _language.SelectedLines;
                        googleTranslate.Initialize(selectedLines, title, useGoogle, GetCurrentEncoding());
                    }
                    else
                    {
                        googleTranslate.Initialize(_subtitle, title, useGoogle, GetCurrentEncoding());
                    }
                    if (googleTranslate.ShowDialog(this) == DialogResult.OK)
                    {
                        _subtitleListViewIndex = -1;
                        string oldFileName = _fileName;
                        MakeHistoryForUndo(_language.BeforeGoogleTranslation);
                        if (onlySelectedLines)
                        {
                            // we only update selected lines
                            int i = 0;
                            foreach (int index in SubtitleListview1.SelectedIndices)
                            {
                                _subtitle.Paragraphs[index] = googleTranslate.TranslatedSubtitle.Paragraphs[i];
                                i++;
                            }
                            ShowStatus(_language.SelectedLinesTranslated);
                        }
                        else
                        {
                            _subtitleAlternate = new Subtitle(_subtitle);
                            _subtitleAlternateFileName = _fileName;
                            _fileName = null;
                            _subtitle.Paragraphs.Clear();
                            foreach (var p in googleTranslate.TranslatedSubtitle.Paragraphs)
                                _subtitle.Paragraphs.Add(new Paragraph(p));
                            ShowStatus(_language.SubtitleTranslated);
                        }
                        ShowSource();

                        if (!onlySelectedLines)
                        {
                            SubtitleListview1.ShowAlternateTextColumn(_languageGeneral.OriginalText);
                            SubtitleListview1.AutoSizeAllColumns(this);
                            SetupAlternateEdit();
                        }
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        ResetHistory();
                        RestoreSubtitleListviewIndices();
                        _fileName = googleTranslate.GetFileNameWithTargetLanguage(oldFileName, _videoFileName, _subtitleAlternate, GetCurrentSubtitleFormat());
                        _converted = true;
                        SetTitle();
                        SetEncoding(Encoding.UTF8);
                        if (!isAlternateVisible)
                        {
                            toolStripMenuItemShowOriginalInPreview.Checked = false;
                            Configuration.Settings.General.ShowOriginalAsPreviewIfAvailable = false;
                            audioVisualizer.Invalidate();
                        }
                    }
                }
            }

            private static string GetTranslateStringFromNikseDk(string input)
            {
                WebRequest.DefaultWebProxy = Utilities.GetProxy();
                //var request = WebRequest.Create("http://localhost:54942/MultiTranslator/TranslateForSubtitleEdit");
                var request = WebRequest.Create("http://www.nikse.dk/MultiTranslator/TranslateForSubtitleEdit");
                request.Method = "POST";
                var postData = String.Format("languagePair={1}&text={0}", Utilities.UrlEncode(input), "svda");
                var byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                using (var dataStream = request.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                }
                using (var response = request.GetResponse())
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }

            private void TranslateFromSwedishToDanishToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                bool isSwedish = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle) == "sv";
                string promptText = _language.TranslateSwedishToDanish;
                if (!isSwedish)
                    promptText = _language.TranslateSwedishToDanishWarning;

                if (MessageBox.Show(promptText, Title, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    try
                    {
                        _subtitleAlternate = new Subtitle(_subtitle);
                        _subtitleAlternateFileName = null;
                        int firstSelectedIndex = 0;
                        if (SubtitleListview1.SelectedItems.Count > 0)
                            firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;
                        _subtitleListViewIndex = -1;

                        Cursor.Current = Cursors.WaitCursor;
                        ShowStatus(_language.TranslatingViaNikseDkMt);
                        var sb = new StringBuilder();
                        var output = new StringBuilder();
                        foreach (var p in _subtitle.Paragraphs)
                        {
                            var s = p.Text.Replace(Environment.NewLine, "<br/>");
                            s = "<p>" + s + "</p>";
                            sb.Append(s);

                            if (sb.Length > 9000)
                            {
                                output.Append(GetTranslateStringFromNikseDk(sb.ToString()));
                                sb.Length = 0;
                            }
                        }
                        if (sb.Length > 0)
                            output.Append(GetTranslateStringFromNikseDk(sb.ToString()));

                        MakeHistoryForUndo(_language.BeforeSwedishToDanishTranslation);
                        var result = output.ToString();
                        if (result.Length > 0)
                        {
                            int index = 0;
                            foreach (var s in result.Split(new[] { "<p>", "</p>" }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                if (index < _subtitle.Paragraphs.Count)
                                    _subtitle.Paragraphs[index].Text = s;
                                index++;
                            }
                            ShowSource();
                            SubtitleListview1.ShowAlternateTextColumn(_languageGeneral.OriginalText);
                            SubtitleListview1.AutoSizeAllColumns(this);
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            ShowStatus(_language.TranslationFromSwedishToDanishComplete);
                            SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedIndex);
                            _converted = true;
                        }
                    }
                    catch
                    {
                        ShowStatus(_language.TranslationFromSwedishToDanishFailed);
                    }
                    Cursor.Current = Cursors.Default;
                }
            }

            /// <summary>
            /// Undo or Redo
            /// </summary>
            /// <param name="undo">True equals undo, false triggers redo</param>
            private void UndoToIndex(bool undo)
            {
                if (_networkSession != null)
                    return;

                lock (_syncUndo)
                {
                    if (!undo && _undoIndex >= _subtitle.HistoryItems.Count - 1)
                        return;
                    if (undo && (_subtitle == null || !_subtitle.CanUndo || _undoIndex < 0))
                        return;

                    // Add latest changes if any (also stop changes from being added while redoing/undoing)
                    timerTextUndo.Stop();
                    timerAlternateTextUndo.Stop();
                    _listViewTextTicks = 0;
                    _listViewAlternateTextTicks = 0;
                    TimerTextUndoTick(null, null);
                    TimerAlternateTextUndoTick(null, null);

                    try
                    {
                        int selectedIndex = FirstSelectedIndex;
                        if (undo)
                        {
                            _subtitle.HistoryItems[_undoIndex].RedoParagraphs = new List<Paragraph>();
                            _subtitle.HistoryItems[_undoIndex].RedoParagraphsAlternate = new List<Paragraph>();

                            foreach (var p in _subtitle.Paragraphs)
                                _subtitle.HistoryItems[_undoIndex].RedoParagraphs.Add(new Paragraph(p));
                            if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null)
                            {
                                foreach (var p in _subtitleAlternate.Paragraphs)
                                    _subtitle.HistoryItems[_undoIndex].RedoParagraphsAlternate.Add(new Paragraph(p));
                            }
                            _subtitle.HistoryItems[_undoIndex].RedoFileName = _fileName;
                            _subtitle.HistoryItems[_undoIndex].RedoFileModified = _fileDateTime;
                            _subtitle.HistoryItems[_undoIndex].RedoOriginalFileName = _subtitleAlternateFileName;

                            if (selectedIndex >= 0)
                            {
                                _subtitle.HistoryItems[_undoIndex].RedoParagraphs[selectedIndex].Text =
                                    textBoxListViewText.Text;
                                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null &&
                                    selectedIndex < _subtitle.HistoryItems[_undoIndex].RedoParagraphsAlternate.Count)
                                    _subtitle.HistoryItems[_undoIndex].RedoParagraphsAlternate[selectedIndex].Text =
                                        textBoxListViewTextAlternate.Text;
                                _subtitle.HistoryItems[_undoIndex].RedoLineIndex = selectedIndex;
                                _subtitle.HistoryItems[_undoIndex].RedoLinePosition = textBoxListViewText.SelectionStart;
                                _subtitle.HistoryItems[_undoIndex].RedoLinePositionAlternate = textBoxListViewTextAlternate.SelectionStart;
                            }
                            else
                            {
                                _subtitle.HistoryItems[_undoIndex].RedoLineIndex = -1;
                                _subtitle.HistoryItems[_undoIndex].RedoLinePosition = -1;
                            }
                        }
                        else
                        {
                            _undoIndex++;
                        }
                        var text = _subtitle.HistoryItems[_undoIndex].Description;

                        _subtitleListViewIndex = -1;
                        textBoxListViewText.Text = string.Empty;
                        textBoxListViewTextAlternate.Text = string.Empty;
                        string subtitleFormatFriendlyName;

                        string oldFileName = _fileName;
                        DateTime oldFileDateTime = _fileDateTime;

                        string oldAlternameFileName = _subtitleAlternateFileName;
                        _fileName = _subtitle.UndoHistory(_undoIndex, out subtitleFormatFriendlyName, out _fileDateTime, out _subtitleAlternate, out _subtitleAlternateFileName);
                        if (string.IsNullOrEmpty(oldAlternameFileName) && !string.IsNullOrEmpty(_subtitleAlternateFileName))
                        {
                            SubtitleListview1.ShowAlternateTextColumn(_languageGeneral.OriginalText);
                            SubtitleListview1.AutoSizeAllColumns(this);
                        }
                        else if (SubtitleListview1.IsAlternateTextColumnVisible && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count == 0)
                        {
                            RemoveAlternate(true);
                        }

                        if (!undo)
                        {
                            // TODO: Sometimes redo paragraphs can be null - how?
                            if (_subtitle.HistoryItems[_undoIndex].RedoParagraphs != null)
                            {
                                _subtitle.Paragraphs.Clear();
                                foreach (var p in _subtitle.HistoryItems[_undoIndex].RedoParagraphs)
                                    _subtitle.Paragraphs.Add(new Paragraph(p));
                                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null)
                                {
                                    _subtitleAlternate.Paragraphs.Clear();
                                    foreach (var p in _subtitle.HistoryItems[_undoIndex].RedoParagraphsAlternate)
                                        _subtitleAlternate.Paragraphs.Add(new Paragraph(p));
                                }
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("Undo failed at undo index: " + _undoIndex);
                            }
                            _subtitle.HistoryItems[_undoIndex].RedoParagraphs = null;
                            _subtitle.HistoryItems[_undoIndex].RedoParagraphsAlternate = null;
                            if (SubtitleListview1.IsAlternateTextColumnVisible && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count == 0)
                            {
                                RemoveAlternate(true);
                            }
                        }

                        if (oldFileName == null || oldFileName.Equals(_fileName, StringComparison.OrdinalIgnoreCase))
                            _fileDateTime = oldFileDateTime; // undo will not give overwrite-newer-file warning

                        comboBoxSubtitleFormats.SelectedIndexChanged -= ComboBoxSubtitleFormatsSelectedIndexChanged;
                        SetCurrentFormat(subtitleFormatFriendlyName);
                        comboBoxSubtitleFormats.SelectedIndexChanged += ComboBoxSubtitleFormatsSelectedIndexChanged;

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);

                        if (selectedIndex >= _subtitle.Paragraphs.Count)
                            SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.Paragraphs.Count - 1, true);
                        else if (selectedIndex >= 0 && selectedIndex < _subtitle.Paragraphs.Count)
                            SubtitleListview1.SelectIndexAndEnsureVisible(selectedIndex, true);
                        else
                            SubtitleListview1.SelectIndexAndEnsureVisible(0, true);

                        audioVisualizer.Invalidate();
                        if (undo)
                        {
                            if (_subtitle.HistoryItems[_undoIndex].LineIndex == FirstSelectedIndex)
                            {
                                textBoxListViewText.SelectionStart = _subtitle.HistoryItems[_undoIndex].LinePosition;
                                if (_subtitleAlternate != null)
                                    textBoxListViewTextAlternate.SelectionStart =
                                        _subtitle.HistoryItems[_undoIndex].LinePositionAlternate;
                            }
                            ShowStatus(_language.UndoPerformed + ": " + text.Replace(Environment.NewLine, "  "));
                            _undoIndex--;
                        }
                        else
                        {
                            if (_subtitle.HistoryItems[_undoIndex].RedoLineIndex >= 0 &&
                                _subtitle.HistoryItems[_undoIndex].RedoLineIndex == FirstSelectedIndex)
                                textBoxListViewText.SelectionStart = _subtitle.HistoryItems[_undoIndex].RedoLinePosition;
                            if (_subtitleAlternate != null && _subtitle.HistoryItems[_undoIndex].RedoLineIndex >= 0 &&
                                _subtitle.HistoryItems[_undoIndex].RedoLineIndex == FirstSelectedIndex)
                                textBoxListViewTextAlternate.SelectionStart =
                                    _subtitle.HistoryItems[_undoIndex].RedoLinePositionAlternate;
                            if (_subtitle.HistoryItems[_undoIndex].RedoFileName.Equals(_fileName, StringComparison.OrdinalIgnoreCase))
                                _fileDateTime = _subtitle.HistoryItems[_undoIndex].RedoFileModified;
                            _fileName = _subtitle.HistoryItems[_undoIndex].RedoFileName;
                            _subtitleAlternateFileName = _subtitle.HistoryItems[_undoIndex].RedoOriginalFileName;
                            ShowStatus(_language.UndoPerformed);
                        }
                    }
                    catch (Exception exception)
                    {
                        System.Diagnostics.Debug.WriteLine(exception.Message);
                    }

                    timerTextUndo.Start();
                    timerAlternateTextUndo.Start();
                    SetTitle();
                }
            }

            private void ShowHistoryforUndoToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (_subtitle != null && _subtitle.CanUndo)
                {
                    ReloadFromSourceView();
                    using (var showHistory = new ShowHistory())
                    {
                        showHistory.Initialize(_subtitle, _undoIndex);
                        if (showHistory.ShowDialog(this) == DialogResult.OK)
                        {
                            int selectedIndex = FirstSelectedIndex;
                            _subtitleListViewIndex = -1;
                            textBoxListViewText.Text = string.Empty;
                            textBoxListViewTextAlternate.Text = string.Empty;
                            MakeHistoryForUndo(_language.BeforeUndo);
                            string subtitleFormatFriendlyName;

                            var oldFileName = _fileName;
                            var oldFileDateTime = _fileDateTime;

                            _fileName = _subtitle.UndoHistory(showHistory.SelectedIndex, out subtitleFormatFriendlyName, out _fileDateTime, out _subtitleAlternate, out _subtitleAlternateFileName);

                            if (oldFileName == null || oldFileName.Equals(_fileName, StringComparison.OrdinalIgnoreCase))
                                _fileDateTime = oldFileDateTime; // undo will not give overwrite-newer-file warning

                            SetTitle();
                            ShowStatus(_language.UndoPerformed);

                            comboBoxSubtitleFormats.SelectedIndexChanged -= ComboBoxSubtitleFormatsSelectedIndexChanged;
                            SetCurrentFormat(subtitleFormatFriendlyName);
                            comboBoxSubtitleFormats.SelectedIndexChanged += ComboBoxSubtitleFormatsSelectedIndexChanged;

                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);

                            if (selectedIndex >= 0 && selectedIndex < _subtitle.Paragraphs.Count)
                                SubtitleListview1.SelectIndexAndEnsureVisible(selectedIndex, true);
                            else
                                SubtitleListview1.SelectIndexAndEnsureVisible(0, true);

                            audioVisualizer.Invalidate();
                        }
                    }
                }
                else
                {
                    MessageBox.Show(_language.NothingToUndo, Title, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            private void ToolStripButtonSpellCheckClick(object sender, EventArgs e)
            {
                SpellCheck(true, 0);
            }

            private void SpellCheckToolStripMenuItemClick(object sender, EventArgs e)
            {
                SpellCheck(true, 0);
            }

            private void SpellCheck(bool autoDetect, int startFromLine)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }
                try
                {
                    string dictionaryFolder = Utilities.DictionaryFolder;
                    if (!Directory.Exists(dictionaryFolder) || Directory.GetFiles(dictionaryFolder, "*.dic").Length == 0)
                    {
                        ShowGetDictionaries();
                        return;
                    }

                    if (_subtitle != null && _subtitle.Paragraphs.Count > 0)
                    {
                        if (_spellCheckForm != null)
                        {
                            var result = MessageBox.Show(_language.ContinueWithCurrentSpellCheck, Title, MessageBoxButtons.YesNoCancel);
                            if (result == DialogResult.Cancel)
                                return;

                            if (result == DialogResult.No)
                            {
                                _spellCheckForm.Dispose();
                                _spellCheckForm = new SpellCheck();
                                _spellCheckForm.DoSpellCheck(autoDetect, _subtitle, dictionaryFolder, this, startFromLine);
                            }
                            else
                            {
                                _spellCheckForm.ContinueSpellCheck(_subtitle);
                            }
                        }
                        else
                        {
                            _spellCheckForm = new SpellCheck();
                            _spellCheckForm.DoSpellCheck(autoDetect, _subtitle, dictionaryFolder, this, startFromLine);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("{0}{1}{2}{3}{4}", ex.Source, Environment.NewLine, ex.Message, Environment.NewLine, ex.StackTrace), _title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            public void ChangeWholeTextMainPart(ref int noOfChangedWords, ref bool firstChange, int i, Paragraph p)
            {
                SubtitleListview1.SetText(i, p.Text);
                noOfChangedWords++;
                if (firstChange)
                {
                    MakeHistoryForUndo(_language.BeforeSpellCheck);
                    firstChange = false;
                }
                if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                    ShowSource();
                else
                    RefreshSelectedParagraph();
            }

            public void FocusParagraph(int index)
            {
                if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                {
                    tabControlSubtitle.SelectedIndex = TabControlListView;
                }

                if (tabControlSubtitle.SelectedIndex == TabControlListView)
                {
                    SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                }
            }

            private void RefreshSelectedParagraph()
            {
                _subtitleListViewIndex = -1;
                SubtitleListview1_SelectedIndexChanged(null, null);
            }

            private int GetPositionFromWordIndex(string text, int wordIndex)
            {
                var sb = new StringBuilder();
                int index = -1;
                for (int i = 0; i < text.Length; i++)
                {
                    if (SpellCheckWordLists.SplitChars.Contains(text[i]))
                    {
                        if (sb.Length > 0)
                        {
                            index++;
                            if (index == wordIndex)
                            {
                                int pos = i - sb.Length;
                                if (pos > 0)
                                    pos--;
                                if (pos >= 0)
                                    return pos;
                            }
                        }
                        sb.Clear();
                    }
                    else
                    {
                        sb.Append(text[i]);
                    }
                }
                if (sb.Length > 0)
                {
                    index++;
                    if (index == wordIndex)
                    {
                        int pos = text.Length - 1 - sb.Length;
                        if (pos >= 0)
                            return pos;
                    }
                }
                return 0;
            }

            public void CorrectWord(string changeWord, Paragraph p, string oldWord, ref bool firstChange, int wordIndex)
            {
                if (oldWord != changeWord)
                {
                    if (firstChange)
                    {
                        MakeHistoryForUndo(_language.BeforeSpellCheck);
                        firstChange = false;
                    }

                    int startIndex = p.Text.IndexOf(oldWord, StringComparison.Ordinal);
                    if (wordIndex >= 0)
                    {
                        startIndex = p.Text.IndexOf(oldWord, GetPositionFromWordIndex(p.Text, wordIndex), StringComparison.Ordinal);
                    }
                    while (startIndex >= 0 && startIndex < p.Text.Length && p.Text.Substring(startIndex).Contains(oldWord))
                    {
                        bool startOk = startIndex == 0 ||
                                       "«»“” <>-—+/'\"[](){}¿¡….,;:!?%&$£\r\n؛،؟".Contains(p.Text[startIndex - 1]) ||
                                       startIndex == p.Text.Length - oldWord.Length;
                        if (startOk)
                        {
                            int end = startIndex + oldWord.Length;
                            if (end <= p.Text.Length && end == p.Text.Length || ("«»“” ,.!?:;'()<>\"-—+/[]{}%&$£…\r\n؛،؟").Contains(p.Text[end]))
                            {
                                p.Text = p.Text.Remove(startIndex, oldWord.Length).Insert(startIndex, changeWord);
                            }
                        }
                        if (startIndex + 2 >= p.Text.Length)
                            startIndex = -1;
                        else
                            startIndex = p.Text.IndexOf(oldWord, startIndex + 2, StringComparison.Ordinal);

                        // stop if using index
                        if (wordIndex >= 0)
                            startIndex = -1;
                    }

                    ShowStatus(string.Format(_language.SpellCheckChangedXToY, oldWord, changeWord));
                    SubtitleListview1.SetText(_subtitle.GetIndex(p), p.Text);
                    if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                    {
                        ShowSource();
                    }
                    else
                    {
                        RefreshSelectedParagraph();
                    }
                }
            }

            private void GetDictionariesToolStripMenuItem_Click(object sender, EventArgs e)
            {
                ShowGetDictionaries();
            }

            private void ShowGetDictionaries()
            {
                using (var form = new GetDictionaries())
                {
                    form.ShowDialog(this);
                }
            }

            private void ContextMenuStripListviewOpening(object sender, System.ComponentModel.CancelEventArgs e)
            {
                var format = GetCurrentSubtitleFormat();
                var formatType = format.GetType();
                var coordinates = SubtitleListview1.PointToClient(Cursor.Position);
                var hitTest = SubtitleListview1.HitTest(coordinates);
                if (coordinates.Y < 19 || (hitTest.Item != null && hitTest.Item.Index == 0 && coordinates.Y < hitTest.Item.Position.Y))
                {
                    e.Cancel = true;
                    var cm = new ContextMenuStrip();
                    var contextMenuStripLvHeaderResizeToolStripMenuItem = new ToolStripMenuItem(Configuration.Settings.Language.Main.Menu.ContextMenu.SizeAllColumnsToFit);
                    contextMenuStripLvHeaderResizeToolStripMenuItem.Click += (sender2, e2) =>
                    {
                        SubtitleListview1.AutoSizeColumns();
                    };
                    cm.Items.Add(contextMenuStripLvHeaderResizeToolStripMenuItem);

                    var tss = new ToolStripSeparator();
                    UiUtil.FixFonts(tss);
                    cm.Items.Add(tss);

                    // End time
                    var contextMenuStripLvHeaderEndTimeToolStripMenuItem = new ToolStripMenuItem(Configuration.Settings.Language.General.EndTime);
                    contextMenuStripLvHeaderEndTimeToolStripMenuItem.CheckOnClick = true;
                    contextMenuStripLvHeaderEndTimeToolStripMenuItem.Checked = Configuration.Settings.Tools.ListViewShowColumnEndTime;
                    contextMenuStripLvHeaderEndTimeToolStripMenuItem.Click += (sender2, e2) =>
                    {
                        SubtitleListview1.BeginUpdate();
                        Configuration.Settings.Tools.ListViewShowColumnEndTime = contextMenuStripLvHeaderEndTimeToolStripMenuItem.Checked;
                        if (Configuration.Settings.Tools.ListViewShowColumnEndTime)
                            SubtitleListview1.ShowEndColumn(Configuration.Settings.Language.General.EndTime);
                        else
                            SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.End);
                        SaveSubtitleListviewIndices();
                        UiUtil.InitializeSubtitleFont(SubtitleListview1);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                        SubtitleListview1.EndUpdate();
                    };
                    cm.Items.Add(contextMenuStripLvHeaderEndTimeToolStripMenuItem);

                    // Duration
                    var contextMenuStripLvHeaderDurationToolStripMenuItem = new ToolStripMenuItem(Configuration.Settings.Language.General.Duration);
                    contextMenuStripLvHeaderDurationToolStripMenuItem.CheckOnClick = true;
                    contextMenuStripLvHeaderDurationToolStripMenuItem.Checked = Configuration.Settings.Tools.ListViewShowColumnDuration;
                    contextMenuStripLvHeaderDurationToolStripMenuItem.Click += (sender2, e2) =>
                    {
                        SubtitleListview1.BeginUpdate();
                        Configuration.Settings.Tools.ListViewShowColumnDuration = contextMenuStripLvHeaderDurationToolStripMenuItem.Checked;
                        if (Configuration.Settings.Tools.ListViewShowColumnDuration)
                            SubtitleListview1.ShowDurationColumn(Configuration.Settings.Language.General.Duration);
                        else
                            SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Duration);
                        SaveSubtitleListviewIndices();
                        UiUtil.InitializeSubtitleFont(SubtitleListview1);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                        SubtitleListview1.EndUpdate();
                    };
                    cm.Items.Add(contextMenuStripLvHeaderDurationToolStripMenuItem);

                    // CPS
                    var contextMenuStripLvHeaderCpsToolStripMenuItem = new ToolStripMenuItem(Configuration.Settings.Language.General.CharsPerSec);
                    contextMenuStripLvHeaderCpsToolStripMenuItem.CheckOnClick = true;
                    contextMenuStripLvHeaderCpsToolStripMenuItem.Checked = Configuration.Settings.Tools.ListViewShowColumnCharsPerSec;
                    contextMenuStripLvHeaderCpsToolStripMenuItem.Click += (sender2, e2) =>
                    {
                        SubtitleListview1.BeginUpdate();
                        Configuration.Settings.Tools.ListViewShowColumnCharsPerSec = contextMenuStripLvHeaderCpsToolStripMenuItem.Checked;
                        if (Configuration.Settings.Tools.ListViewShowColumnCharsPerSec)
                            SubtitleListview1.ShowCharsSecColumn(Configuration.Settings.Language.General.CharsPerSec);
                        else
                            SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.CharactersPerSeconds);
                        SaveSubtitleListviewIndices();
                        UiUtil.InitializeSubtitleFont(SubtitleListview1);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                        SubtitleListview1.EndUpdate();
                    };
                    cm.Items.Add(contextMenuStripLvHeaderCpsToolStripMenuItem);

                    // WPM
                    var contextMenuStripLvHeaderWpmToolStripMenuItem = new ToolStripMenuItem(Configuration.Settings.Language.General.WordsPerMin);
                    contextMenuStripLvHeaderWpmToolStripMenuItem.CheckOnClick = true;
                    contextMenuStripLvHeaderWpmToolStripMenuItem.Checked = Configuration.Settings.Tools.ListViewShowColumnWordsPerMin;
                    contextMenuStripLvHeaderWpmToolStripMenuItem.Click += (sender2, e2) =>
                    {
                        SubtitleListview1.BeginUpdate();
                        Configuration.Settings.Tools.ListViewShowColumnWordsPerMin = contextMenuStripLvHeaderWpmToolStripMenuItem.Checked;
                        if (Configuration.Settings.Tools.ListViewShowColumnWordsPerMin)
                            SubtitleListview1.ShowWordsMinColumn(Configuration.Settings.Language.General.WordsPerMin);
                        else
                            SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.WordsPerMinute);
                        SaveSubtitleListviewIndices();
                        UiUtil.InitializeSubtitleFont(SubtitleListview1);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                        SubtitleListview1.EndUpdate();
                    };
                    cm.Items.Add(contextMenuStripLvHeaderWpmToolStripMenuItem);

                    // GAP
                    var contextMenuStripLvHeaderGapToolStripMenuItem = new ToolStripMenuItem(Configuration.Settings.Language.General.Gap);
                    contextMenuStripLvHeaderGapToolStripMenuItem.CheckOnClick = true;
                    contextMenuStripLvHeaderGapToolStripMenuItem.Checked = Configuration.Settings.Tools.ListViewShowColumnGap;
                    contextMenuStripLvHeaderGapToolStripMenuItem.Click += (sender2, e2) =>
                    {
                        SubtitleListview1.BeginUpdate();
                        Configuration.Settings.Tools.ListViewShowColumnGap = contextMenuStripLvHeaderGapToolStripMenuItem.Checked;
                        if (Configuration.Settings.Tools.ListViewShowColumnGap)
                            SubtitleListview1.ShowGapColumn(Configuration.Settings.Language.General.Gap);
                        else
                            SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Gap);
                        SaveSubtitleListviewIndices();
                        UiUtil.InitializeSubtitleFont(SubtitleListview1);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                        SubtitleListview1.EndUpdate();
                    };
                    cm.Items.Add(contextMenuStripLvHeaderGapToolStripMenuItem);

                    if (formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha) || formatType == typeof(CsvNuendo))
                    {
                        // ACTOR
                        var actorTitle = formatType == typeof(CsvNuendo) ? Configuration.Settings.Language.General.Character : Configuration.Settings.Language.General.Actor;
                        var contextMenuStripLvHeaderActorToolStripMenuItem = new ToolStripMenuItem(actorTitle);
                        contextMenuStripLvHeaderActorToolStripMenuItem.CheckOnClick = true;
                        contextMenuStripLvHeaderActorToolStripMenuItem.Checked = Configuration.Settings.Tools.ListViewShowColumnActor;
                        contextMenuStripLvHeaderActorToolStripMenuItem.Click += (sender2, e2) =>
                        {
                            SubtitleListview1.BeginUpdate();
                            Configuration.Settings.Tools.ListViewShowColumnActor = contextMenuStripLvHeaderActorToolStripMenuItem.Checked;
                            if (Configuration.Settings.Tools.ListViewShowColumnActor)
                                SubtitleListview1.ShowActorColumn(actorTitle);
                            else
                                SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Actor);
                            SaveSubtitleListviewIndices();
                            UiUtil.InitializeSubtitleFont(SubtitleListview1);
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            RestoreSubtitleListviewIndices();
                            SubtitleListview1.EndUpdate();
                        };
                        cm.Items.Add(contextMenuStripLvHeaderActorToolStripMenuItem);
                    }

                    if (formatType == typeof(TimedText10))
                    {
                        // REGION
                        var contextMenuStripLvHeaderRegionToolStripMenuItem = new ToolStripMenuItem(Configuration.Settings.Language.General.Region);
                        contextMenuStripLvHeaderRegionToolStripMenuItem.CheckOnClick = true;
                        contextMenuStripLvHeaderRegionToolStripMenuItem.Checked = Configuration.Settings.Tools.ListViewShowColumnRegion;
                        contextMenuStripLvHeaderRegionToolStripMenuItem.Click += (sender2, e2) =>
                        {
                            SubtitleListview1.BeginUpdate();
                            Configuration.Settings.Tools.ListViewShowColumnRegion = contextMenuStripLvHeaderRegionToolStripMenuItem.Checked;
                            if (Configuration.Settings.Tools.ListViewShowColumnRegion)
                                SubtitleListview1.ShowRegionColumn(Configuration.Settings.Language.General.Region);
                            else
                                SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Region);
                            SaveSubtitleListviewIndices();
                            UiUtil.InitializeSubtitleFont(SubtitleListview1);
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            RestoreSubtitleListviewIndices();
                            SubtitleListview1.EndUpdate();
                        };
                        cm.Items.Add(contextMenuStripLvHeaderRegionToolStripMenuItem);
                    }

                    cm.Show(SubtitleListview1, coordinates);
                    return;
                }

                toolStripMenuItemSetRegion.Visible = false;
                toolStripMenuItemSetLanguage.Visible = false;
                List<string> actors = null;
                if ((formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha) || formatType == typeof(CsvNuendo)) && SubtitleListview1.SelectedItems.Count > 0)
                {
                    actors = new List<string>();
                    toolStripMenuItemWebVTT.Visible = false;
                    var styles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header);
                    setStylesForSelectedLinesToolStripMenuItem.DropDownItems.Clear();
                    foreach (var style in styles)
                    {
                        setStylesForSelectedLinesToolStripMenuItem.DropDownItems.Add(style, null, tsi_Click);
                    }
                    setStylesForSelectedLinesToolStripMenuItem.Visible = styles.Count > 1;
                    toolStripMenuItemAssStyles.Visible = true;
                    if (formatType == typeof(AdvancedSubStationAlpha))
                    {
                        toolStripMenuItemAssStyles.Text = _language.Menu.ContextMenu.AdvancedSubStationAlphaStyles;
                        setStylesForSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.AdvancedSubStationAlphaSetStyle;
                    }
                    else
                    {
                        toolStripMenuItemAssStyles.Text = _language.Menu.ContextMenu.SubStationAlphaStyles;
                        setStylesForSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.SubStationAlphaSetStyle;
                    }

                    // actor
                    foreach (var p in _subtitle.Paragraphs)
                    {
                        if (!string.IsNullOrEmpty(p.Actor) && !actors.Contains(p.Actor))
                        {
                            actors.Add(p.Actor);
                        }
                        actors.Sort();
                    }
                    setActorForSelectedLinesToolStripMenuItem.DropDownItems.Clear();
                    foreach (var actor in actors)
                    {
                        setActorForSelectedLinesToolStripMenuItem.DropDownItems.Add(actor, null, actor_Click);
                    }
                    if (actors.Count > 0)
                    {
                        var tss = new ToolStripSeparator();
                        UiUtil.FixFonts(tss);
                        setActorForSelectedLinesToolStripMenuItem.DropDownItems.Add(tss);
                    }
                    setActorForSelectedLinesToolStripMenuItem.DropDownItems.Add(_language.Menu.ContextMenu.NewActor, null, SetNewActor);
                    if (actors.Count > 0)
                        setActorForSelectedLinesToolStripMenuItem.DropDownItems.Add(_language.Menu.ContextMenu.RemoveActors, null, RemoveActors);
                }
                else if (((formatType == typeof(TimedText10) && Configuration.Settings.SubtitleSettings.TimedText10ShowStyleAndLanguage) || formatType == typeof(ItunesTimedText)) && SubtitleListview1.SelectedItems.Count > 0)
                {
                    toolStripMenuItemWebVTT.Visible = false;
                    toolStripMenuItemAssStyles.Text = _language.Menu.ContextMenu.TimedTextStyles;
                    var styles = TimedText10.GetStylesFromHeader(_subtitle.Header);
                    setStylesForSelectedLinesToolStripMenuItem.DropDownItems.Clear();
                    foreach (var style in styles)
                    {
                        setStylesForSelectedLinesToolStripMenuItem.DropDownItems.Add(style, null, tsi_Click);
                    }
                    setStylesForSelectedLinesToolStripMenuItem.Visible = styles.Count >= 1;
                    toolStripMenuItemAssStyles.Visible = true;
                    setStylesForSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.TimedTextSetStyle;

                    // regions
                    if (string.IsNullOrEmpty(_subtitle.Header) || !_subtitle.Header.Contains("http://www.w3.org/ns/ttml"))
                    {
                        _subtitle.Header = new TimedText10().ToText(_subtitle, string.Empty);
                    }
                    var regions = TimedText10.GetRegionsFromHeader(_subtitle.Header);
                    toolStripMenuItemSetRegion.DropDownItems.Clear();
                    toolStripMenuItemSetRegion.Text = _language.Menu.ContextMenu.TimedTextSetRegion;
                    if (regions.Count > 0)
                    {
                        toolStripMenuItemSetRegion.Visible = true;
                        foreach (var region in regions)
                        {
                            toolStripMenuItemSetRegion.DropDownItems.Add(region, null, SetRegionClick);
                        }
                        toolStripMenuItemSetRegion.DropDownItems.Add("-");
                        var clear = new ToolStripMenuItem(Configuration.Settings.Language.DvdSubRip.Clear);
                        toolStripMenuItemSetRegion.DropDownItems.Add(clear);
                        clear.Click += (sender2, e2) =>
                        {
                            MakeHistoryForUndo("Set region: " + Configuration.Settings.Language.DvdSubRip.Clear);
                            foreach (int index in SubtitleListview1.SelectedIndices)
                            {
                                _subtitle.Paragraphs[index].Region = null;
                                SubtitleListview1.SetTimeAndText(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1));
                            }
                        };
                    }
                    else
                    {
                        toolStripMenuItemSetRegion.Visible = false;
                    }

                    // languages
                    var languages = TimedText10.GetUsedLanguages(_subtitle);
                    toolStripMenuItemSetLanguage.DropDownItems.Clear();
                    toolStripMenuItemSetLanguage.Text = _language.Menu.ContextMenu.TimedTextSetLanguage;
                    toolStripMenuItemSetLanguage.Visible = true;
                    if (languages.Count > 0)
                    {
                        foreach (var language in languages)
                        {
                            toolStripMenuItemSetLanguage.DropDownItems.Add(language, null, AddLanguageClick);
                        }
                        toolStripMenuItemSetLanguage.DropDownItems.Add("-");
                    }

                    var newItem = new ToolStripMenuItem(_language.New);
                    toolStripMenuItemSetLanguage.DropDownItems.Add(newItem);
                    newItem.Click += (senderNew, eNew) =>
                    {
                        var moreLanguages = new List<CultureInfo>();
                        foreach (CultureInfo x in CultureInfo.GetCultures(CultureTypes.NeutralCultures))
                        {
                            var twoLetterLower = x.TwoLetterISOLanguageName.ToLower();
                            if (!languages.Contains(twoLetterLower) &&
                                !languages.Contains(x.ThreeLetterISOLanguageName.ToLower()) &&
                                twoLetterLower != "iv")
                            {
                                moreLanguages.Add(x);
                            }
                        }
                        moreLanguages = moreLanguages.OrderBy(p => p.TwoLetterISOLanguageName).ToList();
                        using (var form = new TimedTextNewLanguage(moreLanguages, LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle)))
                        {
                            if (form.ShowDialog(this) == DialogResult.OK)
                            {
                                if (!string.IsNullOrEmpty(form.Language))
                                {
                                    MakeHistoryForUndo("Set language: " + form.Language);
                                    foreach (int index in SubtitleListview1.SelectedIndices)
                                    {
                                        _subtitle.Paragraphs[index].Language = form.Language;
                                        _subtitle.Paragraphs[index].Extra = TimedText10.SetExtra(_subtitle.Paragraphs[index]);
                                        SubtitleListview1.SetExtraText(index, _subtitle.Paragraphs[index].Extra, SubtitleListview1.ForeColor);
                                    }
                                }
                            }
                        }
                    };

                    if (languages.Count > 0)
                    {
                        var clearLanguage = new ToolStripMenuItem(Configuration.Settings.Language.DvdSubRip.Clear);
                        toolStripMenuItemSetLanguage.DropDownItems.Add(clearLanguage);
                        clearLanguage.Click += (sender2, e2) =>
                        {
                            MakeHistoryForUndo("Set language: " + Configuration.Settings.Language.DvdSubRip.Clear);
                            foreach (int index in SubtitleListview1.SelectedIndices)
                            {
                                _subtitle.Paragraphs[index].Language = null;
                                _subtitle.Paragraphs[index].Extra = TimedText10.SetExtra(_subtitle.Paragraphs[index]);
                                SubtitleListview1.SetTimeAndText(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1));
                            }
                        };
                    }
                }
                else if ((formatType == typeof(Sami) || formatType == typeof(SamiModern)) && SubtitleListview1.SelectedItems.Count > 0)
                {
                    toolStripMenuItemWebVTT.Visible = false;
                    toolStripMenuItemAssStyles.Text = _language.Menu.ContextMenu.TimedTextStyles;
                    var styles = Sami.GetStylesFromHeader(_subtitle.Header);
                    setStylesForSelectedLinesToolStripMenuItem.DropDownItems.Clear();
                    foreach (var style in styles)
                    {
                        setStylesForSelectedLinesToolStripMenuItem.DropDownItems.Add(style, null, tsi_Click);
                    }
                    setStylesForSelectedLinesToolStripMenuItem.Visible = styles.Count > 1;
                    toolStripMenuItemAssStyles.Visible = false;
                    setStylesForSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.SamiSetStyle;
                }
                else if ((formatType == typeof(WebVTT) && SubtitleListview1.SelectedItems.Count > 0))
                {
                    setStylesForSelectedLinesToolStripMenuItem.Visible = false;
                    toolStripMenuItemAssStyles.Visible = false;
                    toolStripMenuItemWebVTT.Visible = true;
                    var voices = WebVTT.GetVoices(_subtitle);
                    toolStripMenuItemWebVTT.DropDownItems.Clear();
                    foreach (var style in voices)
                    {
                        toolStripMenuItemWebVTT.DropDownItems.Add(style, null, WebVTTSetVoice);
                    }
                    toolStripMenuItemWebVTT.DropDownItems.Add(_language.Menu.ContextMenu.WebVTTSetNewVoice, null, WebVTTSetNewVoice);
                    if (voices.Count > 0)
                        toolStripMenuItemWebVTT.DropDownItems.Add(_language.Menu.ContextMenu.WebVTTRemoveVoices, null, WebVTTRemoveVoices);
                }
                else if ((format.Name == "Nuendo" && SubtitleListview1.SelectedItems.Count > 0))
                {
                    toolStripMenuItemWebVTT.Visible = false;
                    var styles = GetNuendoStyles();
                    setStylesForSelectedLinesToolStripMenuItem.DropDownItems.Clear();
                    foreach (var style in styles)
                    {
                        setStylesForSelectedLinesToolStripMenuItem.DropDownItems.Add(style, null, NuendoSetStyle);
                    }
                    setStylesForSelectedLinesToolStripMenuItem.Visible = styles.Count > 1;
                    toolStripMenuItemAssStyles.Visible = false;
                    setStylesForSelectedLinesToolStripMenuItem.Text = _language.Menu.ContextMenu.NuendoSetStyle;
                }
                else
                {
                    setStylesForSelectedLinesToolStripMenuItem.Visible = false;
                    toolStripMenuItemAssStyles.Visible = false;
                    toolStripMenuItemWebVTT.Visible = false;
                }

                if (actors != null)
                {
                    setActorForSelectedLinesToolStripMenuItem.Visible = true;
                }
                else
                {
                    setActorForSelectedLinesToolStripMenuItem.Visible = false;
                }

                toolStripMenuItemGoogleMicrosoftTranslateSelLine.Visible = false;
                if (SubtitleListview1.SelectedItems.Count == 0)
                {
                    contextMenuStripEmpty.Show(MousePosition.X, MousePosition.Y);
                    e.Cancel = true;
                }
                else
                {
                    bool noNetWorkSession = _networkSession == null;

                    toolStripMenuItemSaveSelectedLines.Visible = false;
                    toolStripMenuItemInsertBefore.Visible = true;
                    toolStripMenuItemInsertAfter.Visible = true;
                    toolStripMenuItemInsertSubtitle.Visible = noNetWorkSession;
                    toolStripMenuItemMergeLines.Visible = true;
                    mergeAfterToolStripMenuItem.Visible = true;
                    mergeBeforeToolStripMenuItem.Visible = true;
                    splitLineToolStripMenuItem.Visible = true;
                    toolStripSeparator7.Visible = true;
                    typeEffectToolStripMenuItem.Visible = noNetWorkSession;
                    karokeeEffectToolStripMenuItem.Visible = noNetWorkSession;
                    toolStripSeparatorAdvancedFunctions.Visible = noNetWorkSession;
                    //fixCommonErrorsInSelectedLinesToolStripMenuItem.Visible = true;
                    adjustDisplayTimeForSelectedLinesToolStripMenuItem.Visible = true;
                    //showSelectedLinesEarlierlaterToolStripMenuItem.Visible = true;
                    visualSyncSelectedLinesToolStripMenuItem.Visible = true;
                    //googleTranslateSelectedLinesToolStripMenuItem.Visible = true;
                    toolStripMenuItemGoogleMicrosoftTranslateSelLine.Visible = false;
                    toolStripMenuItemUnbreakLines.Visible = true;
                    toolStripMenuItemAutoBreakLines.Visible = true;
                    toolStripSeparatorBreakLines.Visible = true;
                    toolStripMenuItemSurroundWithMusicSymbols.Visible = IsUnicode;

                    if (SubtitleListview1.SelectedItems.Count == 1)
                    {
                        toolStripMenuItemMergeLines.Visible = false;
                        visualSyncSelectedLinesToolStripMenuItem.Visible = false;
                        toolStripMenuItemUnbreakLines.Visible = false;
                        toolStripMenuItemAutoBreakLines.Visible = false;
                        toolStripSeparatorBreakLines.Visible = false;
                        if (_subtitleAlternate != null && noNetWorkSession)
                            toolStripMenuItemGoogleMicrosoftTranslateSelLine.Visible = true;
                        toolStripMenuItemMergeDialog.Visible = false;
                    }
                    else if (SubtitleListview1.SelectedItems.Count == 2)
                    {
                        toolStripMenuItemInsertBefore.Visible = false;
                        toolStripMenuItemInsertAfter.Visible = false;
                        toolStripMenuItemInsertSubtitle.Visible = false;
                        mergeAfterToolStripMenuItem.Visible = false;
                        mergeBeforeToolStripMenuItem.Visible = false;
                        splitLineToolStripMenuItem.Visible = false;
                        typeEffectToolStripMenuItem.Visible = false;
                        toolStripMenuItemMergeDialog.Visible = true;
                    }
                    else if (SubtitleListview1.SelectedItems.Count >= 2)
                    {
                        toolStripMenuItemSaveSelectedLines.Visible = true;
                        toolStripMenuItemInsertBefore.Visible = false;
                        toolStripMenuItemInsertAfter.Visible = false;
                        toolStripMenuItemInsertSubtitle.Visible = false;
                        splitLineToolStripMenuItem.Visible = false;
                        mergeAfterToolStripMenuItem.Visible = false;
                        mergeBeforeToolStripMenuItem.Visible = false;
                        typeEffectToolStripMenuItem.Visible = false;
                        toolStripSeparator7.Visible = false;

                        if (SubtitleListview1.SelectedItems.Count > 25)
                        {
                            toolStripMenuItemMergeLines.Visible = false;
                        }
                        else if (SubtitleListview1.SelectedItems.Count > 2)
                        { // only allow merge if text is not way too long
                            try
                            {
                                int totalLength = 0;
                                foreach (int index in SubtitleListview1.SelectedIndices)
                                {
                                    totalLength += _subtitle.Paragraphs[index].Text.Length;
                                }
                                if (totalLength > Configuration.Settings.General.SubtitleLineMaximumLength * 2.5)
                                {
                                    toolStripMenuItemMergeLines.Visible = false;
                                }
                            }
                            catch
                            {
                            }
                        }

                        toolStripMenuItemMergeDialog.Visible = false;
                    }

                    if (formatType != typeof(SubRip))
                    {
                        karokeeEffectToolStripMenuItem.Visible = false;
                        toolStripSeparatorAdvancedFunctions.Visible = SubtitleListview1.SelectedItems.Count == 1 && noNetWorkSession;
                    }
                }
                toolStripMenuItemPasteSpecial.Visible = Clipboard.ContainsText();
            }

            private void tsi_Click(object sender, EventArgs e)
            {
                string style = (sender as ToolStripItem).Text;
                if (!string.IsNullOrEmpty(style))
                {
                    MakeHistoryForUndo("Set style: " + style);

                    var format = GetCurrentSubtitleFormat();
                    var formatType = format.GetType();
                    if ((formatType == typeof(TimedText10) || formatType == typeof(ItunesTimedText)))
                    {
                        foreach (int index in SubtitleListview1.SelectedIndices)
                        {
                            _subtitle.Paragraphs[index].Style = style;
                            _subtitle.Paragraphs[index].Extra = TimedText10.SetExtra(_subtitle.Paragraphs[index]);
                            SubtitleListview1.SetExtraText(index, _subtitle.Paragraphs[index].Extra, SubtitleListview1.ForeColor);
                        }
                    }
                    else
                    {
                        foreach (int index in SubtitleListview1.SelectedIndices)
                        {
                            _subtitle.Paragraphs[index].Extra = style;
                            SubtitleListview1.SetExtraText(index, style, SubtitleListview1.ForeColor);
                        }
                    }
                }
            }

            private void actor_Click(object sender, EventArgs e)
            {
                string actor = (sender as ToolStripItem).Text;
                if (!string.IsNullOrEmpty(actor))
                {
                    MakeHistoryForUndo(Configuration.Settings.Language.Main.Menu.ContextMenu.SetActor + ": " + actor);

                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        _subtitle.Paragraphs[index].Actor = actor;
                        SubtitleListview1.SetTimeAndText(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1));
                    }
                }
            }

            private void SetRegionClick(object sender, EventArgs e)
            {
                string region = (sender as ToolStripItem).Text;
                if (!string.IsNullOrEmpty(region))
                {
                    MakeHistoryForUndo("Set region: " + region);
                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        _subtitle.Paragraphs[index].Region = region;
                        SubtitleListview1.SetTimeAndText(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1));
                    }
                }
            }

            private void AddLanguageClick(object sender, EventArgs e)
            {
                string lang = (sender as ToolStripItem).Text;
                if (!string.IsNullOrEmpty(lang))
                {
                    MakeHistoryForUndo("Set language: " + lang);
                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        _subtitle.Paragraphs[index].Language = lang;
                        _subtitle.Paragraphs[index].Extra = TimedText10.SetExtra(_subtitle.Paragraphs[index]);
                        SubtitleListview1.SetExtraText(index, _subtitle.Paragraphs[index].Extra, SubtitleListview1.ForeColor);
                    }
                }
            }

            private void NuendoSetStyle(object sender, EventArgs e)
            {
                string style = (sender as ToolStripItem).Text;
                if (!string.IsNullOrEmpty(style))
                {
                    int indexOfComment = style.IndexOf('[');
                    if (indexOfComment > 0)
                        style = style.Substring(0, indexOfComment).Trim();
                    MakeHistoryForUndo("Set style: " + style);
                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        _subtitle.Paragraphs[index].Extra = style;
                        _subtitle.Paragraphs[index].Actor = style;
                        SubtitleListview1.SetExtraText(index, style, SubtitleListview1.ForeColor);
                    }
                }
            }

            private void WebVTTSetVoice(object sender, EventArgs e)
            {
                string voice = (sender as ToolStripItem).Text;
                if (!string.IsNullOrEmpty(voice))
                {
                    MakeHistoryForUndo("Set voice: " + voice);
                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        _subtitle.Paragraphs[index].Text = WebVTT.RemoveTag("v", _subtitle.Paragraphs[index].Text);
                        _subtitle.Paragraphs[index].Text = string.Format("<v {0}>{1}", voice, _subtitle.Paragraphs[index].Text);
                        SubtitleListview1.SetText(index, _subtitle.Paragraphs[index].Text);
                    }
                    RefreshSelectedParagraph();
                }
            }

            private void WebVTTSetNewVoice(object sender, EventArgs e)
            {
                using (var form = new TextPrompt(Configuration.Settings.Language.WebVttNewVoice.Title, Configuration.Settings.Language.WebVttNewVoice.VoiceName))
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        string voice = form.InputText;
                        if (!string.IsNullOrEmpty(voice))
                        {
                            foreach (int index in SubtitleListview1.SelectedIndices)
                            {
                                _subtitle.Paragraphs[index].Text = WebVTT.RemoveTag("v", _subtitle.Paragraphs[index].Text);
                                _subtitle.Paragraphs[index].Text = string.Format("<v {0}>{1}", voice, _subtitle.Paragraphs[index].Text);
                                SubtitleListview1.SetText(index, _subtitle.Paragraphs[index].Text);
                            }
                            RefreshSelectedParagraph();
                        }
                    }
                }
            }
            private void SetNewActor(object sender, EventArgs e)
            {
                using (var form = new TextPrompt(Configuration.Settings.Language.Main.Menu.ContextMenu.NewActor.Replace("...", string.Empty), Configuration.Settings.Language.General.Actor))
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        string actor = form.InputText;
                        if (!string.IsNullOrEmpty(actor))
                        {
                            foreach (int index in SubtitleListview1.SelectedIndices)
                            {
                                _subtitle.Paragraphs[index].Actor = actor;
                                SubtitleListview1.SetTimeAndText(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1));
                            }
                        }
                    }
                }
            }

            private void WebVTTRemoveVoices(object sender, EventArgs e)
            {
                foreach (int index in SubtitleListview1.SelectedIndices)
                {
                    _subtitle.Paragraphs[index].Text = WebVTT.RemoveTag("v", _subtitle.Paragraphs[index].Text);
                    SubtitleListview1.SetText(index, _subtitle.Paragraphs[index].Text);
                }
                RefreshSelectedParagraph();
            }

            private void RemoveActors(object sender, EventArgs e)
            {
                foreach (int index in SubtitleListview1.SelectedIndices)
                {
                    _subtitle.Paragraphs[index].Actor = null;
                    SubtitleListview1.SetTimeAndText(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1));
                }
            }

            private void WebVTTSetVoiceTextBox(object sender, EventArgs e)
            {
                string voice = (sender as ToolStripItem).Text;
                if (!string.IsNullOrEmpty(voice))
                {
                    var tb = GetFocusedTextBox();

                    if (tb.SelectionLength > 0)
                    {
                        string s = tb.SelectedText;
                        s = WebVTT.RemoveTag("v", s);
                        if (tb.SelectedText == tb.Text)
                            s = string.Format("<v {0}>{1}", voice, s);
                        else
                            s = string.Format("<v {0}>{1}</v>", voice, s);
                        tb.SelectedText = s;
                    }
                }
            }

            private void WebVTTSetNewVoiceTextBox(object sender, EventArgs e)
            {
                using (var form = new TextPrompt(Configuration.Settings.Language.WebVttNewVoice.Title, Configuration.Settings.Language.WebVttNewVoice.VoiceName))
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        string voice = form.InputText;
                        if (!string.IsNullOrEmpty(voice))
                        {
                            var tb = GetFocusedTextBox();

                            if (tb.SelectionLength > 0)
                            {
                                string s = tb.SelectedText;
                                s = WebVTT.RemoveTag("v", s);
                                if (tb.SelectedText == tb.Text)
                                    s = string.Format("<v {0}>{1}", voice, s);
                                else
                                    s = string.Format("<v {0}>{1}</v>", voice, s);
                                tb.SelectedText = s;
                            }
                        }
                    }
                }
            }

            private void BoldToolStripMenuItemClick(object sender, EventArgs e)
            {
                ListViewToggleTag(HtmlUtil.TagBold);
            }

            private void ItalicToolStripMenuItemClick(object sender, EventArgs e)
            {
                ListViewToggleTag(HtmlUtil.TagItalic);
            }

            private void UnderlineToolStripMenuItemClick(object sender, EventArgs e)
            {
                ListViewToggleTag(HtmlUtil.TagUnderline);
            }

            private void ListViewToggleTag(string tag)
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                    MakeHistoryForUndo(string.Format(_language.BeforeAddingTagX, tag));

                    var indices = new List<int>();
                    foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                        indices.Add(item.Index);

                    SubtitleListview1.BeginUpdate();
                    foreach (int i in indices)
                    {
                        var p = _subtitle.GetParagraphOrDefault(i);
                        if (p != null)
                        {
                            if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                            {
                                var original = Utilities.GetOriginalParagraph(i, p, _subtitleAlternate.Paragraphs);
                                if (original != null)
                                {
                                    original.Text = HtmlUtil.ToggleTag(original.Text, tag);
                                    SubtitleListview1.SetAlternateText(i, original.Text);
                                }
                            }
                            p.Text = HtmlUtil.ToggleTag(p.Text, tag);
                            SubtitleListview1.SetText(i, p.Text);
                        }
                    }
                    SubtitleListview1.EndUpdate();

                    ShowStatus(string.Format(_language.TagXAdded, tag));
                    ShowSource();
                    RefreshSelectedParagraph();
                    SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                }
            }

            private void ToolStripMenuItemDeleteClick(object sender, EventArgs e)
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    string statusText;
                    string historyText;
                    string askText;

                    if (SubtitleListview1.SelectedItems.Count > 1)
                    {
                        statusText = string.Format(_language.XLinesDeleted, SubtitleListview1.SelectedItems.Count);
                        historyText = string.Format(_language.BeforeDeletingXLines, SubtitleListview1.SelectedItems.Count);
                        askText = string.Format(_language.DeleteXLinesPrompt, SubtitleListview1.SelectedItems.Count);
                    }
                    else
                    {
                        statusText = _language.OneLineDeleted;
                        historyText = _language.BeforeDeletingOneLine;
                        askText = _language.DeleteOneLinePrompt;
                    }

                    if (Configuration.Settings.General.PromptDeleteLines && MessageBox.Show(askText, Title, MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        _cutText = string.Empty;
                        return;
                    }

                    if (!string.IsNullOrEmpty(_cutText))
                    {
                        Clipboard.SetText(_cutText);
                        _cutText = string.Empty;
                    }

                    MakeHistoryForUndo(historyText);
                    DeleteSelectedLines();

                    ShowStatus(statusText);
                    ShowSource();
                }
            }

            private void DeleteSelectedLines()
            {
                _subtitleListViewIndex = -1;

                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    var alternateIndices = new List<int>();
                    foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                    {
                        var p = _subtitle.GetParagraphOrDefault(item.Index);
                        if (p != null)
                        {
                            var original = Utilities.GetOriginalParagraph(item.Index, p, _subtitleAlternate.Paragraphs);
                            if (original != null)
                                alternateIndices.Add(_subtitleAlternate.GetIndex(original));
                        }
                    }

                    alternateIndices.Reverse();
                    foreach (int i in alternateIndices)
                    {
                        if (i < _subtitleAlternate.Paragraphs.Count)
                            _subtitleAlternate.Paragraphs.RemoveAt(i);
                    }
                    _subtitleAlternate.Renumber();
                }

                var indices = new List<int>();
                foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                    indices.Add(item.Index);
                int firstIndex = SubtitleListview1.SelectedItems[0].Index;

                if (_networkSession != null)
                {
                    _networkSession.TimerStop();
                    NetworkGetSendUpdates(indices, 0, null);
                }
                else
                {
                    indices.Reverse();
                    foreach (int i in indices)
                    {
                        _subtitle.Paragraphs.RemoveAt(i);
                        if (_networkSession != null && _networkSession.LastSubtitle != null && i < _networkSession.LastSubtitle.Paragraphs.Count)
                            _networkSession.LastSubtitle.Paragraphs.RemoveAt(i);
                    }
                    _subtitle.Renumber();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    if (SubtitleListview1.FirstVisibleIndex == 0)
                        SubtitleListview1.FirstVisibleIndex = -1;
                    if (SubtitleListview1.Items.Count > firstIndex)
                    {
                        SubtitleListview1.SelectIndexAndEnsureVisible(firstIndex, true);
                    }
                    else if (SubtitleListview1.Items.Count > 0)
                    {
                        SubtitleListview1.SelectIndexAndEnsureVisible(SubtitleListview1.Items.Count - 1, true);
                    }
                }
            }

            private void ToolStripMenuItemInsertBeforeClick(object sender, EventArgs e)
            {
                if (_subtitle.Paragraphs.Count > 0)
                    InsertBefore();
                textBoxListViewText.Focus();
            }

            private void InsertBefore()
            {
                var format = GetCurrentSubtitleFormat();
                bool useExtraForStyle = format.HasStyleSupport;
                var styles = new List<string>();
                if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha))
                    styles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header);
                else if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText))
                    styles = TimedText10.GetStylesFromHeader(_subtitle.Header);
                else if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern))
                    styles = Sami.GetStylesFromHeader(_subtitle.Header);
                string style = "Default";
                if (styles.Count > 0)
                    style = styles[0];

                MakeHistoryForUndo(_language.BeforeInsertLine);

                int firstSelectedIndex = 0;
                if (SubtitleListview1.SelectedItems.Count > 0)
                    firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;

                int addMilliseconds = Configuration.Settings.General.MinimumMillisecondsBetweenLines + 1;
                if (addMilliseconds < 1)
                    addMilliseconds = 1;

                var newParagraph = new Paragraph();
                if (useExtraForStyle)
                {
                    newParagraph.Extra = style;
                    if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText))
                    {
                        if (styles.Count > 0)
                            newParagraph.Style = style;
                        var c = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                        if (c != null)
                        {
                            newParagraph.Style = c.Style;
                            newParagraph.Region = c.Region;
                            newParagraph.Language = c.Language;
                        }
                        newParagraph.Extra = TimedText10.SetExtra(newParagraph);
                    }
                }

                var prev = _subtitle.GetParagraphOrDefault(firstSelectedIndex - 1);
                var next = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                if (prev != null && next != null)
                {
                    newParagraph.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - addMilliseconds;
                    newParagraph.StartTime.TotalMilliseconds = newParagraph.EndTime.TotalMilliseconds - 2000;
                    if (newParagraph.StartTime.TotalMilliseconds <= prev.EndTime.TotalMilliseconds)
                        newParagraph.StartTime.TotalMilliseconds = prev.EndTime.TotalMilliseconds + 1;
                    if (newParagraph.Duration.TotalMilliseconds < 100)
                        newParagraph.EndTime.TotalMilliseconds += 100;
                }
                else if (prev != null)
                {
                    newParagraph.StartTime.TotalMilliseconds = prev.EndTime.TotalMilliseconds + addMilliseconds;
                    newParagraph.EndTime.TotalMilliseconds = newParagraph.StartTime.TotalMilliseconds + Configuration.Settings.General.NewEmptyDefaultMs;
                    if (newParagraph.StartTime.TotalMilliseconds > newParagraph.EndTime.TotalMilliseconds)
                        newParagraph.StartTime.TotalMilliseconds = prev.EndTime.TotalMilliseconds + 1;
                }
                else if (next != null)
                {
                    newParagraph.StartTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 2000;
                    newParagraph.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 1;
                }
                else
                {
                    newParagraph.StartTime.TotalMilliseconds = 1000;
                    newParagraph.EndTime.TotalMilliseconds = 3000;
                }
                if (GetCurrentSubtitleFormat().IsFrameBased)
                {
                    newParagraph.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                    newParagraph.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                }

                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    var currentOriginal = Utilities.GetOriginalParagraph(firstSelectedIndex, _subtitle.Paragraphs[firstSelectedIndex], _subtitleAlternate.Paragraphs);
                    if (currentOriginal != null)
                    {
                        _subtitleAlternate.Paragraphs.Insert(_subtitleAlternate.Paragraphs.IndexOf(currentOriginal), new Paragraph(newParagraph));
                    }
                    else
                    {
                        _subtitleAlternate.InsertParagraphInCorrectTimeOrder(new Paragraph(newParagraph));
                    }
                    _subtitleAlternate.Renumber();
                }

                if (_networkSession != null)
                {
                    _networkSession.TimerStop();
                    NetworkGetSendUpdates(new List<int>(), firstSelectedIndex, newParagraph);
                }
                else
                {
                    _subtitle.Paragraphs.Insert(firstSelectedIndex, newParagraph);
                    _subtitleListViewIndex = -1;
                    _subtitle.Renumber();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                }
                SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedIndex, true);
                ShowSource();
                ShowStatus(_language.LineInserted);
            }

            private void ToolStripMenuItemInsertAfterClick(object sender, EventArgs e)
            {
                if (_subtitle.Paragraphs.Count > 0)
                {
                    InsertAfter();
                    textBoxListViewText.Focus();
                }
            }

            private void InsertAfter()
            {
                var format = GetCurrentSubtitleFormat();
                bool useExtraForStyle = format.HasStyleSupport;
                var formatType = format.GetType();
                var styles = new List<string>();
                if (formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha))
                    styles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header);
                else if (formatType == typeof(TimedText10) || formatType == typeof(ItunesTimedText))
                    styles = TimedText10.GetStylesFromHeader(_subtitle.Header);
                else if (formatType == typeof(Sami) || formatType == typeof(SamiModern))
                    styles = Sami.GetStylesFromHeader(_subtitle.Header);
                string style = "Default";
                if (styles.Count > 0)
                    style = styles[0];

                MakeHistoryForUndo(_language.BeforeInsertLine);

                int firstSelectedIndex = 0;
                if (SubtitleListview1.SelectedItems.Count > 0)
                    firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index + 1;

                var newParagraph = new Paragraph();
                if (useExtraForStyle)
                {
                    newParagraph.Extra = style;
                    if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText))
                    {
                        if (styles.Count > 0)
                            newParagraph.Style = style;
                        var c = _subtitle.GetParagraphOrDefault(FirstSelectedIndex);
                        if (c != null)
                        {
                            newParagraph.Style = c.Style;
                            newParagraph.Region = c.Region;
                            newParagraph.Language = c.Language;
                        }
                        newParagraph.Extra = TimedText10.SetExtra(newParagraph);
                    }
                }

                var prev = _subtitle.GetParagraphOrDefault(firstSelectedIndex - 1);
                var next = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                if (prev != null)
                {
                    int addMilliseconds = Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                    if (addMilliseconds < 1)
                        addMilliseconds = 1;

                    newParagraph.StartTime.TotalMilliseconds = prev.EndTime.TotalMilliseconds + addMilliseconds;
                    newParagraph.EndTime.TotalMilliseconds = newParagraph.StartTime.TotalMilliseconds + Configuration.Settings.General.NewEmptyDefaultMs;
                    if (next != null && newParagraph.EndTime.TotalMilliseconds > next.StartTime.TotalMilliseconds)
                        newParagraph.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 1;
                    if (newParagraph.StartTime.TotalMilliseconds > newParagraph.EndTime.TotalMilliseconds)
                        newParagraph.StartTime.TotalMilliseconds = prev.EndTime.TotalMilliseconds + 1;
                }
                else if (next != null)
                {
                    newParagraph.StartTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 2000;
                    newParagraph.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 1;
                }
                else
                {
                    newParagraph.StartTime.TotalMilliseconds = 1000;
                    newParagraph.EndTime.TotalMilliseconds = 3000;
                }
                if (GetCurrentSubtitleFormat().IsFrameBased)
                {
                    newParagraph.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                    newParagraph.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                }

                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    var currentOriginal = Utilities.GetOriginalParagraph(firstSelectedIndex - 1, _subtitle.Paragraphs[firstSelectedIndex - 1], _subtitleAlternate.Paragraphs);
                    if (currentOriginal != null)
                    {
                        _subtitleAlternate.Paragraphs.Insert(_subtitleAlternate.Paragraphs.IndexOf(currentOriginal) + 1, new Paragraph(newParagraph));
                    }
                    else
                    {
                        _subtitleAlternate.InsertParagraphInCorrectTimeOrder(new Paragraph(newParagraph));
                    }
                    _subtitleAlternate.Renumber();
                }

                if (_networkSession != null)
                {
                    _networkSession.TimerStop();
                    NetworkGetSendUpdates(new List<int>(), firstSelectedIndex, newParagraph);
                }
                else
                {
                    _subtitle.Paragraphs.Insert(firstSelectedIndex, newParagraph);
                    _subtitle.Renumber();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                }
                SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedIndex, true);
                ShowSource();
                ShowStatus(_language.LineInserted);
            }

            private void SubtitleListView1SelectedIndexChange()
            {
                StopAutoDuration();
                ShowLineInformationListView();
                if (_subtitle.Paragraphs.Count > 0)
                {
                    int firstSelectedIndex = 0;
                    if (SubtitleListview1.SelectedItems.Count > 0)
                        firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;

                    if (_subtitleListViewIndex >= 0)
                    {
                        if (_subtitleListViewIndex == firstSelectedIndex)
                            return;

                        bool showSource = false;

                        var last = _subtitle.GetParagraphOrDefault(_subtitleListViewIndex);
                        if (textBoxListViewText.Text != last.Text)
                        {
                            last.Text = textBoxListViewText.Text.TrimEnd();
                            SubtitleListview1.SetText(_subtitleListViewIndex, last.Text);
                            showSource = true;
                        }

                        var startTime = timeUpDownStartTime.TimeCode;
                        if (startTime != null)
                        {
                            if (Math.Abs(last.StartTime.TotalMilliseconds - startTime.TotalMilliseconds) > 0.5)
                            {
                                var dur = last.Duration.TotalMilliseconds;
                                last.StartTime.TotalMilliseconds = startTime.TotalMilliseconds;
                                last.EndTime.TotalMilliseconds = startTime.TotalMilliseconds + dur;
                                SubtitleListview1.SetStartTimeAndDuration(_subtitleListViewIndex, last, _subtitle.GetParagraphOrDefault(_subtitleListViewIndex + 1), _subtitle.GetParagraphOrDefault(_subtitleListViewIndex - 1));
                                showSource = true;
                            }
                        }

                        var duration = GetDurationInMilliseconds();
                        if (duration > 0 && duration < 100000 && Math.Abs(duration - last.Duration.TotalMilliseconds) > 0.5)
                        {
                            last.EndTime.TotalMilliseconds = last.StartTime.TotalMilliseconds + duration;
                            SubtitleListview1.SetDuration(_subtitleListViewIndex, last, _subtitle.GetParagraphOrDefault(_subtitleListViewIndex + 1));
                            showSource = true;
                        }

                        if (showSource)
                        {
                            ShowSource();
                        }
                    }

                    var p = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                    if (p != null)
                    {
                        InitializeListViewEditBox(p);
                        _subtitleListViewIndex = firstSelectedIndex;
                        _oldSelectedParagraph = new Paragraph(p);
                        UpdateListViewTextInfo(labelTextLineLengths, labelSingleLine, labelTextLineTotal, labelCharactersPerSecond, p, textBoxListViewText);

                        if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                        {
                            InitializeListViewEditBoxAlternate(p, firstSelectedIndex);
                            labelAlternateCharactersPerSecond.Left = textBoxListViewTextAlternate.Left + (textBoxListViewTextAlternate.Width - labelAlternateCharactersPerSecond.Width);
                            labelTextAlternateLineTotal.Left = textBoxListViewTextAlternate.Left + (textBoxListViewTextAlternate.Width - labelTextAlternateLineTotal.Width);
                        }
                    }
                }
            }

            private void SubtitleListview1_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (!_makeHistoryPaused)
                {
                    if (_listViewTextUndoLast != null && _listViewTextUndoIndex >= 0 && _subtitle.Paragraphs.Count > _listViewTextUndoIndex &&
                        _subtitle.Paragraphs[_listViewTextUndoIndex].Text.TrimEnd() != _listViewTextUndoLast.TrimEnd())
                    {
                        MakeHistoryForUndo(_languageGeneral.Text + ": " + _listViewTextUndoLast.TrimEnd() + " -> " + _subtitle.Paragraphs[_listViewTextUndoIndex].Text.TrimEnd(), false);
                        _subtitle.HistoryItems[_subtitle.HistoryItems.Count - 1].Subtitle.Paragraphs[_listViewTextUndoIndex].Text = _listViewTextUndoLast;
                        if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null)
                        {
                            var original = Utilities.GetOriginalParagraph(_listViewTextUndoIndex, _subtitle.Paragraphs[_listViewTextUndoIndex], _subtitleAlternate.Paragraphs);
                            var idx = _subtitleAlternate.GetIndex(original);
                            if (idx >= 0)
                                _subtitle.HistoryItems[_subtitle.HistoryItems.Count - 1].OriginalSubtitle.Paragraphs[idx].Text = _listViewAlternateTextUndoLast;
                        }
                    }
                    else if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _listViewAlternateTextUndoLast != null &&
                            _subtitle.Paragraphs.Count > _listViewTextUndoIndex && _listViewTextUndoIndex >= 0)
                    {
                        var original = Utilities.GetOriginalParagraph(_listViewTextUndoIndex, _subtitle.Paragraphs[_listViewTextUndoIndex], _subtitleAlternate.Paragraphs);
                        if (original != null && original.Text.TrimEnd() != _listViewAlternateTextUndoLast.TrimEnd())
                        {
                            var idx = _subtitleAlternate.GetIndex(original);
                            if (idx >= 0)
                            {
                                MakeHistoryForUndo(_languageGeneral.Text + ": " + _listViewAlternateTextUndoLast.TrimEnd() + " -> " + original.Text.TrimEnd(), false);
                                _subtitle.HistoryItems[_subtitle.HistoryItems.Count - 1].OriginalSubtitle.Paragraphs[idx].Text = _listViewAlternateTextUndoLast;
                            }
                        }
                    }
                }

                _listViewTextUndoIndex = -1;
                SubtitleListView1SelectedIndexChange();
            }

            private void ShowLineInformationListView()
            {
                if (tabControlSubtitle.SelectedIndex == TabControlListView)
                {
                    if (SubtitleListview1.SelectedItems.Count == 1)
                        toolStripSelected.Text = string.Format("{0}/{1}", SubtitleListview1.SelectedItems[0].Index + 1, SubtitleListview1.Items.Count);
                    else
                        toolStripSelected.Text = string.Format(_language.XLinesSelected, SubtitleListview1.SelectedItems.Count);
                }
            }

            private void UpdateListViewTextCharactersPerSeconds(Label charsPerSecond, Paragraph paragraph)
            {
                if (paragraph.Duration.TotalSeconds > 0)
                {
                    double charactersPerSecond = Utilities.GetCharactersPerSecond(paragraph);
                    if (charactersPerSecond > Configuration.Settings.General.SubtitleMaximumCharactersPerSeconds)
                        charsPerSecond.ForeColor = Color.Red;
                    else
                        charsPerSecond.ForeColor = Color.Black;
                    charsPerSecond.Text = string.Format(_language.CharactersPerSecond, charactersPerSecond);
                }
                else
                {
                    charsPerSecond.ForeColor = Color.Red;
                    charsPerSecond.Text = string.Format(_language.CharactersPerSecond, _languageGeneral.NotAvailable);
                }
            }

            private void UpdateListViewTextInfo(Label lineLengths, Label singleLine, Label lineTotal, Label charactersPerSecond, Paragraph paragraph, TextBox textBox)
            {
                if (paragraph == null)
                    return;
                bool textBoxHasFocus = textBox.Focused;
                string text = paragraph.Text;
                lineLengths.Text = _languageGeneral.SingleLineLengths.Trim();
                singleLine.Left = lineLengths.Left + lineLengths.Width - 3;
                text = HtmlUtil.RemoveHtmlTags(text, true);
                UiUtil.GetLineLengths(singleLine, text);

                buttonSplitLine.Visible = false;

                // remove unicode control characters
                var s = text.RemoveControlCharacters(); // incl. new line

                int numberOfLines = Utilities.GetNumberOfLines(text.Trim());
                int maxLines = int.MaxValue;
                if (Configuration.Settings.Tools.ListViewSyntaxMoreThanXLines)
                    maxLines = Configuration.Settings.Tools.ListViewSyntaxMoreThanXLinesX;
                var splitLines = text.SplitToLines();
                if (numberOfLines <= maxLines)
                {
                    if (s.Length <= Configuration.Settings.General.SubtitleLineMaximumLength * Math.Max(numberOfLines, 2) &&
                        splitLines.Count == 2 && splitLines[0].StartsWith('-') && splitLines[1].StartsWith('-') &&
                        (splitLines[0].Length > Configuration.Settings.General.SubtitleLineMaximumLength || splitLines[1].Length > Configuration.Settings.General.SubtitleLineMaximumLength))
                    {
                        if (buttonUnBreak.Visible)
                        {
                            if (!textBoxHasFocus)
                                lineTotal.Text = string.Format(_languageGeneral.TotalLengthX, s.Length);
                            buttonSplitLine.Visible = true;
                        }
                    }
                    else if (s.Length <= Configuration.Settings.General.SubtitleLineMaximumLength * Math.Max(numberOfLines, 2))
                    {
                        lineTotal.ForeColor = Color.Black;
                        if (!textBoxHasFocus)
                            lineTotal.Text = string.Format(_languageGeneral.TotalLengthX, s.Length);
                    }
                    else
                    {
                        lineTotal.ForeColor = Color.Red;
                        if (!textBoxHasFocus)
                            lineTotal.Text = string.Format(_languageGeneral.TotalLengthXSplitLine, s.Length);
                        if (buttonUnBreak.Visible)
                        {
                            if (!textBoxHasFocus)
                                lineTotal.Text = string.Format(_languageGeneral.TotalLengthX, s.Length);
                            buttonSplitLine.Visible = true;
                        }
                    }
                }
                UpdateListViewTextCharactersPerSeconds(charactersPerSecond, paragraph);
                charactersPerSecond.Left = textBox.Left + (textBox.Width - labelCharactersPerSecond.Width);
                lineTotal.Left = textBox.Left + (textBox.Width - lineTotal.Width);
                FixVerticalScrollBars(textBox);
            }

            private void ButtonNextClick(object sender, EventArgs e)
            {
                MoveNextPrevious(0);
            }

            private void ButtonPreviousClick(object sender, EventArgs e)
            {
                MoveNextPrevious(1);
            }

            private void MoveNextPrevious(int firstSelectedIndex)
            {
                if (_subtitle.Paragraphs.Count == 0)
                    return;
                var temp = firstSelectedIndex;
                if (SubtitleListview1.SelectedItems.Count > 0)
                    firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;
                firstSelectedIndex = temp == 0 ? firstSelectedIndex + 1 : firstSelectedIndex - 1;
                var p = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                if (p != null)
                    SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedIndex, true);
            }

            private void NormalToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    MakeHistoryForUndo(_language.BeforeSettingFontToNormal);
                    var subFormatName = GetCurrentSubtitleFormat().Name;
                    foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                    {
                        var p = _subtitle.GetParagraphOrDefault(item.Index);
                        if (p != null)
                        {
                            // Remove music symbols.
                            p.Text = p.Text.Replace("♪", string.Empty);
                            p.Text = p.Text.Replace("♫", string.Empty);
                            p.Text = HtmlUtil.RemoveHtmlTags(p.Text, true).Trim();
                            SubtitleListview1.SetText(item.Index, p.Text);

                            if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                            {
                                var original = Utilities.GetOriginalParagraph(item.Index, p, _subtitleAlternate.Paragraphs);
                                if (original != null)
                                {
                                    original.Text = original.Text.Replace("♪", string.Empty);
                                    original.Text = original.Text.Replace("♫", string.Empty);
                                    original.Text = HtmlUtil.RemoveHtmlTags(original.Text, true).Trim();
                                    SubtitleListview1.SetAlternateText(item.Index, original.Text);
                                }
                            }
                        }
                    }
                    ShowSource();
                    RefreshSelectedParagraph();
                }
            }

            private void ButtonAutoBreakClick(object sender, EventArgs e)
            {
                string language = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle);
                string languageOriginal = string.Empty;
                if (_subtitleAlternate != null)
                    languageOriginal = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitleAlternate);

                var textCaretPos = textBoxListViewText.SelectionStart;

                if (SubtitleListview1.SelectedItems.Count > 1)
                {
                    MakeHistoryForUndo(_language.Controls.AutoBreak);
                    SubtitleListview1.BeginUpdate();
                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        var p = _subtitle.GetParagraphOrDefault(index);
                        if (p != null)
                        {
                            p.Text = Utilities.AutoBreakLine(p.Text, language);
                            SubtitleListview1.SetText(index, p.Text);

                            if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                            {
                                var original = Utilities.GetOriginalParagraph(index, p, _subtitleAlternate.Paragraphs);
                                if (original != null)
                                {
                                    original.Text = Utilities.AutoBreakLine(original.Text, languageOriginal);
                                    SubtitleListview1.SetAlternateText(index, original.Text);
                                }
                            }
                            SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, index, p);
                        }
                    }
                    SubtitleListview1.EndUpdate();
                    RefreshSelectedParagraph();
                }
                else
                {
                    var fixedText = Utilities.AutoBreakLine(textBoxListViewText.Text, language);
                    var makeHistory = textBoxListViewText.Text != fixedText;
                    if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                    {
                        var alternateFixedText = Utilities.AutoBreakLine(textBoxListViewTextAlternate.Text, languageOriginal);
                        if (!makeHistory)
                            makeHistory = textBoxListViewTextAlternate.Text != alternateFixedText;
                        if (makeHistory)
                        {
                            MakeHistoryForUndo(_language.Controls.AutoBreak.RemoveChar('&'));
                            textBoxListViewText.Text = fixedText;
                        }
                        textBoxListViewTextAlternate.Text = alternateFixedText;
                    }
                    else if (makeHistory)
                    {
                        MakeHistoryForUndo(_language.Controls.AutoBreak.RemoveChar('&'));
                        textBoxListViewText.Text = fixedText;
                    }
                }
                var s = textBoxListViewText.Text;
                var startText = s.Substring(0, Math.Min(textCaretPos, s.Length));
                var numberOfNewLines = Utilities.CountTagInText(startText, Environment.NewLine);
                textCaretPos += numberOfNewLines;
                if (s.Length > textCaretPos && '\n' == s[textCaretPos])
                    textCaretPos--;
                if (textCaretPos > 0)
                    textBoxListViewText.SelectionStart = textCaretPos;
            }

            private static void FixVerticalScrollBars(TextBox tb)
            {
                if (Utilities.GetNumberOfLines(tb.Text) > 3)
                    tb.ScrollBars = ScrollBars.Vertical;
                else
                    tb.ScrollBars = ScrollBars.None;
            }

            private void TextBoxListViewTextTextChanged(object sender, EventArgs e)
            {
                if (_subtitleListViewIndex >= 0)
                {
                    if (_doAutoBreakOnTextChanged)
                        UiUtil.CheckAutoWrap(textBoxListViewText, new KeyEventArgs(Keys.None), Utilities.GetNumberOfLines(textBoxListViewText.Text));

                    // update _subtitle + listview
                    string text = textBoxListViewText.Text.TrimEnd();
                    if (ContainsNonStandardNewLines(text))
                    {
                        var lines = text.SplitToLines();
                        text = string.Join(Environment.NewLine, lines);
                        textBoxListViewText.Text = text;
                    }
                    _subtitle.Paragraphs[_subtitleListViewIndex].Text = text;
                    UpdateListViewTextInfo(labelTextLineLengths, labelSingleLine, labelTextLineTotal, labelCharactersPerSecond, _subtitle.Paragraphs[_subtitleListViewIndex], textBoxListViewText);
                    SubtitleListview1.SetText(_subtitleListViewIndex, text);

                    _listViewTextUndoIndex = _subtitleListViewIndex;
                    labelStatus.Text = string.Empty;

                    StartUpdateListSyntaxColoring();
                    FixVerticalScrollBars(textBoxListViewText);
                }
            }

            private bool ContainsNonStandardNewLines(string s)
            {
                if (Environment.NewLine == "\r\n")
                {
                    int i = 0;
                    while (i < s.Length)
                    {
                        var ch = s[i];
                        if (ch == '\r')
                        {
                            if (i >= s.Length - 1 || s[i + 1] != '\n')
                                return true;
                            i++;
                        }
                        else if (ch == '\n')
                        {
                            return true;
                        }
                        i++;
                    }
                    return false;
                }
                else if (Environment.NewLine == "\n")
                {
                    return s.Contains('\r');
                }
                else
                {
                    s = s.Replace(Environment.NewLine, string.Empty);
                    return s.Contains('\n') || s.Contains('\r');
                }
            }

            private void TextBoxListViewTextAlternateTextChanged(object sender, EventArgs e)
            {
                if (_subtitleListViewIndex >= 0)
                {
                    var p = _subtitle.GetParagraphOrDefault(_subtitleListViewIndex);
                    if (p == null)
                        return;

                    var original = Utilities.GetOriginalParagraph(_subtitleListViewIndex, p, _subtitleAlternate.Paragraphs);
                    if (original != null)
                    {
                        int numberOfNewLines = Utilities.GetNumberOfLines(textBoxListViewTextAlternate.Text);
                        UiUtil.CheckAutoWrap(textBoxListViewTextAlternate, new KeyEventArgs(Keys.None), numberOfNewLines);

                        // update _subtitle + listview
                        string text = textBoxListViewTextAlternate.Text.TrimEnd();
                        if (ContainsNonStandardNewLines(text))
                        {
                            var lines = text.SplitToLines();
                            text = string.Join(Environment.NewLine, lines);
                            textBoxListViewTextAlternate.Text = text;
                        }
                        original.Text = text;
                        UpdateListViewTextInfo(labelTextAlternateLineLengths, labelAlternateSingleLine, labelTextAlternateLineTotal, labelAlternateCharactersPerSecond, original, textBoxListViewTextAlternate);
                        SubtitleListview1.SetAlternateText(_subtitleListViewIndex, text);
                        _listViewTextUndoIndex = _subtitleListViewIndex;
                    }
                    labelStatus.Text = string.Empty;

                    StartUpdateListSyntaxColoring();
                    FixVerticalScrollBars(textBoxListViewTextAlternate);
                }
            }

            private void TextBoxListViewTextKeyDown(object sender, KeyEventArgs e)
            {
                _listViewTextTicks = DateTime.UtcNow.Ticks;

                if (e.Modifiers == Keys.Shift && e.KeyCode == Keys.ShiftKey)
                    return;
                if (e.Modifiers == Keys.Control && e.KeyCode == (Keys.LButton | Keys.ShiftKey))
                { // surround ctrl+v action with history (for undo)
                    _listViewTextTicks = 0;
                    TimerTextUndoTick(sender, e);
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(50);
                    Application.DoEvents();
                    _listViewTextTicks = 0;
                    TimerTextUndoTick(sender, e);
                    return;
                }

                int numberOfLines = Utilities.GetNumberOfLines(textBoxListViewText.Text);

                //Utilities.CheckAutoWrap(textBoxListViewText, e, numberOfNewLines);

                if (e.Modifiers == Keys.None && e.KeyCode == Keys.Enter && numberOfLines > Configuration.Settings.Tools.ListViewSyntaxMoreThanXLinesX)
                {
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _mainTextBoxAutoBreak)
                {
                    ButtonAutoBreakClick(null, null);
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _mainTextBoxUnbreak)
                {
                    ButtonUnBreakClick(null, null);
                    e.SuppressKeyPress = true;
                }
                else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.I)
                {
                    if (textBoxListViewText.SelectionLength == 0)
                    {
                        if (textBoxListViewText.Text.Contains("<i>", StringComparison.Ordinal))
                        {
                            textBoxListViewText.Text = HtmlUtil.RemoveOpenCloseTags(textBoxListViewText.Text, HtmlUtil.TagItalic);
                        }
                        else
                        {
                            textBoxListViewText.Text = string.Format("<i>{0}</i>", textBoxListViewText.Text);
                        }
                    }
                    else
                    {
                        TextBoxListViewToggleTag(HtmlUtil.TagItalic);
                    }
                }
                if (e.Modifiers == Keys.Control && e.KeyCode == Keys.D)
                {
                    textBoxListViewText.SelectionLength = 0;
                    e.SuppressKeyPress = true;
                }
                else if (_mainTextBoxSplitAtCursor == e.KeyData)
                {
                    ToolStripMenuItemSplitTextAtCursorClick(null, null);
                    e.SuppressKeyPress = true;
                }
                else if (_mainTextBoxSplitAtCursorAndVideoPos == e.KeyData)
                {
                    toolStripMenuItemSplitViaWaveform_Click(null, null);
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _mainTextBoxInsertAfter)
                {
                    InsertAfter();
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _mainListViewGoToNextError)
                {
                    GoToNextSynaxError();
                    e.SuppressKeyPress = true;
                }
                else if (_mainTextBoxSelectionToLower == e.KeyData && textBoxListViewText.SelectionLength > 0) // selection to lowercase
                {
                    int start = textBoxListViewText.SelectionStart;
                    int length = textBoxListViewText.SelectionLength;
                    textBoxListViewText.SelectedText = textBoxListViewText.SelectedText.ToLower();
                    textBoxListViewText.SelectionStart = start;
                    textBoxListViewText.SelectionLength = length;
                    e.SuppressKeyPress = true;
                }
                else if (_mainTextBoxSelectionToUpper == e.KeyData && textBoxListViewText.SelectionLength > 0) // selection to uppercase
                {
                    int start = textBoxListViewText.SelectionStart;
                    int length = textBoxListViewText.SelectionLength;
                    textBoxListViewText.SelectedText = textBoxListViewText.SelectedText.ToUpper();
                    textBoxListViewText.SelectionStart = start;
                    textBoxListViewText.SelectionLength = length;
                    e.SuppressKeyPress = true;
                }
                else if (_mainTextBoxToggleAutoDuration == e.KeyData) // toggle auto-duration
                {
                    if (timerAutoDuration.Enabled)
                    {
                        timerAutoDuration.Stop();
                        labelAutoDuration.Visible = false;
                    }
                    else
                    {
                        timerAutoDuration.Start();
                        labelAutoDuration.Visible = true;
                    }
                    e.SuppressKeyPress = true;
                }

                // last key down in text
                _lastTextKeyDownTicks = DateTime.UtcNow.Ticks;

                UpdatePositionAndTotalLength(labelTextLineTotal, textBoxListViewText);
            }

            private void MoveFirstWordInNextUp()
            {
                int firstIndex = FirstSelectedIndex;
                if (firstIndex >= 0)
                {
                    var p = _subtitle.GetParagraphOrDefault(firstIndex);
                    var next = _subtitle.GetParagraphOrDefault(firstIndex + 1);
                    if (p != null && next != null)
                    {
                        string s = next.Text.Trim();
                        // Find the first space.
                        int idx = s.IndexOf(' ');
                        // If the first space is after a "-", even if there is "{\an8}<i>" before, find the second space.
                        if (idx > 0 && s.Substring(idx - 1, 2) == "- ")
                            idx = idx + 1 + s.Substring(idx + 1).IndexOf(' ');

                        if (idx > 0 || s.Length > 0)
                        // A first word was found or next subtitle is not empty (has one word).
                        {
                            // Undo
                            MakeHistoryForUndo(_language.BeforeLineUpdatedInListView);

                            // Define firstWord. If idx > 0, there is a first word.
                            // If not, firstWord is the whole text of the next subtitle.
                            string firstWord = (idx > 0 ? s.Substring(0, idx).Trim() : next.Text);

                            // If firstWord contains a line break, it has two words.
                            if (firstWord.Contains(Environment.NewLine))
                            {
                                // Redefine firstWord and idx.
                                firstWord = firstWord.Remove(firstWord.IndexOf(Environment.NewLine, StringComparison.Ordinal));
                                idx = s.IndexOf(Environment.NewLine, StringComparison.Ordinal);
                            }

                            // Remove first word from the next subtitle.
                            // If there is only one word, 'next' will be empty.
                            next.Text = (idx > 0 ? s.Substring(idx + 1).Trim() : string.Empty);

                            // If the first subtitle ends with a tag (</i>):
                            String endTag = string.Empty;
                            if (p.Text.EndsWith('>') && p.Text.Contains('<'))
                            {
                                // Save the end tag.
                                endTag = p.Text.Substring(p.Text.LastIndexOf('<'), p.Text.Length - p.Text.LastIndexOf('<'));
                                // Remove the endTag from first subtitle.
                                p.Text = p.Text.Remove(p.Text.LastIndexOf('<'));
                            }

                            // If the first subtitle ends with "...":
                            Boolean firstSubtitleEndsWithEllipsis = p.Text.EndsWith("...", StringComparison.Ordinal);
                            if (firstSubtitleEndsWithEllipsis)
                            {
                                // Remove "..." from first subtitle.
                                p.Text = p.Text.TrimEnd('.');
                            }

                            // If the second subtitle (next) starts with a position tag, like {\an8}:
                            String positionTag = string.Empty;
                            if (firstWord.StartsWith('{') && firstWord.Contains('}'))
                            {
                                // Save the start tag.
                                positionTag = firstWord.Substring(firstWord.IndexOf('{'), firstWord.IndexOf('}') + 1);
                                // Remove the position tag from the first word.
                                firstWord = firstWord.Remove(0, firstWord.IndexOf('}') + 1);
                            }

                            // If the second subtitle (next) starts with a tag:
                            String startTag = string.Empty;
                            if (firstWord.StartsWith('<') && firstWord.Contains('>'))
                            {
                                // Save the start tag.
                                startTag = firstWord.Substring(firstWord.IndexOf('<'), firstWord.IndexOf('>') + 1);
                                // Remove the start tag from the first word.
                                firstWord = firstWord.Remove(0, firstWord.IndexOf('>') + 1);
                            }

                            // If the second subtitle ends with a tag and there's only one word in it:
                            if (next.Text.EndsWith('>') && next.Text.Contains('<') && !next.Text.Contains(' '))
                            {
                                // Remove the end tag.
                                next.Text = next.Text.Remove(next.Text.LastIndexOf('<'));
                            }

                            // If the second subtitle (next) starts with a dialog ("-"):
                            String dialogMarker = string.Empty;
                            if (firstWord.StartsWith('-'))
                            {
                                // Save the dialog marker ("-" or "- ").
                                dialogMarker = (firstWord.StartsWith("- ", StringComparison.Ordinal) ? "- " : "-");
                                // Remove the dialog marker from the first word.
                                firstWord = firstWord.Remove(0, dialogMarker.Length);
                            }

                            // If the second subtitle starts with "...":
                            Boolean nextSubtitleStartsWithEllipsis = firstWord.StartsWith("...", StringComparison.Ordinal);
                            if (nextSubtitleStartsWithEllipsis)
                            {
                                // Remove "..." from the beginning of first word.
                                firstWord = firstWord.TrimStart('.');
                            }

                            // Add positionTag + startTag + dialogMarker + "..." + text to 'next'.
                            if (idx > 0)
                                next.Text = positionTag + startTag + dialogMarker + (nextSubtitleStartsWithEllipsis ? "..." : string.Empty) + next.Text.Trim();

                            // Add text + firstWord + "..." + endTag to First line.
                            p.Text = (idx == 0 ? startTag : string.Empty) + p.Text.Trim() + " " + firstWord.Trim() + (idx > 0 && firstSubtitleEndsWithEllipsis ? "..." : string.Empty) + endTag;

                            // Now, idx will hold the position of the last line break, if any.
                            idx = p.Text.LastIndexOf(Environment.NewLine, StringComparison.Ordinal);

                            // Check if the last line of the subtitle (the one that now contains the moved word) is longer than SubtitleLineMaximumLength.
                            if (HtmlUtil.RemoveHtmlTags(p.Text.Substring((idx > 0 ? idx + Environment.NewLine.Length : 0))).Length > Configuration.Settings.General.SubtitleLineMaximumLength)
                                p.Text = Utilities.AutoBreakLine(p.Text);
                        }

                        SubtitleListview1.SetText(firstIndex, p.Text);
                        SubtitleListview1.SetText(firstIndex + 1, next.Text);
                        textBoxListViewText.Text = p.Text;
                    }
                }
            }

            private void MoveLastWordDown()
            {
                int firstIndex = FirstSelectedIndex;
                if (firstIndex >= 0)
                {
                    var p = _subtitle.GetParagraphOrDefault(firstIndex);
                    var next = _subtitle.GetParagraphOrDefault(firstIndex + 1);
                    if (p != null && next != null)
                    {
                        string s = p.Text.Trim();
                        int idx = s.LastIndexOf(' ');
                        if (idx > 0 || s.Length > 0)
                        // A last word was found or the first subtitle is not empty (has one word).
                        {
                            // Undo
                            MakeHistoryForUndo(_language.BeforeLineUpdatedInListView);

                            // Define lastWord. If idx > 0, there is a last word.
                            // If not, lastWord is the whole text of the first subtitle.
                            string lastWord = (idx > 0 ? s.Substring(idx).Trim() : p.Text);

                            // If lastWord contains a line break, it has two words.
                            if (lastWord.Contains(Environment.NewLine))
                            {
                                // Redefine lastWord and idx.
                                lastWord = lastWord.Substring(lastWord.LastIndexOf(Environment.NewLine, StringComparison.Ordinal));
                                idx = s.LastIndexOf(Environment.NewLine, StringComparison.Ordinal);
                            }

                            // Remove last word from the first subtitle.
                            p.Text = (idx > 0 ? s.Substring(0, idx).Trim() : string.Empty);

                            // If the first subtitle ends with a tag (</i>):
                            string endTag = string.Empty;
                            if (lastWord.EndsWith('>') && lastWord.Contains('<'))
                            {
                                // Save the end tag.
                                endTag = lastWord.Substring(lastWord.LastIndexOf('<'), lastWord.Length - lastWord.LastIndexOf('<'));
                                // Remove the end tag from the last word.
                                lastWord = lastWord.Remove(lastWord.LastIndexOf('<'));
                            }

                            // If the first subtitle ends with "...":
                            bool firstSubtitleEndsWithEllipsis = lastWord.EndsWith("...", StringComparison.Ordinal);
                            if (firstSubtitleEndsWithEllipsis)
                            {
                                // Remove "..." from the last word.
                                lastWord = lastWord.TrimEnd('.');
                            }

                            // If the second subtitle (next) starts with a position tag, like {\an8}:
                            string positionTag = string.Empty;
                            if (next.Text.StartsWith('{') && next.Text.Contains('}'))
                            {
                                // Save the start tag.
                                positionTag = next.Text.Substring(next.Text.IndexOf('{'), next.Text.IndexOf('}') + 1);
                                // Remove the position tag from next subtitle.
                                next.Text = next.Text.Remove(0, next.Text.IndexOf('}') + 1);
                            }

                            // If the second subtitle (next) starts with a tag:
                            string startTag = string.Empty;
                            if (next.Text.StartsWith('<') && next.Text.Contains('>'))
                            {
                                // Save the start tag.
                                startTag = next.Text.Substring(next.Text.IndexOf('<'), next.Text.IndexOf('>') + 1);
                                // Remove the start tag from next subtitle.
                                next.Text = next.Text.Remove(0, next.Text.IndexOf('>') + 1);
                            }

                            // If the second subtitle (next) starts with a dialog ("-"):
                            string dialogMarker = string.Empty;
                            if (next.Text.StartsWith('-'))
                            {
                                // Save the dialog marker ("-" or "- ").
                                dialogMarker = (next.Text.StartsWith("- ", StringComparison.Ordinal) ? "- " : "-");
                                // Remove the dialog marker from the next subtitle.
                                next.Text = next.Text.Remove(0, dialogMarker.Length);
                            }

                            // If the second subtitle starts with "...":
                            bool nextSubtitleStartsWithEllipsis = next.Text.StartsWith("...", StringComparison.Ordinal);
                            if (nextSubtitleStartsWithEllipsis)
                            {
                                // Remove "..." from the beginning of 'next'.
                                next.Text = next.Text.TrimStart('.');
                            }

                            // Add text + "..." + endTag to first subtitle.
                            if (idx > 0)
                                p.Text = p.Text + (firstSubtitleEndsWithEllipsis ? "..." : string.Empty) + endTag;

                            // Add positionTag + startTag + dialogMarker + "..." + lastWord to 'next'.
                            next.Text = (idx > 0 ? positionTag : string.Empty) +
                                        (idx > 0 ? startTag : string.Empty) + dialogMarker +
                                        (nextSubtitleStartsWithEllipsis && idx > 0 ? "..." : string.Empty) +
                                        lastWord.Trim() + " " + next.Text.Trim();

                            // Now, idx will hold the position of the first line break, if any.
                            idx = next.Text.IndexOf(Environment.NewLine, StringComparison.Ordinal);

                            // Check if the first line of the next subtitle (the one that now contains the moved word) is longer than SubtitleLineMaximumLength.
                            if (HtmlUtil.RemoveHtmlTags(next.Text.Substring(0, (idx > 0 ? idx : next.Text.Length))).Length > Configuration.Settings.General.SubtitleLineMaximumLength)
                                next.Text = Utilities.AutoBreakLine(next.Text);
                        }

                        SubtitleListview1.SetText(firstIndex, p.Text);
                        SubtitleListview1.SetText(firstIndex + 1, next.Text);
                        textBoxListViewText.Text = p.Text;
                    }
                }
            }

            private void MakeAutoDurationSelectedLines()
            {
                if (_subtitle.Paragraphs.Count == 0)
                    return;

                if (SubtitleListview1.SelectedItems.Count == 1)
                {
                    MakeAutoDuration();
                    return;
                }

                if (SubtitleListview1.SelectedItems.Count > 1)
                {
                    MakeHistoryForUndo(_language.BeforeAutoDuration);
                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        var p = _subtitle.GetParagraphOrDefault(index);
                        if (p == null)
                            return;

                        double duration = Utilities.GetOptimalDisplayMilliseconds(textBoxListViewText.Text);
                        var next = _subtitle.GetParagraphOrDefault(index + 1);
                        if (next != null && p.StartTime.TotalMilliseconds + duration + Configuration.Settings.General.MinimumMillisecondsBetweenLines > next.StartTime.TotalMilliseconds)
                        {
                            duration = next.StartTime.TotalMilliseconds - p.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                        }
                        if (duration > 500)
                        {
                            p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + duration;
                        }
                    }
                    SaveSubtitleListviewIndices();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    RestoreSubtitleListviewIndices();
                    RefreshSelectedParagraph();
                }
            }

            private void MakeAutoDuration()
            {
                int i = _subtitleListViewIndex;
                var p = _subtitle.GetParagraphOrDefault(i);
                if (p == null)
                    return;

                double duration = Utilities.GetOptimalDisplayMilliseconds(textBoxListViewText.Text);
                var next = _subtitle.GetParagraphOrDefault(i + 1);
                if (next != null && p.StartTime.TotalMilliseconds + duration + Configuration.Settings.General.MinimumMillisecondsBetweenLines > next.StartTime.TotalMilliseconds)
                {
                    duration = next.StartTime.TotalMilliseconds - p.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                    if (duration < 400)
                        return;
                }
                SetDurationInSeconds(duration / TimeCode.BaseUnit);

                p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + duration;
                SubtitleListview1.SetDuration(i, p, _subtitle.GetParagraphOrDefault(i + 1));
            }

            private void SplitLineToolStripMenuItemClick(object sender, EventArgs e)
            {
                SplitSelectedParagraph(null, null);
            }

            private void SplitSelectedParagraph(double? splitSeconds, int? textIndex)
            {
                string language = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle);

                int? alternateTextIndex = null;
                if (textBoxListViewTextAlternate.Focused)
                {
                    alternateTextIndex = textIndex;
                    textIndex = null;
                }

                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                    MakeHistoryForUndo(_language.BeforeSplitLine);

                    int firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;

                    var currentParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                    var newParagraph = new Paragraph(currentParagraph);
                    newParagraph.NewSection = false;

                    currentParagraph.Text = currentParagraph.Text.Replace("< /i>", "</i>");
                    currentParagraph.Text = currentParagraph.Text.Replace("< i>", "<i>");
                    string oldText = currentParagraph.Text;
                    var lines = currentParagraph.Text.SplitToLines();
                    if (textIndex != null && textIndex.Value > 2 && textIndex.Value < oldText.Length - 2)
                    {
                        string a = oldText.Substring(0, textIndex.Value).Trim();
                        string b = oldText.Substring(textIndex.Value).Trim();
                        string aTrimmed = a.TrimEnd('"').TrimEnd().TrimEnd('\'').TrimEnd();
                        string bTrimmed = b.TrimEnd('"').TrimEnd().TrimEnd('\'').TrimEnd();
                        if (oldText.TrimStart().StartsWith("<i>", StringComparison.Ordinal) && oldText.TrimEnd().EndsWith("</i>", StringComparison.Ordinal) &&
                            Utilities.CountTagInText(oldText, "<i>") == 1 && Utilities.CountTagInText(oldText, "</i>") == 1)
                        {
                            a = a + "</i>";
                            b = "<i>" + b;
                        }
                        else if (oldText.TrimStart().StartsWith("<b>", StringComparison.Ordinal) && oldText.TrimEnd().EndsWith("</b>", StringComparison.Ordinal) &&
                            Utilities.CountTagInText(oldText, "<b>") == 1 && Utilities.CountTagInText(oldText, "</b>") == 1)
                        {
                            a = a + "</b>";
                            b = "<b>" + b;
                        }
                        else if (a.StartsWith('-') && (aTrimmed.EndsWith('.') || aTrimmed.EndsWith('!') || aTrimmed.EndsWith('?')) &&
                            b.StartsWith('-') && (bTrimmed.EndsWith('.') || bTrimmed.EndsWith('!') || bTrimmed.EndsWith('?')))
                        {
                            a = a.TrimStart('-').TrimStart();
                            b = b.TrimStart('-').TrimStart();
                        }
                        else if (a.StartsWith("<i>-", StringComparison.Ordinal) && (aTrimmed.EndsWith(".</i>", StringComparison.Ordinal) || aTrimmed.EndsWith("!</i>", StringComparison.Ordinal) || aTrimmed.EndsWith("?</i>", StringComparison.Ordinal)) &&
                            b.StartsWith("<i>-", StringComparison.Ordinal) && (bTrimmed.EndsWith(".</i>", StringComparison.Ordinal) || bTrimmed.EndsWith("!</i>", StringComparison.Ordinal) || bTrimmed.EndsWith("?</i>", StringComparison.Ordinal)))
                        {
                            a = a.Remove(3, 1).Replace("  ", " ");
                            b = b.Remove(3, 1).Replace("  ", " ");
                        }
                        else if (a.StartsWith('-') && (aTrimmed.EndsWith('.') || aTrimmed.EndsWith('!') || aTrimmed.EndsWith('?')) &&
                            b.StartsWith("<i>-", StringComparison.Ordinal) && (bTrimmed.EndsWith(".</i>", StringComparison.Ordinal) || bTrimmed.EndsWith("!</i>", StringComparison.Ordinal) || bTrimmed.EndsWith("?</i>", StringComparison.Ordinal)))
                        {
                            a = a.TrimStart('-').TrimStart();
                            b = b.Remove(3, 1).Replace("  ", " ").Trim();
                        }
                        else if (a.StartsWith("<i>-", StringComparison.Ordinal) && (aTrimmed.EndsWith(".</i>", StringComparison.Ordinal) || aTrimmed.EndsWith("!</i>", StringComparison.Ordinal) || aTrimmed.EndsWith("?</i>", StringComparison.Ordinal)) &&
                            b.StartsWith('-') && (bTrimmed.EndsWith('.') || bTrimmed.EndsWith('!') || bTrimmed.EndsWith('?')))
                        {
                            a = a.Remove(3, 1).Replace("  ", " ").Trim();
                            b = b.TrimStart('-').TrimStart();
                        }

                        currentParagraph.Text = Utilities.AutoBreakLine(a, language);
                        newParagraph.Text = Utilities.AutoBreakLine(b, language);
                    }
                    else
                    {
                        var l0 = string.Empty;
                        if (lines.Count > 0)
                            l0 = lines[0].Trim().TrimEnd('"', '\'').TrimEnd();
                        if (lines.Count == 2 && (l0.EndsWith('.') || l0.EndsWith('!') || l0.EndsWith('?')))
                        {
                            currentParagraph.Text = Utilities.AutoBreakLine(lines[0], language);
                            newParagraph.Text = Utilities.AutoBreakLine(lines[1], language);
                            if (lines[0].Length > 2 && lines[0][0] == '-' && lines[0][1] != '-' &&
                                lines[1].Length > 2 && lines[1][0] == '-' && lines[1][1] != '-')
                            {
                                currentParagraph.Text = currentParagraph.Text.TrimStart('-').Trim();
                                newParagraph.Text = newParagraph.Text.TrimStart('-').Trim();
                            }
                            if (currentParagraph.Text.StartsWith("<i>", StringComparison.Ordinal) && !currentParagraph.Text.Contains("</i>") &&
                               newParagraph.Text.EndsWith("</i>", StringComparison.Ordinal) && !newParagraph.Text.Contains("<i>"))
                            {
                                currentParagraph.Text = currentParagraph.Text + "</i>";
                                newParagraph.Text = "<i>" + newParagraph.Text;
                            }
                            if (currentParagraph.Text.StartsWith("<b>", StringComparison.Ordinal) && !currentParagraph.Text.Contains("</b>") &&
                               newParagraph.Text.EndsWith("</b>", StringComparison.Ordinal) && !newParagraph.Text.Contains("<b>"))
                            {
                                currentParagraph.Text = currentParagraph.Text + "</b>";
                                newParagraph.Text = "<b>" + newParagraph.Text;
                            }
                            if (currentParagraph.Text.StartsWith("<i>-", StringComparison.Ordinal) && (currentParagraph.Text.EndsWith(".</i>", StringComparison.Ordinal) || currentParagraph.Text.EndsWith("!</i>", StringComparison.Ordinal)) &&
                                newParagraph.Text.StartsWith("<i>-", StringComparison.Ordinal) && (newParagraph.Text.EndsWith(".</i>", StringComparison.Ordinal) || newParagraph.Text.EndsWith("!</i>", StringComparison.Ordinal)))
                            {
                                currentParagraph.Text = currentParagraph.Text.Remove(3, 1);
                                newParagraph.Text = newParagraph.Text.Remove(3, 1);
                            }
                            else if (lines[0].StartsWith('-') && (lines[0].EndsWith('.') || lines[0].EndsWith('!') || lines[0].EndsWith('?')) &&
                                     lines[1].StartsWith("<i>-", StringComparison.Ordinal) && (lines[1].EndsWith(".</i>", StringComparison.Ordinal) || lines[1].EndsWith("!</i>", StringComparison.Ordinal) || lines[1].EndsWith("?</i>", StringComparison.Ordinal)))
                            {
                                currentParagraph.Text = lines[0].TrimStart('-').TrimStart();
                                newParagraph.Text = lines[1].Remove(3, 1).Replace("  ", " ").Trim();
                            }
                        }
                        else if (lines.Count == 2 && (lines[0].EndsWith(".</i>", StringComparison.Ordinal) || lines[0].EndsWith("!</i>", StringComparison.Ordinal) || lines[0].EndsWith("?</i>", StringComparison.Ordinal)))
                        {
                            currentParagraph.Text = Utilities.AutoBreakLine(lines[0], language);
                            newParagraph.Text = Utilities.AutoBreakLine(lines[1], language);
                            if (lines[0].Length > 5 && lines[0].StartsWith("<i>-", StringComparison.Ordinal) && lines[0][4] != '-' &&
                                lines[1].Length > 5 && lines[1].StartsWith("<i>-", StringComparison.Ordinal) && lines[1][4] != '-')
                            {
                                currentParagraph.Text = currentParagraph.Text.Remove(3, 1);
                                if (currentParagraph.Text[3] == ' ')
                                    currentParagraph.Text = currentParagraph.Text.Remove(3, 1);

                                newParagraph.Text = newParagraph.Text.Remove(3, 1);
                                if (newParagraph.Text[3] == ' ')
                                    newParagraph.Text = newParagraph.Text.Remove(3, 1);
                            }
                            else if (lines[0].StartsWith('-') && (lines[0].EndsWith('.') || lines[0].EndsWith('!') || lines[0].EndsWith('?')) &&
                                                    lines[1].StartsWith("<i>-", StringComparison.Ordinal) && (lines[1].EndsWith(".</i>", StringComparison.Ordinal) || lines[1].EndsWith("!</i>", StringComparison.Ordinal) || lines[1].EndsWith("?</i>", StringComparison.Ordinal)))
                            {
                                currentParagraph.Text = lines[0].TrimStart('-').TrimStart();
                                newParagraph.Text = lines[1].Remove(3, 1).Replace("  ", " ").Trim();
                            }
                            else if (lines[0].StartsWith("<i>-", StringComparison.Ordinal) && (lines[0].EndsWith(".</i>", StringComparison.Ordinal) || lines[0].EndsWith("!</i>", StringComparison.Ordinal) || lines[0].EndsWith("?</i>", StringComparison.Ordinal)) &&
                                lines[1].StartsWith('-') && (lines[1].EndsWith('.') || lines[1].EndsWith('!') || lines[1].EndsWith('?')))
                            {
                                currentParagraph.Text = lines[0].Remove(3, 1).Replace("  ", " ").Trim();
                                newParagraph.Text = lines[1].TrimStart('-').TrimStart();
                            }
                        }
                        else
                        {
                            string s = currentParagraph.Text;
                            var arr = HtmlUtil.RemoveHtmlTags(s, true).SplitToLines();
                            if (arr.Count != 2 || arr[0].Length > Configuration.Settings.General.SubtitleLineMaximumLength || arr[1].Length > Configuration.Settings.General.SubtitleLineMaximumLength)
                            {
                                if (arr.Count == 2 && arr[0].StartsWith('-') && arr[1].StartsWith('-'))
                                {
                                    if (lines[0].StartsWith("<i>-", StringComparison.Ordinal))
                                    {
                                        lines[0] = "<i>" + lines[0].Remove(0, 4).TrimStart();
                                    }
                                    lines[0] = lines[0].TrimStart('-').TrimStart();
                                    lines[1] = lines[1].TrimStart('-').TrimStart();
                                    s = lines[0] + Environment.NewLine + lines[1];
                                }
                                else
                                {
                                    s = Utilities.AutoBreakLine(currentParagraph.Text, 5, Configuration.Settings.Tools.MergeLinesShorterThan, language);
                                }
                            }

                            lines = s.SplitToLines();
                            if (lines.Count == 1)
                            {
                                s = Utilities.AutoBreakLine(currentParagraph.Text, 3, 20, language);
                                lines = s.SplitToLines();
                            }
                            if (lines.Count == 1)
                            {
                                s = Utilities.AutoBreakLine(currentParagraph.Text, 3, 18, language);
                                lines = s.SplitToLines();
                            }
                            if (lines.Count == 1)
                            {
                                s = Utilities.AutoBreakLine(currentParagraph.Text, 3, 15, language);
                                lines = s.SplitToLines();
                            }

                            if (lines.Count == 2)
                            {
                                if (Utilities.CountTagInText(s, "<i>") == 1 && lines[0].StartsWith("<i>", StringComparison.Ordinal) && lines[1].EndsWith("</i>", StringComparison.Ordinal))
                                {
                                    lines[0] += "</i>";
                                    lines[1] = "<i>" + lines[1];
                                }
                                currentParagraph.Text = Utilities.AutoBreakLine(lines[0], language);
                                newParagraph.Text = Utilities.AutoBreakLine(lines[1], language);
                            }
                            else if (lines.Count == 1)
                            {
                                currentParagraph.Text = Utilities.AutoBreakLine(lines[0], language);
                                newParagraph.Text = string.Empty;
                            }

                            if (currentParagraph.Text.StartsWith("<i>", StringComparison.Ordinal) && !currentParagraph.Text.Contains("</i>", StringComparison.Ordinal) &&
                             newParagraph.Text.EndsWith("</i>", StringComparison.Ordinal) && !newParagraph.Text.Contains("<i>", StringComparison.Ordinal))
                            {
                                currentParagraph.Text = currentParagraph.Text + "</i>";
                                newParagraph.Text = "<i>" + newParagraph.Text;
                            }
                            if (currentParagraph.Text.StartsWith("<b>", StringComparison.Ordinal) && !currentParagraph.Text.Contains("</b>", StringComparison.Ordinal) &&
                               newParagraph.Text.EndsWith("</b>", StringComparison.Ordinal) && !newParagraph.Text.Contains("<b>"))
                            {
                                currentParagraph.Text = currentParagraph.Text + "</b>";
                                newParagraph.Text = "<b>" + newParagraph.Text;
                            }
                            if (currentParagraph.Text.StartsWith("<i>-", StringComparison.Ordinal) && (currentParagraph.Text.EndsWith(".</i>", StringComparison.Ordinal) || currentParagraph.Text.EndsWith("!</i>", StringComparison.Ordinal)) &&
                                newParagraph.Text.StartsWith("<i>-", StringComparison.Ordinal) && (newParagraph.Text.EndsWith(".</i>", StringComparison.Ordinal) || newParagraph.Text.EndsWith("!</i>", StringComparison.Ordinal)))
                            {
                                currentParagraph.Text = currentParagraph.Text.Remove(3, 1);
                                newParagraph.Text = newParagraph.Text.Remove(3, 1);
                            }
                        }
                    }
                    if (currentParagraph.Text.StartsWith("<i> ", StringComparison.Ordinal))
                        currentParagraph.Text = currentParagraph.Text.Remove(3, 1);
                    if (newParagraph.Text.StartsWith("<i> ", StringComparison.Ordinal))
                        newParagraph.Text = newParagraph.Text.Remove(3, 1);

                    double middle = currentParagraph.StartTime.TotalMilliseconds + (currentParagraph.Duration.TotalMilliseconds / 2);
                    if (!string.IsNullOrWhiteSpace(HtmlUtil.RemoveHtmlTags(oldText)))
                    {
                        var startFactor = (double)HtmlUtil.RemoveHtmlTags(currentParagraph.Text).Length / HtmlUtil.RemoveHtmlTags(oldText).Length;
                        if (startFactor < 0.25)
                            startFactor = 0.25;
                        if (startFactor > 0.75)
                            startFactor = 0.75;
                        middle = currentParagraph.StartTime.TotalMilliseconds + (currentParagraph.Duration.TotalMilliseconds * startFactor);
                    }

                    if (currentParagraph.StartTime.IsMaxTime && currentParagraph.EndTime.IsMaxTime)
                    {
                        newParagraph.StartTime = TimeCode.MaxTime;
                        newParagraph.EndTime = TimeCode.MaxTime;
                    }
                    else
                    {
                        if (splitSeconds.HasValue && splitSeconds.Value > (currentParagraph.StartTime.TotalSeconds + 0.2) && splitSeconds.Value < (currentParagraph.EndTime.TotalSeconds - 0.2))
                            middle = splitSeconds.Value * TimeCode.BaseUnit;
                        newParagraph.EndTime.TotalMilliseconds = currentParagraph.EndTime.TotalMilliseconds;
                        currentParagraph.EndTime.TotalMilliseconds = middle;
                        newParagraph.StartTime.TotalMilliseconds = currentParagraph.EndTime.TotalMilliseconds + 1;
                        if (Configuration.Settings.General.MinimumMillisecondsBetweenLines > 0)
                        {
                            var next = _subtitle.GetParagraphOrDefault(firstSelectedIndex + 1);
                            if (next == null || next.StartTime.TotalMilliseconds > newParagraph.EndTime.TotalMilliseconds + Configuration.Settings.General.MinimumMillisecondsBetweenLines + Configuration.Settings.General.MinimumMillisecondsBetweenLines)
                            {
                                newParagraph.StartTime.TotalMilliseconds += Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                                newParagraph.EndTime.TotalMilliseconds += Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                            }
                            else
                            {
                                newParagraph.StartTime.TotalMilliseconds += Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                            }
                        }
                    }

                    if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                    {
                        var originalCurrent = Utilities.GetOriginalParagraph(firstSelectedIndex, currentParagraph, _subtitleAlternate.Paragraphs);
                        if (originalCurrent != null)
                        {
                            string languageOriginal = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitleAlternate);

                            originalCurrent.EndTime.TotalMilliseconds = currentParagraph.EndTime.TotalMilliseconds;
                            var originalNew = new Paragraph(newParagraph);
                            originalNew.NewSection = false;

                            lines = originalCurrent.Text.SplitToLines();

                            oldText = originalCurrent.Text;
                            if (alternateTextIndex != null && alternateTextIndex.Value > 2 && alternateTextIndex.Value < oldText.Length - 2)
                            {
                                originalCurrent.Text = Utilities.AutoBreakLine(oldText.Substring(0, alternateTextIndex.Value).Trim(), language);
                                originalNew.Text = Utilities.AutoBreakLine(oldText.Substring(alternateTextIndex.Value).Trim(), language);
                                if (originalCurrent.Text.StartsWith("<i>", StringComparison.Ordinal) && !originalCurrent.Text.Contains("</i>", StringComparison.Ordinal) &&
                                    originalNew.Text.EndsWith("</i>", StringComparison.Ordinal) && !originalNew.Text.Contains("<i>", StringComparison.Ordinal))
                                {
                                    originalCurrent.Text = originalCurrent.Text + "</i>";
                                    originalNew.Text = "<i>" + originalNew.Text;
                                }
                                if (originalCurrent.Text.StartsWith("<b>", StringComparison.Ordinal) && !originalCurrent.Text.Contains("</b>") &&
                                    originalNew.Text.EndsWith("</b>", StringComparison.Ordinal) && !originalNew.Text.Contains("<b>"))
                                {
                                    originalCurrent.Text = originalCurrent.Text + "</b>";
                                    originalNew.Text = "<b>" + originalNew.Text;
                                }
                                if (originalCurrent.Text.StartsWith('-') && (originalCurrent.Text.EndsWith('.') || originalCurrent.Text.EndsWith('!')) &&
                                    originalNew.Text.StartsWith('-') && (originalNew.Text.EndsWith('.') || originalNew.Text.EndsWith('!')))
                                {
                                    originalCurrent.Text = originalCurrent.Text.Remove(0, 1).Trim();
                                    originalNew.Text = originalNew.Text.Remove(0, 1).Trim();
                                }
                                if (originalCurrent.Text.StartsWith("<i>-", StringComparison.Ordinal) && (originalCurrent.Text.EndsWith(".</i>", StringComparison.Ordinal) || originalCurrent.Text.EndsWith("!</i>", StringComparison.Ordinal)) &&
                                    originalNew.Text.StartsWith("<i>-", StringComparison.Ordinal) && (originalNew.Text.EndsWith(".</i>", StringComparison.Ordinal) || originalNew.Text.EndsWith("!</i>", StringComparison.Ordinal)))
                                {
                                    originalCurrent.Text = originalCurrent.Text.Remove(3, 1);
                                    originalNew.Text = originalNew.Text.Remove(3, 1);
                                }
                                if (originalCurrent.Text.StartsWith("<b>-", StringComparison.Ordinal) && (originalCurrent.Text.EndsWith(".</b>", StringComparison.Ordinal) || originalCurrent.Text.EndsWith("!</b>", StringComparison.Ordinal)) &&
                                    originalNew.Text.StartsWith("<b>-", StringComparison.Ordinal) && (originalNew.Text.EndsWith(".</b>", StringComparison.Ordinal) || originalNew.Text.EndsWith("!</b>", StringComparison.Ordinal)))
                                {
                                    originalCurrent.Text = originalCurrent.Text.Remove(3, 1);
                                    originalNew.Text = originalNew.Text.Remove(3, 1);
                                }
                                lines.Clear();
                            }
                            else if (lines.Count == 2 && (lines[0].EndsWith('.') || lines[0].EndsWith('!') || lines[0].EndsWith('?')))
                            {
                                string a = lines[0].Trim();
                                string b = lines[1].Trim();
                                if (oldText.TrimStart().StartsWith("<i>", StringComparison.Ordinal) && oldText.TrimEnd().EndsWith("</i>", StringComparison.Ordinal) &&
                                    Utilities.CountTagInText(oldText, "<i>") == 1 && Utilities.CountTagInText(oldText, "</i>") == 1)
                                {
                                    a = a + "</i>";
                                    b = "<i>" + b;
                                }
                                if (oldText.TrimStart().StartsWith("<b>", StringComparison.Ordinal) && oldText.TrimEnd().EndsWith("</b>", StringComparison.Ordinal) &&
                                    Utilities.CountTagInText(oldText, "<b>") == 1 && Utilities.CountTagInText(oldText, "</b>") == 1)
                                {
                                    a = a + "</b>";
                                    b = "<b>" + b;
                                }
                                if (a.StartsWith('-') && (a.EndsWith('.') || a.EndsWith('!') || a.EndsWith('?')) &&
                                    b.StartsWith('-') && (b.EndsWith('.') || b.EndsWith('!') || b.EndsWith('?')))
                                {
                                    a = a.TrimStart('-').TrimStart();
                                    b = b.TrimStart('-').TrimStart();
                                }
                                if (a.StartsWith("<i>-", StringComparison.Ordinal) && (a.EndsWith(".</i>", StringComparison.Ordinal) || a.EndsWith("!</i>", StringComparison.Ordinal) || a.EndsWith("?</i>", StringComparison.Ordinal)) &&
                                    b.StartsWith("<i>-", StringComparison.Ordinal) && (b.EndsWith(".</i>", StringComparison.Ordinal) || b.EndsWith("!</i>", StringComparison.Ordinal) || b.EndsWith("?</i>", StringComparison.Ordinal)))
                                {
                                    a = a.Remove(3, 1).Replace("  ", " ");
                                    b = b.Remove(3, 1).Replace("  ", " ");
                                }

                                lines[0] = a;
                                lines[1] = b;
                                originalCurrent.Text = Utilities.AutoBreakLine(a);
                                originalNew.Text = Utilities.AutoBreakLine(b);
                            }
                            else
                            {
                                string s = Utilities.AutoBreakLine(originalCurrent.Text, 5, Configuration.Settings.Tools.MergeLinesShorterThan, languageOriginal);
                                lines = s.SplitToLines();
                            }

                            if (lines.Count == 1)
                            {
                                string s = Utilities.AutoBreakLine(lines[0], 3, 20, languageOriginal);
                                lines = s.SplitToLines();
                            }
                            if (lines.Count == 1)
                            {
                                string s = Utilities.AutoBreakLine(lines[0], 3, 18, languageOriginal);
                                lines = s.SplitToLines();
                            }
                            if (lines.Count == 1)
                            {
                                string s = Utilities.AutoBreakLine(lines[0], 3, 15, languageOriginal);
                                lines = s.SplitToLines();
                            }
                            if (lines.Count == 2)
                            {
                                string a = lines[0].Trim();
                                string b = lines[1].Trim();
                                if (oldText.TrimStart().StartsWith("<i>", StringComparison.Ordinal) && oldText.TrimEnd().EndsWith("</i>", StringComparison.Ordinal) &&
                                    Utilities.CountTagInText(oldText, "<i>") == 1 && Utilities.CountTagInText(oldText, "</i>") == 1)
                                {
                                    a = a + "</i>";
                                    b = "<i>" + b;
                                }
                                if (oldText.TrimStart().StartsWith("<b>", StringComparison.Ordinal) && oldText.TrimEnd().EndsWith("</b>", StringComparison.Ordinal) &&
                                    Utilities.CountTagInText(oldText, "<b>") == 1 && Utilities.CountTagInText(oldText, "</b>") == 1)
                                {
                                    a = a + "</b>";
                                    b = "<b>" + b;
                                }
                                if (a.StartsWith('-') && (a.EndsWith('.') || a.EndsWith('!') || a.EndsWith('?')) &&
                                    b.StartsWith('-') && (b.EndsWith('.') || b.EndsWith('!') || b.EndsWith('?')))
                                {
                                    a = a.TrimStart('-').TrimStart();
                                    b = b.TrimStart('-').TrimStart();
                                }
                                if (a.StartsWith("<i>-", StringComparison.Ordinal) && (a.EndsWith(".</i>", StringComparison.Ordinal) || a.EndsWith("!</i>", StringComparison.Ordinal) || a.EndsWith("?</i>", StringComparison.Ordinal)) &&
                                    b.StartsWith("<i>-", StringComparison.Ordinal) && (b.EndsWith(".</i>", StringComparison.Ordinal) || b.EndsWith("!</i>", StringComparison.Ordinal) || b.EndsWith("?</i>", StringComparison.Ordinal)))
                                {
                                    a = a.Remove(3, 1).Replace("  ", " ");
                                    b = b.Remove(3, 1).Replace("  ", " ");
                                }

                                lines[0] = a;
                                lines[1] = b;

                                originalCurrent.Text = Utilities.AutoBreakLine(lines[0]);
                                originalNew.Text = Utilities.AutoBreakLine(lines[1]);
                            }
                            else if (lines.Count == 1)
                            {
                                originalNew.Text = string.Empty;
                            }
                            if (originalCurrent != null && originalNew != null)
                            {
                                if (originalCurrent.Text.StartsWith("<i> ", StringComparison.Ordinal))
                                    originalCurrent.Text = originalCurrent.Text.Remove(3, 1);
                                if (originalNew.Text.StartsWith("<i> ", StringComparison.Ordinal))
                                    originalCurrent.Text = originalCurrent.Text.Remove(3, 1);
                            }
                            _subtitleAlternate.InsertParagraphInCorrectTimeOrder(originalNew);
                            _subtitleAlternate.Renumber();
                        }
                    }

                    if (_networkSession != null)
                    {
                        _networkSession.TimerStop();
                        SetDurationInSeconds(currentParagraph.Duration.TotalSeconds);
                        _networkSession.UpdateLine(_subtitle.GetIndex(currentParagraph), currentParagraph);
                        NetworkGetSendUpdates(new List<int>(), firstSelectedIndex + 1, newParagraph);
                    }
                    else
                    {
                        if (GetCurrentSubtitleFormat().IsFrameBased)
                        {
                            if (currentParagraph != null)
                            {
                                currentParagraph.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                                currentParagraph.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                            }
                            newParagraph.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                            newParagraph.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                        }
                        _subtitle.Paragraphs.Insert(firstSelectedIndex + 1, newParagraph);
                        _subtitle.Renumber();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    }
                    SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedIndex);
                    ShowSource();
                    ShowStatus(_language.LineSplitted);
                    SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                    RefreshSelectedParagraph();
                    SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedIndex, true);
                }
            }

            private void MergeBeforeToolStripMenuItemClick(object sender, EventArgs e)
            {
                string language = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle);
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    int firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;

                    var prevParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex - 1);
                    var currentParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex);

                    if (prevParagraph != null && currentParagraph != null)
                    {
                        SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                        MakeHistoryForUndo(_language.BeforeMergeLines);

                        if (_subtitleAlternate != null)
                        {
                            var prevOriginal = Utilities.GetOriginalParagraph(firstSelectedIndex, prevParagraph, _subtitleAlternate.Paragraphs);
                            var currentOriginal = Utilities.GetOriginalParagraph(firstSelectedIndex + 1, currentParagraph, _subtitleAlternate.Paragraphs);

                            if (currentOriginal != null)
                            {
                                if (prevOriginal == null)
                                {
                                    currentOriginal.StartTime = prevParagraph.StartTime;
                                    currentOriginal.EndTime = currentParagraph.EndTime;
                                }
                                else
                                {
                                    prevOriginal.Text = prevOriginal.Text.Replace(Environment.NewLine, " ");
                                    prevOriginal.Text += Environment.NewLine + currentOriginal.Text.Replace(Environment.NewLine, " ");
                                    prevOriginal.Text = ChangeAllLinesItalictoSingleItalic(prevOriginal.Text);
                                    prevOriginal.Text = Utilities.AutoBreakLine(prevOriginal.Text);
                                    prevOriginal.EndTime = currentOriginal.EndTime;
                                    _subtitleAlternate.Paragraphs.Remove(currentOriginal);
                                }
                                _subtitleAlternate.Renumber();
                            }
                        }

                        prevParagraph.Text = prevParagraph.Text.Replace(Environment.NewLine, " ");
                        prevParagraph.Text += Environment.NewLine + currentParagraph.Text.Replace(Environment.NewLine, " ");
                        prevParagraph.Text = Utilities.AutoBreakLine(prevParagraph.Text, language);

                        //prevParagraph.EndTime.TotalMilliseconds = prevParagraph.EndTime.TotalMilliseconds + currentParagraph.Duration.TotalMilliseconds;
                        prevParagraph.EndTime.TotalMilliseconds = currentParagraph.EndTime.TotalMilliseconds;

                        if (_networkSession != null)
                        {
                            _networkSession.TimerStop();
                            var deleteIndices = new List<int>();
                            deleteIndices.Add(_subtitle.GetIndex(currentParagraph));
                            NetworkGetSendUpdates(deleteIndices, 0, null);
                        }
                        else
                        {
                            _subtitle.Paragraphs.Remove(currentParagraph);
                            _subtitle.Renumber();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            SubtitleListview1.Items[firstSelectedIndex - 1].Selected = true;
                        }
                        SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedIndex - 1, true);
                        ShowSource();
                        ShowStatus(_language.LinesMerged);
                        SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                        RefreshSelectedParagraph();
                    }
                }
            }

            private void MergeSelectedLines()
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 1)
                {
                    var sb = new StringBuilder();
                    var deleteIndices = new List<int>();
                    bool first = true;
                    int firstIndex = 0;
                    double durationMilliseconds = 0;
                    int next = 0;
                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        if (first)
                        {
                            firstIndex = index;
                            next = index + 1;
                            first = !first;
                        }
                        else
                        {
                            deleteIndices.Add(index);
                            if (next != index)
                                return;
                            next++;
                        }
                        sb.AppendLine(_subtitle.Paragraphs[index].Text);
                        durationMilliseconds += _subtitle.Paragraphs[index].Duration.TotalMilliseconds;
                    }

                    if (sb.Length > 200)
                        return;

                    SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                    MakeHistoryForUndo(_language.BeforeMergeLines);

                    var currentParagraph = _subtitle.Paragraphs[firstIndex];
                    string text = sb.ToString();
                    text = HtmlUtil.FixInvalidItalicTags(text);
                    text = ChangeAllLinesItalictoSingleItalic(text);
                    text = Utilities.AutoBreakLine(text, LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle));
                    currentParagraph.Text = text;

                    //display time
                    currentParagraph.EndTime.TotalMilliseconds = currentParagraph.StartTime.TotalMilliseconds + durationMilliseconds;

                    var nextParagraph = _subtitle.GetParagraphOrDefault(next);
                    if (nextParagraph != null && currentParagraph.EndTime.TotalMilliseconds > nextParagraph.StartTime.TotalMilliseconds && currentParagraph.StartTime.TotalMilliseconds < nextParagraph.StartTime.TotalMilliseconds)
                    {
                        currentParagraph.EndTime.TotalMilliseconds = nextParagraph.StartTime.TotalMilliseconds - 1;
                    }

                    // original subtitle
                    if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                    {
                        var original = Utilities.GetOriginalParagraph(firstIndex, currentParagraph, _subtitleAlternate.Paragraphs);
                        if (original != null)
                        {
                            var originalTexts = new StringBuilder();
                            originalTexts.Append(original.Text + " ");
                            for (int i = 0; i < deleteIndices.Count; i++)
                            {
                                var originalNext = Utilities.GetOriginalParagraph(deleteIndices[i], _subtitle.Paragraphs[deleteIndices[i]], _subtitleAlternate.Paragraphs);
                                if (originalNext != null)
                                    originalTexts.Append(originalNext.Text + " ");
                            }
                            for (int i = deleteIndices.Count - 1; i >= 0; i--)
                            {
                                var originalNext = Utilities.GetOriginalParagraph(deleteIndices[i], _subtitle.Paragraphs[deleteIndices[i]], _subtitleAlternate.Paragraphs);
                                if (originalNext != null)
                                    _subtitleAlternate.Paragraphs.Remove(originalNext);
                            }
                            original.Text = originalTexts.ToString().Replace("  ", " ");
                            original.Text = original.Text.Replace(Environment.NewLine, " ");
                            original.Text = ChangeAllLinesItalictoSingleItalic(original.Text);
                            original.Text = Utilities.AutoBreakLine(original.Text);
                            original.EndTime.TotalMilliseconds = currentParagraph.EndTime.TotalMilliseconds;
                            _subtitleAlternate.Renumber();
                        }
                    }

                    if (_networkSession != null)
                    {
                        _networkSession.TimerStop();
                        _networkSession.UpdateLine(firstIndex, currentParagraph);
                        NetworkGetSendUpdates(deleteIndices, 0, null);
                    }
                    else
                    {
                        for (int i = deleteIndices.Count - 1; i >= 0; i--)
                            _subtitle.Paragraphs.RemoveAt(deleteIndices[i]);
                        _subtitle.Renumber();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    }
                    ShowSource();
                    ShowStatus(_language.LinesMerged);
                    SubtitleListview1.SelectIndexAndEnsureVisible(firstIndex, true);
                    SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                    RefreshSelectedParagraph();
                }
            }

            private static string ChangeAllLinesItalictoSingleItalic(string text)
            {
                if (!text.Contains("<i>"))
                    return text;
                foreach (var line in text.SplitToLines())
                {
                    if (!line.TrimStart().StartsWith("<i>", StringComparison.Ordinal) || !line.TrimEnd().EndsWith("</i>", StringComparison.Ordinal))
                        return text;
                }
                return "<i>" + HtmlUtil.RemoveOpenCloseTags(text, HtmlUtil.TagItalic).Trim() + "</i>";
            }

            private void MergeAfterToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    if (SubtitleListview1.SelectedItems.Count > 2)
                    {
                        MergeSelectedLines();
                        return;
                    }

                    MergeWithLineAfter(false);
                }
            }

            private void MergeWithLineAfter(bool insertDash)
            {
                int firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;

                var currentParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                var nextParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex + 1);

                if (nextParagraph != null && currentParagraph != null)
                {
                    SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                    MakeHistoryForUndo(_language.BeforeMergeLines);

                    if (_subtitleAlternate != null)
                    {
                        var original = Utilities.GetOriginalParagraph(firstSelectedIndex, currentParagraph, _subtitleAlternate.Paragraphs);
                        var originalNext = Utilities.GetOriginalParagraph(firstSelectedIndex + 1, nextParagraph, _subtitleAlternate.Paragraphs);

                        if (originalNext != null)
                        {
                            if (original == null)
                            {
                                originalNext.StartTime.TotalMilliseconds = currentParagraph.StartTime.TotalMilliseconds;
                                originalNext.EndTime.TotalMilliseconds = nextParagraph.EndTime.TotalMilliseconds;
                            }
                            else
                            {
                                if (insertDash)
                                {
                                    string s = Utilities.UnbreakLine(original.Text);
                                    if (s.StartsWith('-') || s.StartsWith("<i>-", StringComparison.Ordinal))
                                        original.Text = s;
                                    else if (s.StartsWith("<i>", StringComparison.Ordinal))
                                        original.Text = s.Insert(3, "- ");
                                    else
                                        original.Text = "- " + s;

                                    s = Utilities.UnbreakLine(originalNext.Text);
                                    if (s.StartsWith('-') || s.StartsWith("<i>-", StringComparison.Ordinal))
                                        original.Text += Environment.NewLine + s;
                                    else if (s.StartsWith("<i>", StringComparison.Ordinal))
                                        original.Text += Environment.NewLine + s.Insert(3, "- ");
                                    else
                                        original.Text += Environment.NewLine + "- " + s;

                                    original.Text = original.Text.Replace("</i>" + Environment.NewLine + "<i>", Environment.NewLine);
                                }
                                else
                                {
                                    string old1 = original.Text;
                                    string old2 = originalNext.Text;
                                    original.Text = original.Text.Replace(Environment.NewLine, " ");
                                    original.Text += Environment.NewLine + originalNext.Text.Replace(Environment.NewLine, " ");
                                    original.Text = ChangeAllLinesItalictoSingleItalic(original.Text);

                                    if (old1.Contains(Environment.NewLine) || old2.Contains(Environment.NewLine) ||
                                        old1.Length > Configuration.Settings.General.SubtitleLineMaximumLength || old2.Length > Configuration.Settings.General.SubtitleLineMaximumLength)
                                        original.Text = Utilities.AutoBreakLine(original.Text, LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitleAlternate));

                                    if (string.IsNullOrWhiteSpace(old1))
                                        original.Text = original.Text.TrimStart();

                                    if (string.IsNullOrWhiteSpace(old2))
                                        original.Text = original.Text.TrimEnd();
                                }
                                original.EndTime = originalNext.EndTime;
                                _subtitleAlternate.Paragraphs.Remove(originalNext);
                            }
                            _subtitleAlternate.Renumber();
                        }
                    }

                    if (insertDash)
                    {
                        string s = Utilities.UnbreakLine(currentParagraph.Text);
                        if (s.StartsWith('-') || s.StartsWith("<i>-", StringComparison.Ordinal))
                            currentParagraph.Text = s;
                        else if (s.StartsWith("<i>", StringComparison.Ordinal))
                            currentParagraph.Text = s.Insert(3, "- ");
                        else
                            currentParagraph.Text = "- " + s;

                        s = Utilities.UnbreakLine(nextParagraph.Text);
                        if (s.StartsWith('-') || s.StartsWith("<i>-", StringComparison.Ordinal))
                            currentParagraph.Text += Environment.NewLine + s;
                        else if (s.StartsWith("<i>", StringComparison.Ordinal))
                            currentParagraph.Text += Environment.NewLine + s.Insert(3, "- ");
                        else
                            currentParagraph.Text += Environment.NewLine + "- " + s;

                        currentParagraph.Text = currentParagraph.Text.Replace("</i>" + Environment.NewLine + "<i>", Environment.NewLine);
                    }
                    else
                    {
                        string old1 = currentParagraph.Text;
                        string old2 = nextParagraph.Text;
                        currentParagraph.Text = currentParagraph.Text.Replace(Environment.NewLine, " ");
                        currentParagraph.Text += Environment.NewLine + nextParagraph.Text.Replace(Environment.NewLine, " ");
                        currentParagraph.Text = ChangeAllLinesItalictoSingleItalic(currentParagraph.Text);

                        if (old1.Contains(Environment.NewLine) || old2.Contains(Environment.NewLine) ||
                            old1.Length > Configuration.Settings.General.SubtitleLineMaximumLength || old2.Length > Configuration.Settings.General.SubtitleLineMaximumLength)
                            currentParagraph.Text = Utilities.AutoBreakLine(currentParagraph.Text, LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle));

                        if (string.IsNullOrWhiteSpace(old1) && old2 != null)
                            currentParagraph.Text = old2.Trim();

                        if (string.IsNullOrWhiteSpace(old2) && old1 != null)
                            currentParagraph.Text = old1.Trim();
                    }

                    currentParagraph.EndTime.TotalMilliseconds = nextParagraph.EndTime.TotalMilliseconds;

                    if (_networkSession != null)
                    {
                        _networkSession.TimerStop();
                        SetDurationInSeconds(currentParagraph.Duration.TotalSeconds);
                        _networkSession.UpdateLine(_subtitle.GetIndex(currentParagraph), currentParagraph);
                        var deleteIndices = new List<int>();
                        deleteIndices.Add(_subtitle.GetIndex(nextParagraph));
                        NetworkGetSendUpdates(deleteIndices, 0, null);
                    }
                    else
                    {
                        _subtitle.Paragraphs.Remove(nextParagraph);
                        _subtitle.Renumber();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    }
                    ShowSource();
                    ShowStatus(_language.LinesMerged);
                    SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedIndex);
                    SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                    RefreshSelectedParagraph();
                    SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedIndex, true);
                }
            }

            private void UpdateStartTimeInfo(TimeCode startTime)
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0 && startTime != null)
                {
                    UpdateOverlapErrors(startTime);

                    // update _subtitle + listview
                    var p = _subtitle.Paragraphs[_subtitleListViewIndex];
                    p.EndTime.TotalMilliseconds += (startTime.TotalMilliseconds - p.StartTime.TotalMilliseconds);
                    p.StartTime = startTime;
                    SubtitleListview1.SetStartTimeAndDuration(_subtitleListViewIndex, p, _subtitle.GetParagraphOrDefault(_subtitleListViewIndex + 1), _subtitle.GetParagraphOrDefault(_subtitleListViewIndex - 1));
                    if (GetCurrentSubtitleFormat().IsFrameBased)
                    {
                        p.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        p.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                    }

                    StartUpdateListSyntaxColoring();
                }
            }

            private void StartUpdateListSyntaxColoring()
            {
                if (!_timerDoSyntaxColoring.Enabled)
                    _timerDoSyntaxColoring.Start();
            }

            private void UpdateListSyntaxColoring()
            {
                if (_loading || !IsSubtitleLoaded || _subtitleListViewIndex < 0 || _subtitleListViewIndex >= _subtitle.Paragraphs.Count)
                    return;

                SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, _subtitleListViewIndex, _subtitle.Paragraphs[_subtitleListViewIndex]);
                var idx = _subtitleListViewIndex + 1;
                var p = _subtitle.GetParagraphOrDefault(idx);
                if (p != null)
                    SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, idx, p);
                idx = _subtitleListViewIndex - 1;
                p = _subtitle.GetParagraphOrDefault(idx);
                if (p != null)
                    SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, idx, p);
            }

            private void UpdateOverlapErrors(TimeCode startTime)
            {
                string startTimeWarning = string.Empty;
                string durationWarning = string.Empty;
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0 && startTime != null)
                {
                    int firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;

                    var prevParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex - 1);
                    if (prevParagraph != null && !prevParagraph.EndTime.IsMaxTime && prevParagraph.EndTime.TotalMilliseconds > startTime.TotalMilliseconds && Configuration.Settings.Tools.ListViewSyntaxColorOverlap)
                        startTimeWarning = string.Format(_languageGeneral.OverlapPreviousLineX, prevParagraph.EndTime.TotalSeconds - startTime.TotalSeconds);

                    var nextParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex + 1);
                    if (nextParagraph != null)
                    {
                        double durationMilliSeconds = GetDurationInMilliseconds();
                        if (startTime.TotalMilliseconds + durationMilliSeconds > nextParagraph.StartTime.TotalMilliseconds &&
                            Configuration.Settings.Tools.ListViewSyntaxColorOverlap &&
                            !startTime.IsMaxTime)
                        {
                            durationWarning = string.Format(_languageGeneral.OverlapX, ((startTime.TotalMilliseconds + durationMilliSeconds) - nextParagraph.StartTime.TotalMilliseconds) / TimeCode.BaseUnit);
                        }

                        if (startTimeWarning.Length == 0 &&
                            startTime.TotalMilliseconds > nextParagraph.StartTime.TotalMilliseconds &&
                            Configuration.Settings.Tools.ListViewSyntaxColorOverlap &&
                            !startTime.IsMaxTime)
                        {
                            double di = (startTime.TotalMilliseconds - nextParagraph.StartTime.TotalMilliseconds) / TimeCode.BaseUnit;
                            startTimeWarning = string.Format(_languageGeneral.OverlapNextX, di);
                        }
                        else if (numericUpDownDuration.Value < 0)
                        {
                            durationWarning = _languageGeneral.Negative;
                        }
                    }
                }
                labelStartTimeWarning.Text = startTimeWarning;
                labelDurationWarning.Text = durationWarning;
            }

            private double _durationMsInitialValue = 0;
            private bool _durationIsDirty = false;

            private double GetDurationInMilliseconds()
            {
                if (!_durationIsDirty)
                    return _durationMsInitialValue;
                if (Configuration.Settings.General.UseTimeFormatHHMMSSFF)
                {
                    var seconds = (int)numericUpDownDuration.Value;
                    var frames = (int)Math.Round((Convert.ToDouble(numericUpDownDuration.Value) % 1.0 * 100.0));
                    return seconds * TimeCode.BaseUnit + frames * (TimeCode.BaseUnit / Configuration.Settings.General.CurrentFrameRate);
                }
                return ((double)numericUpDownDuration.Value * TimeCode.BaseUnit);
            }

            private void SetDurationInSeconds(double seconds)
            {
                _durationIsDirty = false;
                _durationMsInitialValue = seconds * 1000.0;
                if (Configuration.Settings.General.UseTimeFormatHHMMSSFF)
                {
                    var wholeSeconds = (int)seconds;
                    var frames = SubtitleFormat.MillisecondsToFrames(seconds % 1.0 * TimeCode.BaseUnit);
                    var extraSeconds = (int)(frames / Configuration.Settings.General.CurrentFrameRate);
                    var restFrames = (int)(frames % Configuration.Settings.General.CurrentFrameRate);
                    numericUpDownDuration.Value = (decimal)(wholeSeconds + extraSeconds + restFrames / 100.0);
                }
                else
                {
                    var d = (decimal)seconds;
                    if (d > numericUpDownDuration.Maximum)
                        numericUpDownDuration.Value = numericUpDownDuration.Maximum;
                    else if (d < numericUpDownDuration.Minimum)
                        numericUpDownDuration.Value = numericUpDownDuration.Minimum;
                    else
                        numericUpDownDuration.Value = d;
                }
            }

            private void NumericUpDownDurationValueChanged(object sender, EventArgs e)
            {
                _durationIsDirty = true;
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    int firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;

                    var currentParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                    if (currentParagraph != null)
                    {
                        // update _subtitle + listview
                        string oldDuration = currentParagraph.Duration.ToString();

                        var temp = new Paragraph(currentParagraph);

                        if (Configuration.Settings.General.UseTimeFormatHHMMSSFF)
                        {
                            var seconds = (int)numericUpDownDuration.Value;
                            var frames = Convert.ToInt32((numericUpDownDuration.Value - seconds) * 100);
                            if (frames > Math.Round(Configuration.Settings.General.CurrentFrameRate) - 1)
                            {
                                numericUpDownDuration.ValueChanged -= NumericUpDownDurationValueChanged;
                                if (frames >= 99)
                                    numericUpDownDuration.Value = (decimal)(seconds + ((Math.Round((Configuration.Settings.General.CurrentFrameRate - 1))) / 100.0));
                                else
                                    numericUpDownDuration.Value = seconds + 1;
                                numericUpDownDuration.ValueChanged += NumericUpDownDurationValueChanged;
                            }
                        }
                        temp.EndTime.TotalMilliseconds = currentParagraph.StartTime.TotalMilliseconds + GetDurationInMilliseconds();

                        MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.DisplayTimeAdjustedX, "#" + currentParagraph.Number + ": " + oldDuration + " -> " + temp.Duration));

                        currentParagraph.EndTime.TotalMilliseconds = temp.EndTime.TotalMilliseconds;
                        SubtitleListview1.SetDuration(firstSelectedIndex, currentParagraph, _subtitle.GetParagraphOrDefault(firstSelectedIndex + 1));

                        UpdateOverlapErrors(timeUpDownStartTime.TimeCode);
                        UpdateListViewTextCharactersPerSeconds(labelCharactersPerSecond, currentParagraph);

                        if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                        {
                            var original = Utilities.GetOriginalParagraph(firstSelectedIndex, currentParagraph, _subtitleAlternate.Paragraphs);
                            if (original != null)
                            {
                                original.EndTime.TotalMilliseconds = currentParagraph.EndTime.TotalMilliseconds;
                            }
                        }

                        StartUpdateListSyntaxColoring();

                        if (GetCurrentSubtitleFormat().IsFrameBased)
                        {
                            currentParagraph.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                            currentParagraph.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                        }
                    }
                    labelStatus.Text = string.Empty;
                    StartUpdateListSyntaxColoring();
                }
            }

            private void InitializeListViewEditBoxAlternate(Paragraph p, int firstSelectedIndex)
            {
                if (_subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    var original = Utilities.GetOriginalParagraph(firstSelectedIndex, p, _subtitleAlternate.Paragraphs);
                    if (original == null)
                    {
                        textBoxListViewTextAlternate.Enabled = false;
                        textBoxListViewTextAlternate.Text = string.Empty;
                        labelAlternateCharactersPerSecond.Text = string.Empty;
                    }
                    else
                    {
                        textBoxListViewTextAlternate.Enabled = true;
                        textBoxListViewTextAlternate.TextChanged -= TextBoxListViewTextAlternateTextChanged;
                        textBoxListViewTextAlternate.Text = original.Text;
                        textBoxListViewTextAlternate.TextChanged += TextBoxListViewTextAlternateTextChanged;
                        UpdateListViewTextCharactersPerSeconds(labelAlternateCharactersPerSecond, original);
                        _listViewAlternateTextUndoLast = original.Text;
                    }
                }
            }

            private void InitializeListViewEditBox(Paragraph p)
            {
                textBoxListViewText.TextChanged -= TextBoxListViewTextTextChanged;
                textBoxListViewText.Text = p.Text;
                textBoxListViewText.TextChanged += TextBoxListViewTextTextChanged;
                _listViewTextUndoLast = p.Text;

                timeUpDownStartTime.MaskedTextBox.TextChanged -= MaskedTextBoxTextChanged;
                timeUpDownStartTime.TimeCode = p.StartTime;
                timeUpDownStartTime.MaskedTextBox.TextChanged += MaskedTextBoxTextChanged;

                numericUpDownDuration.ValueChanged -= NumericUpDownDurationValueChanged;
                if (p.Duration.TotalSeconds > (double)numericUpDownDuration.Maximum)
                    SetDurationInSeconds((double)numericUpDownDuration.Maximum);
                else
                    SetDurationInSeconds(p.Duration.TotalSeconds);
                numericUpDownDuration.ValueChanged += NumericUpDownDurationValueChanged;

                UpdateOverlapErrors(timeUpDownStartTime.TimeCode);
                UpdateListViewTextCharactersPerSeconds(labelCharactersPerSecond, p);
                if (_subtitle != null && _subtitle.Paragraphs.Count > 0)
                    textBoxListViewText.Enabled = true;

                StartUpdateListSyntaxColoring();
            }

            private void MaskedTextBoxTextChanged(object sender, EventArgs e)
            {
                if (_subtitleListViewIndex >= 0)
                {
                    MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.StarTimeAdjustedX, "#" + (_subtitleListViewIndex + 1) + ": " + timeUpDownStartTime.TimeCode));

                    int firstSelectedIndex = FirstSelectedIndex;
                    var oldParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                    if (oldParagraph != null)
                        oldParagraph = new Paragraph(oldParagraph);

                    UpdateStartTimeInfo(timeUpDownStartTime.TimeCode);

                    UpdateOriginalTimeCodes(oldParagraph);
                    labelStatus.Text = string.Empty;
                }
            }

            private void UpdateOriginalTimeCodes(Paragraph currentPargraphBeforeChange)
            {
                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    int firstSelectedIndex = FirstSelectedIndex;
                    var p = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                    if (currentPargraphBeforeChange != null && p != null)
                    {
                        var original = Utilities.GetOriginalParagraph(FirstSelectedIndex, currentPargraphBeforeChange, _subtitleAlternate.Paragraphs);
                        if (original != null)
                        {
                            original.StartTime.TotalMilliseconds = p.StartTime.TotalMilliseconds;
                            original.EndTime.TotalMilliseconds = p.EndTime.TotalMilliseconds;
                        }
                    }
                }
            }

            private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
            {
                _lastDoNotPrompt = string.Empty;
                ReloadFromSourceView();
                if (!ContinueNewOrExit())
                {
                    e.Cancel = true;
                }
                else
                {
                    if (_networkSession != null)
                    {
                        try
                        {
                            _networkSession.TimerStop();
                            _networkSession.Leave();
                        }
                        catch
                        {
                        }
                    }

                    if (Configuration.Settings.General.StartRememberPositionAndSize && WindowState != FormWindowState.Minimized)
                    {
                        Configuration.Settings.General.StartPosition = Left + ";" + Top;
                        if (WindowState == FormWindowState.Maximized)
                            Configuration.Settings.General.StartSize = "Maximized";
                        else
                            Configuration.Settings.General.StartSize = Width + ";" + Height;

                        Configuration.Settings.General.SplitContainerMainSplitterDistance = splitContainerMain.SplitterDistance;
                        Configuration.Settings.General.SplitContainer1SplitterDistance = splitContainer1.SplitterDistance;
                        Configuration.Settings.General.SplitContainerListViewAndTextSplitterDistance = splitContainerListViewAndText.SplitterDistance;
                    }
                    Configuration.Settings.General.AutoRepeatOn = checkBoxAutoRepeatOn.Checked;
                    int autoRepeat;
                    if (int.TryParse(comboBoxAutoRepeat.Text, out autoRepeat))
                        Configuration.Settings.General.AutoRepeatCount = autoRepeat;
                    Configuration.Settings.General.AutoContinueOn = checkBoxAutoContinue.Checked;
                    Configuration.Settings.General.AutoContinueDelay = comboBoxAutoContinue.SelectedIndex;
                    Configuration.Settings.General.SyncListViewWithVideoWhilePlaying = checkBoxSyncListViewWithVideoWhilePlaying.Checked;
                    if (audioVisualizer != null)
                    {
                        Configuration.Settings.General.ShowWaveform = audioVisualizer.ShowWaveform;
                        Configuration.Settings.General.ShowSpectrogram = audioVisualizer.ShowSpectrogram;
                    }
                    if (Configuration.Settings.General.ShowRecentFiles && !string.IsNullOrEmpty(_fileName))
                        Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);

                    SaveUndockedPositions();
                    SaveListViewWidths();
                    Configuration.Settings.Save();

                    if (mediaPlayer.VideoPlayer != null)
                    {
                        mediaPlayer.PauseAndDisposePlayer();
                    }
                }
            }

            private void SaveListViewWidths()
            {
                if (Configuration.Settings.General.ListViewColumnsRememberSize)
                {
                    if (SubtitleListview1.ColumnIndexNumber >= 0)
                        Configuration.Settings.General.ListViewNumberWidth = SubtitleListview1.Columns[SubtitleListview1.ColumnIndexNumber].Width;

                    if (SubtitleListview1.ColumnIndexStart >= 0)
                        Configuration.Settings.General.ListViewStartWidth = SubtitleListview1.Columns[SubtitleListview1.ColumnIndexStart].Width;

                    if (SubtitleListview1.ColumnIndexEnd >= 0)
                        Configuration.Settings.General.ListViewEndWidth = SubtitleListview1.Columns[SubtitleListview1.ColumnIndexEnd].Width;

                    if (SubtitleListview1.ColumnIndexDuration >= 0)
                        Configuration.Settings.General.ListViewDurationWidth = SubtitleListview1.Columns[SubtitleListview1.ColumnIndexDuration].Width;

                    if (SubtitleListview1.ColumnIndexCps >= 0)
                        Configuration.Settings.General.ListViewCpsWidth = SubtitleListview1.Columns[SubtitleListview1.ColumnIndexCps].Width;

                    if (SubtitleListview1.ColumnIndexWpm >= 0)
                        Configuration.Settings.General.ListViewWpmWidth = SubtitleListview1.Columns[SubtitleListview1.ColumnIndexWpm].Width;

                    if (SubtitleListview1.ColumnIndexText >= 0)
                        Configuration.Settings.General.ListViewTextWidth = SubtitleListview1.Columns[SubtitleListview1.ColumnIndexText].Width;
                }
            }

            private void SaveUndockedPositions()
            {
                if (_videoPlayerUndocked != null && !_videoPlayerUndocked.IsDisposed)
                    Configuration.Settings.General.UndockedVideoPosition = _videoPlayerUndocked.Left + @";" + _videoPlayerUndocked.Top + @";" + _videoPlayerUndocked.Width + @";" + _videoPlayerUndocked.Height;
                if (_waveformUndocked != null && !_waveformUndocked.IsDisposed)
                    Configuration.Settings.General.UndockedWaveformPosition = _waveformUndocked.Left + @";" + _waveformUndocked.Top + @";" + _waveformUndocked.Width + @";" + _waveformUndocked.Height;
                if (_videoControlsUndocked != null && !_videoControlsUndocked.IsDisposed)
                    Configuration.Settings.General.UndockedVideoControlsPosition = _videoControlsUndocked.Left + @";" + _videoControlsUndocked.Top + @";" + _videoControlsUndocked.Width + @";" + _videoControlsUndocked.Height;
            }

            private void ButtonUnBreakClick(object sender, EventArgs e)
            {
                Unbreak();
            }

            private void Unbreak(bool removeNewLineOnly = false)
            {
                _doAutoBreakOnTextChanged = false;

                var textCaretPos = textBoxListViewText.SelectionStart;
                var startText = textBoxListViewText.Text.Substring(0, textCaretPos);
                var numberOfNewLines = Utilities.CountTagInText(startText, Environment.NewLine);
                textCaretPos -= numberOfNewLines;

                if (SubtitleListview1.SelectedItems.Count > 1)
                {
                    MakeHistoryForUndo(_language.BeforeRemoveLineBreaksInSelectedLines);

                    SubtitleListview1.BeginUpdate();
                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        var p = _subtitle.GetParagraphOrDefault(index);
                        if (removeNewLineOnly)
                            p.Text = p.Text.Replace(Environment.NewLine, string.Empty);
                        else
                            p.Text = Utilities.UnbreakLine(p.Text);
                        SubtitleListview1.SetText(index, p.Text);

                        if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                        {
                            var original = Utilities.GetOriginalParagraph(index, p, _subtitleAlternate.Paragraphs);
                            if (original != null)
                            {
                                if (removeNewLineOnly)
                                    original.Text = original.Text.Replace(Environment.NewLine, string.Empty);
                                else
                                    original.Text = Utilities.UnbreakLine(original.Text);
                                SubtitleListview1.SetAlternateText(index, original.Text);
                            }
                        }
                    }
                    SubtitleListview1.EndUpdate();
                    RefreshSelectedParagraph();
                }
                else
                {
                    var fixedText = removeNewLineOnly ? textBoxListViewText.Text.Replace(Environment.NewLine, string.Empty) : Utilities.UnbreakLine(textBoxListViewText.Text);
                    var makeHistory = textBoxListViewText.Text != fixedText;
                    if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                    {
                        var alternateFixedText = Utilities.UnbreakLine(textBoxListViewTextAlternate.Text);
                        if (!makeHistory)
                            makeHistory = textBoxListViewTextAlternate.Text != alternateFixedText;
                        if (makeHistory)
                        {
                            MakeHistoryForUndo(_language.BeforeRemoveLineBreaksInSelectedLines);
                            textBoxListViewText.Text = fixedText;
                        }

                        textBoxListViewTextAlternate.Text = alternateFixedText;
                    }
                    else if (makeHistory)
                    {
                        MakeHistoryForUndo(_language.BeforeRemoveLineBreaksInSelectedLines);
                        textBoxListViewText.Text = fixedText;
                    }
                }

                _doAutoBreakOnTextChanged = true;
                textBoxListViewText.SelectionStart = textCaretPos;
            }

            private void TabControlSubtitleSelectedIndexChanged(object sender, EventArgs e)
            {
                var format = GetCurrentSubtitleFormat();
                if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                {
                    ShowSource();
                    ShowSourceLineNumber();
                    if (textBoxSource.CanFocus)
                        textBoxSource.Focus();

                    // go to correct line in source view
                    if (SubtitleListview1.SelectedItems.Count > 0)
                    {
                        if (format.GetType() == typeof(SubRip))
                        {
                            var p = _subtitle.GetParagraphOrDefault(FirstSelectedIndex);
                            if (p != null)
                            {
                                string tc = p.StartTime + " --> " + p.EndTime;
                                int start = textBoxSource.Text.IndexOf(tc, StringComparison.Ordinal);
                                if (start > 0)
                                {
                                    textBoxSource.SelectionStart = start + tc.Length + Environment.NewLine.Length;
                                    textBoxSource.SelectionLength = 0;
                                    textBoxSource.ScrollToCaret();
                                }
                            }
                        }
                        else if (format.GetType() == typeof(SubStationAlpha) || format.GetType() == typeof(AdvancedSubStationAlpha))
                        {
                            var p = _subtitle.GetParagraphOrDefault(FirstSelectedIndex);
                            if (p != null)
                            {
                                const string timeCodeFormat = "{0}:{1:00}:{2:00}.{3:00}"; // h:mm:ss.cc
                                string startTimeCode = string.Format(timeCodeFormat, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds / 10);
                                string endTimeCode = string.Format(timeCodeFormat, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds / 10);
                                string tc = startTimeCode + "," + endTimeCode;
                                int start = textBoxSource.Text.IndexOf(tc, StringComparison.Ordinal);
                                if (start > 0)
                                {
                                    int start2 = textBoxSource.Text.LastIndexOf("Dialogue:", start, StringComparison.Ordinal);
                                    if (start2 > 0)
                                        start2 = (textBoxSource.Text + Environment.NewLine).IndexOf(Environment.NewLine, start2, StringComparison.Ordinal);
                                    if (start2 > 0)
                                        start = start2;
                                    textBoxSource.SelectionStart = start;
                                    textBoxSource.SelectionLength = 0;
                                    textBoxSource.ScrollToCaret();
                                }
                            }
                        }
                    }
                }
                else
                {
                    ReloadFromSourceView();
                    ShowLineInformationListView();
                    if (SubtitleListview1.CanFocus)
                        SubtitleListview1.Focus();

                    // go to (select + focus) correct line in list view
                    if (textBoxSource.SelectionStart > 0 && textBoxSource.TextLength > 30)
                    {
                        if (format.GetType() == typeof(SubRip))
                        {
                            int pos = textBoxSource.SelectionStart;
                            if (pos + 35 < textBoxSource.TextLength)
                                pos += 35;
                            string s = textBoxSource.Text.Substring(0, pos);
                            int lastTimeCode = s.LastIndexOf(" --> ", StringComparison.Ordinal); // 00:02:26,407 --> 00:02:31,356
                            if (lastTimeCode > 14 && lastTimeCode + 16 >= s.Length)
                            {
                                s = s.Substring(0, lastTimeCode - 5);
                                lastTimeCode = s.LastIndexOf(" --> ", StringComparison.Ordinal);
                            }

                            if (lastTimeCode > 14 && lastTimeCode + 16 < s.Length)
                            {
                                string tc = s.Substring(lastTimeCode - 13, 30).Trim();
                                int index = 0;
                                foreach (var p in _subtitle.Paragraphs)
                                {
                                    if (tc == p.StartTime + " --> " + p.EndTime)
                                    {
                                        SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                                        break;
                                    }
                                    index++;
                                }
                            }
                        }
                        else if (format.GetType() == typeof(SubStationAlpha) || format.GetType() == typeof(AdvancedSubStationAlpha))
                        {
                            int pos = textBoxSource.SelectionStart;
                            string s = textBoxSource.Text;
                            if (pos > 0)
                                pos--;
                            while (pos > 0 && pos + 3 < s.Length && !s.Substring(pos, 3).StartsWith(Environment.NewLine, StringComparison.Ordinal))
                                pos--;
                            s = s.Substring(pos).Trim();
                            int lastTimeCode = s.IndexOf("Dialogue:", StringComparison.Ordinal);

                            if (lastTimeCode >= 0)
                            {
                                string tc = s.Substring(lastTimeCode).Trim();
                                while (tc.Length > 0 && !char.IsDigit(tc[0]))
                                    tc = tc.Remove(0, 1);
                                if (tc.Length > 12)
                                {
                                    tc = tc.Substring(0, 13);
                                    var timeCode = tc.Split(new[] { ':', '.', ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    var realTC = new TimeCode();
                                    try
                                    {
                                        realTC = new TimeCode(int.Parse(timeCode[1]), int.Parse(timeCode[2]), int.Parse(timeCode[3]), int.Parse(timeCode[4]) * 10);
                                    }
                                    catch
                                    {
                                        SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                                        return;
                                    }

                                    int index = 0;
                                    foreach (var p in _subtitle.Paragraphs)
                                    {
                                        if (Math.Abs(realTC.TotalMilliseconds - p.StartTime.TotalMilliseconds) < 50)
                                        {
                                            SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                                            break;
                                        }
                                        index++;
                                    }
                                }
                            }
                        }
                    }
                    else if (textBoxSource.SelectionStart == 0 && textBoxSource.TextLength > 30)
                    {
                        SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                    }
                }
            }

            private void ColorToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {

                    string color;
                    if (GetCurrentSubtitleFormat().GetType() == typeof(Ebu))
                    {
                        using (var form = new EbuColorPicker())
                        {
                            if (form.ShowDialog(this) != DialogResult.OK)
                                return;
                            color = form.Color;
                        }
                    }
                    else
                    {
                        if (colorDialog1.ShowDialog(this) != DialogResult.OK)
                            return;
                        color = Utilities.ColorToHex(colorDialog1.Color);
                    }

                    MakeHistoryForUndo(_language.BeforeSettingColor);
                    foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                    {
                        var p = _subtitle.GetParagraphOrDefault(item.Index);
                        if (p != null)
                        {
                            SetFontColor(p, color);
                            SubtitleListview1.SetText(item.Index, p.Text);
                            if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle && SubtitleListview1.IsAlternateTextColumnVisible)
                            {
                                var original = Utilities.GetOriginalParagraph(item.Index, p, _subtitleAlternate.Paragraphs);
                                if (original != null)
                                {
                                    SetFontColor(original, color);
                                    SubtitleListview1.SetAlternateText(item.Index, original.Text);
                                }
                            }
                        }
                    }
                    RefreshSelectedParagraph();

                }
            }

            private static void SetFontColor(Paragraph p, string color)
            {
                if (p == null)
                    return;

                string s = p.Text;
                if (s.StartsWith("<font ", StringComparison.Ordinal))
                {
                    int end = s.IndexOf('>');
                    if (end > 0)
                    {
                        string f = s.Substring(0, end);

                        if (f.Contains(" face=") && !f.Contains(" color="))
                        {
                            var start = s.IndexOf(" face=", StringComparison.Ordinal);
                            s = s.Insert(start, string.Format(" color=\"{0}\"", color));
                            p.Text = s;
                            return;
                        }

                        var colorStart = f.IndexOf(" color=", StringComparison.Ordinal);
                        if (colorStart >= 0)
                        {
                            if (s.IndexOf('"', colorStart + 8) > 0)
                                end = s.IndexOf('"', colorStart + 8);
                            s = s.Substring(0, colorStart) + string.Format(" color=\"{0}", color) + s.Substring(end);
                            p.Text = s;
                            return;
                        }
                    }
                }

                p.Text = string.Format("<font color=\"{0}\">{1}</font>", color, p.Text);
            }

            private void toolStripMenuItemFont_Click(object sender, EventArgs e)
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    if (fontDialog1.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeSettingFontName);

                        foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                        {
                            var p = _subtitle.GetParagraphOrDefault(item.Index);
                            if (p != null)
                            {
                                SetFontName(p);
                                SubtitleListview1.SetText(item.Index, p.Text);
                                if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle && SubtitleListview1.IsAlternateTextColumnVisible)
                                {
                                    var original = Utilities.GetOriginalParagraph(item.Index, p, _subtitleAlternate.Paragraphs);
                                    if (original != null)
                                    {
                                        SetFontName(original);
                                        SubtitleListview1.SetAlternateText(item.Index, original.Text);
                                    }
                                }
                            }
                        }
                        RefreshSelectedParagraph();
                    }
                }
            }

            private void SetFontName(Paragraph p)
            {
                if (p == null)
                    return;

                string s = p.Text;
                if (s.StartsWith("<font ", StringComparison.Ordinal))
                {
                    var end = s.IndexOf('>');
                    if (end > 0)
                    {
                        var f = s.Substring(0, end);

                        if (f.Contains(" color=") && !f.Contains(" face="))
                        {
                            var start = s.IndexOf(" color=", StringComparison.Ordinal);
                            p.Text = s.Insert(start, string.Format(" face=\"{0}\"", fontDialog1.Font.Name));
                            return;
                        }

                        var faceStart = f.IndexOf(" face=", StringComparison.Ordinal);
                        if (f.Contains(" face="))
                        {
                            if (s.IndexOf('"', faceStart + 7) > 0)
                                end = s.IndexOf('"', faceStart + 7);
                            p.Text = s.Substring(0, faceStart) + string.Format(" face=\"{0}", fontDialog1.Font.Name) + s.Substring(end);
                            return;
                        }
                    }
                }

                p.Text = string.Format("<font face=\"{0}\">{1}</font>", fontDialog1.Font.Name, s);
            }

            private void TypeEffectToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedItems.Count > 0)
                {
                    using (var typewriter = new EffectTypewriter())
                    {
                        typewriter.Initialize(SubtitleListview1.GetSelectedParagraph(_subtitle));

                        if (typewriter.ShowDialog(this) == DialogResult.OK)
                        {
                            MakeHistoryForUndo(_language.BeforeTypeWriterEffect);
                            int lastSelectedIndex = SubtitleListview1.SelectedItems[0].Index;
                            int index = lastSelectedIndex;
                            _subtitle.Paragraphs.RemoveAt(index);
                            bool isframeBased = GetCurrentSubtitleFormat().IsFrameBased;
                            foreach (var p in typewriter.TypewriterParagraphs)
                            {
                                if (isframeBased)
                                {
                                    p.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                                    p.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                                }
                                _subtitle.Paragraphs.Insert(index, p);
                                index++;
                            }
                            _subtitle.Renumber();
                            _subtitleListViewIndex = -1;
                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            SubtitleListview1.SelectIndexAndEnsureVisible(lastSelectedIndex);
                        }
                    }
                }
            }

            private void KarokeeEffectToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedItems.Count > 0)
                {
                    using (var karaoke = new EffectKaraoke())
                    {
                        karaoke.Initialize(SubtitleListview1.GetSelectedParagraph(_subtitle));

                        if (karaoke.ShowDialog(this) == DialogResult.OK)
                        {
                            MakeHistoryForUndo(_language.BeforeKaraokeEffect);
                            int lastSelectedIndex = SubtitleListview1.SelectedItems[0].Index;
                            bool isframeBased = GetCurrentSubtitleFormat().IsFrameBased;

                            int i = SubtitleListview1.SelectedItems.Count - 1;
                            while (i >= 0)
                            {
                                var item = SubtitleListview1.SelectedItems[i];
                                var p = _subtitle.GetParagraphOrDefault(item.Index);
                                if (p != null)
                                {
                                    int index = item.Index;
                                    _subtitle.Paragraphs.RemoveAt(index);
                                    foreach (var kp in karaoke.MakeAnimation(p))
                                    {
                                        if (isframeBased)
                                        {
                                            p.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                                            p.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                                        }
                                        _subtitle.Paragraphs.Insert(index, kp);
                                        index++;
                                    }
                                }
                                i--;
                            }

                            _subtitle.Renumber();
                            _subtitleListViewIndex = -1;
                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            SubtitleListview1.SelectIndexAndEnsureVisible(lastSelectedIndex);
                        }
                    }
                }
            }

            private void MatroskaImportStripMenuItemClick(object sender, EventArgs e)
            {
                openFileDialog1.Title = _language.OpenMatroskaFile;
                openFileDialog1.FileName = string.Empty;
                openFileDialog1.Filter = _language.MatroskaFiles + "|*.mkv;*.mks|" + _languageGeneral.AllFiles + "|*.*";
                if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = Path.GetDirectoryName(openFileDialog1.FileName);
                    ImportSubtitleFromMatroskaFile(openFileDialog1.FileName);
                }
            }

            private void ImportSubtitleFromMatroskaFile(string fileName)
            {
                using (var matroska = new MatroskaFile(fileName))
                {
                    if (matroska.IsValid)
                    {
                        var subtitleList = matroska.GetTracks(true);
                        if (subtitleList.Count == 0)
                        {
                            MessageBox.Show(_language.NoSubtitlesFound);
                        }
                        else if (ContinueNewOrExit())
                        {
                            if (subtitleList.Count > 1)
                            {
                                using (var subtitleChooser = new MatroskaSubtitleChooser("mkv"))
                                {
                                    subtitleChooser.Initialize(subtitleList);
                                    if (_loading)
                                    {
                                        subtitleChooser.Icon = (Icon)this.Icon.Clone();
                                        subtitleChooser.ShowInTaskbar = true;
                                        subtitleChooser.ShowIcon = true;
                                    }
                                    if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                    {
                                        if (LoadMatroskaSubtitle(subtitleList[subtitleChooser.SelectedIndex], matroska, false) &&
                                            (Path.GetExtension(matroska.Path).Equals(".mkv", StringComparison.OrdinalIgnoreCase) ||
                                             Path.GetExtension(matroska.Path).Equals(".mks", StringComparison.OrdinalIgnoreCase)))
                                        {
                                            if (!Configuration.Settings.General.DisableVideoAutoLoading)
                                            {
                                                OpenVideo(matroska.Path);
                                            }
                                        }
                                        else
                                        {
                                            _exitWhenLoaded = _loading;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (LoadMatroskaSubtitle(subtitleList[0], matroska, false) &&
                                    (Path.GetExtension(matroska.Path).Equals(".mkv", StringComparison.OrdinalIgnoreCase) ||
                                     Path.GetExtension(matroska.Path).Equals(".mks", StringComparison.OrdinalIgnoreCase)))
                                {
                                    if (!Configuration.Settings.General.DisableVideoAutoLoading)
                                    {
                                        OpenVideo(matroska.Path);
                                    }
                                }
                                else
                                {
                                    _exitWhenLoaded = _loading;
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(string.Format(_language.NotAValidMatroskaFileX, fileName));
                    }
                }
            }

            private int _lastProgressPercent = -1;
            private void UpdateProgress(long position, long total, string statusMessage)
            {
                var percent = (int)Math.Round(position * 100.0 / total);
                if (percent == _lastProgressPercent)
                {
                    return;
                }

                ShowStatus(string.Format("{0}, {1:0}%", statusMessage, _lastProgressPercent));
                statusStrip1.Refresh();
                TaskbarList.SetProgressValue(Handle, percent, 100);
                if (DateTime.UtcNow.Ticks % 10 == 0)
                {
                    Application.DoEvents();
                }
                _lastProgressPercent = percent;
            }

            private void MatroskaProgress(long position, long total)
            {
                UpdateProgress(position, total, _language.ParsingMatroskaFile);
            }

            private Subtitle LoadMatroskaSubtitleForSync(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska)
            {
                var subtitle = new Subtitle();
                bool isSsa = false;

                if (matroskaSubtitleInfo.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase))
                {
                    return subtitle;
                }
                if (matroskaSubtitleInfo.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase))
                {
                    return subtitle;
                }

                SubtitleFormat format;
                var codecPrivate = matroskaSubtitleInfo.GetCodecPrivate();
                if (codecPrivate.Contains("[script info]", StringComparison.OrdinalIgnoreCase))
                {
                    if (codecPrivate.Contains("[V4 Styles]", StringComparison.OrdinalIgnoreCase))
                        format = new SubStationAlpha();
                    else
                        format = new AdvancedSubStationAlpha();
                    isSsa = true;
                }
                else
                {
                    format = new SubRip();
                }

                var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress);
                TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress);
                if (isSsa)
                {
                    foreach (var p in Utilities.LoadMatroskaSSA(matroskaSubtitleInfo, matroska.Path, format, sub).Paragraphs)
                    {
                        subtitle.Paragraphs.Add(p);
                    }
                }
                else
                {
                    foreach (var p in sub)
                    {
                        subtitle.Paragraphs.Add(new Paragraph(p.GetText(matroskaSubtitleInfo), p.Start, p.End));
                    }
                }
                return subtitle;
            }

            private bool LoadMatroskaSubtitle(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska, bool batchMode)
            {
                if (matroskaSubtitleInfo.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase))
                {
                    if (batchMode)
                        return false;
                    return LoadVobSubFromMatroska(matroskaSubtitleInfo, matroska);
                }
                if (matroskaSubtitleInfo.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase))
                {
                    if (batchMode)
                        return false;
                    return LoadBluRaySubFromMatroska(matroskaSubtitleInfo, matroska);
                }
                if (matroskaSubtitleInfo.CodecId.Equals("S_HDMV/TEXTST", StringComparison.OrdinalIgnoreCase))
                {
                    if (batchMode)
                        return false;
                    return LoadTextSTFromMatroska(matroskaSubtitleInfo, matroska, batchMode);
                }
                if (matroskaSubtitleInfo.CodecId.Equals("S_DVBSUB", StringComparison.OrdinalIgnoreCase))
                {
                    if (batchMode)
                        return false;
                    return LoadDvbFromMatroska(matroskaSubtitleInfo, matroska, batchMode);
                }

                ShowStatus(_language.ParsingMatroskaFile);
                Refresh();
                Cursor.Current = Cursors.WaitCursor;
                var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress);
                TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress);
                Cursor.Current = Cursors.Default;

                MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                _subtitleListViewIndex = -1;
                if (!batchMode)
                    ResetSubtitle();
                _subtitle.Paragraphs.Clear();

                var format = Utilities.LoadMatroskaTextSubtitle(matroskaSubtitleInfo, matroska, sub, _subtitle);

                if (matroskaSubtitleInfo.GetCodecPrivate().Contains("[script info]", StringComparison.OrdinalIgnoreCase))
                {
                    if (_networkSession == null)
                    {
                        SubtitleListview1.ShowExtraColumn(_languageGeneral.Style);
                    }
                }
                else if (_networkSession == null)
                {
                    SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Extra);
                }
                comboBoxSubtitleFormats.SelectedIndexChanged -= ComboBoxSubtitleFormatsSelectedIndexChanged;
                SetCurrentFormat(format);
                comboBoxSubtitleFormats.SelectedIndexChanged += ComboBoxSubtitleFormatsSelectedIndexChanged;
                SetEncoding(Encoding.UTF8);
                ShowStatus(_language.SubtitleImportedFromMatroskaFile);
                _subtitle.Renumber();
                _subtitle.WasLoadedWithFrameNumbers = false;
                if (matroska.Path.EndsWith(".mkv", StringComparison.OrdinalIgnoreCase) || matroska.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
                {
                    _fileName = matroska.Path.Remove(matroska.Path.Length - 4) + GetCurrentSubtitleFormat().Extension;
                    Text = Title + " - " + _fileName;
                }
                else
                {
                    Text = Title;
                }
                _fileDateTime = new DateTime();

                _converted = true;

                if (batchMode)
                    return true;

                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                if (_subtitle.Paragraphs.Count > 0)
                    SubtitleListview1.SelectIndexAndEnsureVisible(0);

                ShowSource();
                return true;
            }

            private bool LoadTextSTFromMatroska(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska, bool batchMode)
            {
                ShowStatus(_language.ParsingMatroskaFile);
                Refresh();
                Cursor.Current = Cursors.WaitCursor;
                var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress);
                TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress);
                Cursor.Current = Cursors.Default;

                MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                _subtitleListViewIndex = -1;
                if (!batchMode)
                    ResetSubtitle();
                _subtitle.Paragraphs.Clear();

                Utilities.LoadMatroskaTextSubtitle(matroskaSubtitleInfo, matroska, sub, _subtitle);
                for (int index = 0; index < sub.Count; index++)
                {
                    try
                    {
                        var msub = sub[index];
                        int idx = -6; // MakeMKV starts at DialogPresentationSegment
                        var data = msub.GetData(matroskaSubtitleInfo);
                        if (VobSubParser.IsPrivateStream2(data, 0))
                            idx = 0; //  starts with MPEG2 private stream 2 (just to be sure)
                        var dps = new TextST.DialogPresentationSegment(data, idx);
                        _subtitle.Paragraphs[index].Text = dps.Text;
                    }
                    catch (Exception exception)
                    {
                        _subtitle.Paragraphs[index].Text = exception.Message;
                    }
                }

                if (_networkSession == null)
                {
                    SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Extra);
                }
                comboBoxSubtitleFormats.SelectedIndexChanged -= ComboBoxSubtitleFormatsSelectedIndexChanged;
                SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                comboBoxSubtitleFormats.SelectedIndexChanged += ComboBoxSubtitleFormatsSelectedIndexChanged;
                SetEncoding(Encoding.UTF8);
                ShowStatus(_language.SubtitleImportedFromMatroskaFile);
                _subtitle.Renumber();
                _subtitle.WasLoadedWithFrameNumbers = false;
                if (matroska.Path.EndsWith(".mkv", StringComparison.OrdinalIgnoreCase) || matroska.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
                {
                    _fileName = matroska.Path.Remove(matroska.Path.Length - 4);
                    Text = Title + " - " + _fileName;
                }
                else
                {
                    Text = Title;
                }
                _fileDateTime = new DateTime();
                _converted = true;
                if (batchMode)
                    return true;

                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                if (_subtitle.Paragraphs.Count > 0)
                    SubtitleListview1.SelectIndexAndEnsureVisible(0);

                ShowSource();
                return true;
            }

            private bool LoadDvbFromMatroska(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska, bool batchMode)
            {
                ShowStatus(_language.ParsingMatroskaFile);
                Refresh();
                Cursor.Current = Cursors.WaitCursor;
                var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress);
                TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress);
                Cursor.Current = Cursors.Default;

                MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                _subtitleListViewIndex = -1;
                if (!batchMode)
                    ResetSubtitle();
                _subtitle.Paragraphs.Clear();
                var subtitleImages = new List<DvbSubPes>();
                var subtitle = new Subtitle();
                Utilities.LoadMatroskaTextSubtitle(matroskaSubtitleInfo, matroska, sub, _subtitle);
                for (int index = 0; index < sub.Count; index++)
                {
                    try
                    {
                        var msub = sub[index];
                        DvbSubPes pes = null;
                        var data = msub.GetData(matroskaSubtitleInfo);
                        if (data != null && data.Length > 9 && data[0] == 15 && data[1] >= SubtitleSegment.PageCompositionSegment && data[1] <= SubtitleSegment.DisplayDefinitionSegment) // sync byte + segment id
                        {
                            var buffer = new byte[data.Length + 3];
                            Buffer.BlockCopy(data, 0, buffer, 2, data.Length);
                            buffer[0] = 32;
                            buffer[1] = 0;
                            buffer[buffer.Length - 1] = 255;
                            pes = new DvbSubPes(0, buffer);
                        }
                        else if (VobSubParser.IsMpeg2PackHeader(data))
                        {
                            pes = new DvbSubPes(data, Mpeg2Header.Length);
                        }
                        else if (VobSubParser.IsPrivateStream1(data, 0))
                        {
                            pes = new DvbSubPes(data, 0);
                        }
                        else if (data.Length > 9 && data[0] == 32 && data[1] == 0 && data[2] == 14 && data[3] == 16)
                        {
                            pes = new DvbSubPes(0, data);
                        }

                        if (pes == null && subtitle.Paragraphs.Count > 0)
                        {
                            var last = subtitle.Paragraphs[subtitle.Paragraphs.Count - 1];
                            if (last.Duration.TotalMilliseconds < 100)
                            {
                                last.EndTime.TotalMilliseconds = msub.Start;
                                if (last.Duration.TotalMilliseconds > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds)
                                {
                                    last.EndTime.TotalMilliseconds = last.StartTime.TotalMilliseconds + 3000;
                                }
                            }
                        }
                        if (pes != null && pes.PageCompositions != null && pes.PageCompositions.Any(p => p.Regions.Count > 0))
                        {
                            subtitleImages.Add(pes);
                            subtitle.Paragraphs.Add(new Paragraph(string.Empty, msub.Start, msub.End));
                        }
                    }
                    catch
                    {
                        // continue
                    }
                }

                if (subtitleImages.Count == 0)
                {
                    return false;
                }

                for (int index = 0; index < subtitle.Paragraphs.Count; index++)
                {
                    var p = subtitle.Paragraphs[index];
                    if (p.Duration.TotalMilliseconds < 200)
                    {
                        p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + 3000;
                    }
                    var next = subtitle.GetParagraphOrDefault(index + 1);
                    if (next != null && next.StartTime.TotalMilliseconds < p.EndTime.TotalMilliseconds)
                    {
                        p.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                    }
                }

                using (var formSubOcr = new VobSubOcr())
                {
                    formSubOcr.Initialize(subtitle, subtitleImages, Configuration.Settings.VobSubOcr); // TODO: language???
                    if (_loading)
                    {
                        formSubOcr.Icon = (Icon)Icon.Clone();
                        formSubOcr.ShowInTaskbar = true;
                        formSubOcr.ShowIcon = true;
                    }
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        ResetSubtitle();
                        _subtitle.Paragraphs.Clear();
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                            _subtitle.Paragraphs.Add(p);

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.GetFileNameWithoutExtension(matroska.Path);
                        _converted = true;
                        Text = Title;

                        Configuration.Settings.Save();
                        return true;
                    }
                }
                return false;
            }

            public static void CopyStream(Stream input, Stream output)
            {
                var buffer = new byte[128 * 1024];
                int len;
                while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, len);
                }
                output.Flush();
            }

            private bool LoadVobSubFromMatroska(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska)
            {
                if (matroskaSubtitleInfo.ContentEncodingType == 1)
                {
                    MessageBox.Show(_language.NoSupportEncryptedVobSub);
                }

                ShowStatus(_language.ParsingMatroskaFile);
                Refresh();
                Cursor.Current = Cursors.WaitCursor;
                var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress);
                TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress);
                Cursor.Current = Cursors.Default;

                MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                _subtitleListViewIndex = -1;
                _subtitle.Paragraphs.Clear();

                List<VobSubMergedPack> mergedVobSubPacks = new List<VobSubMergedPack>();
                var idx = new Core.VobSub.Idx(matroskaSubtitleInfo.GetCodecPrivate().SplitToLines());
                foreach (var p in sub)
                {
                    mergedVobSubPacks.Add(new VobSubMergedPack(p.GetData(matroskaSubtitleInfo), TimeSpan.FromMilliseconds(p.Start), 32, null));
                    if (mergedVobSubPacks.Count > 0)
                        mergedVobSubPacks[mergedVobSubPacks.Count - 1].EndTime = TimeSpan.FromMilliseconds(p.End);

                    // fix overlapping (some versions of Handbrake makes overlapping time codes - thx Hawke)
                    if (mergedVobSubPacks.Count > 1 && mergedVobSubPacks[mergedVobSubPacks.Count - 2].EndTime > mergedVobSubPacks[mergedVobSubPacks.Count - 1].StartTime)
                        mergedVobSubPacks[mergedVobSubPacks.Count - 2].EndTime = TimeSpan.FromMilliseconds(mergedVobSubPacks[mergedVobSubPacks.Count - 1].StartTime.TotalMilliseconds - 1);
                }

                using (var formSubOcr = new VobSubOcr())
                {
                    formSubOcr.Initialize(mergedVobSubPacks, idx.Palette, Configuration.Settings.VobSubOcr, null); // TODO: language???
                    if (_loading)
                    {
                        formSubOcr.Icon = (Icon)Icon.Clone();
                        formSubOcr.ShowInTaskbar = true;
                        formSubOcr.ShowIcon = true;
                    }
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        ResetSubtitle();
                        _subtitle.Paragraphs.Clear();
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                            _subtitle.Paragraphs.Add(p);

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.GetFileNameWithoutExtension(matroska.Path);
                        _converted = true;
                        Text = Title;

                        Configuration.Settings.Save();
                        return true;
                    }
                }
                return false;
            }

            private bool LoadBluRaySubFromMatroska(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska)
            {
                if (matroskaSubtitleInfo.ContentEncodingType == 1)
                {
                    MessageBox.Show(_language.NoSupportEncryptedVobSub);
                }

                ShowStatus(_language.ParsingMatroskaFile);
                Refresh();
                Cursor.Current = Cursors.WaitCursor;
                var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress);
                TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress);
                Cursor.Current = Cursors.Default;

                int noOfErrors = 0;
                string lastError = string.Empty;
                MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                _subtitleListViewIndex = -1;
                _subtitle.Paragraphs.Clear();
                var subtitles = new List<BluRaySupParser.PcsData>();
                var log = new StringBuilder();
                var clusterStream = new MemoryStream();
                foreach (var p in sub)
                {
                    byte[] buffer = p.GetData(matroskaSubtitleInfo);
                    if (buffer != null && buffer.Length > 2)
                    {
                        clusterStream.Write(buffer, 0, buffer.Length);
                        if (ContainsBluRayStartSegment(buffer))
                        {
                            if (subtitles.Count > 0 && subtitles[subtitles.Count - 1].StartTime == subtitles[subtitles.Count - 1].EndTime)
                            {
                                subtitles[subtitles.Count - 1].EndTime = (long)((p.Start - 1) * 90.0);
                            }
                            clusterStream.Position = 0;
                            var list = BluRaySupParser.ParseBluRaySup(clusterStream, log, true);
                            foreach (var sup in list)
                            {
                                sup.StartTime = (long)((p.Start - 1) * 90.0);
                                sup.EndTime = (long)((p.End - 1) * 90.0);
                                subtitles.Add(sup);

                                // fix overlapping
                                if (subtitles.Count > 1 && sub[subtitles.Count - 2].End > sub[subtitles.Count - 1].Start)
                                    subtitles[subtitles.Count - 2].EndTime = subtitles[subtitles.Count - 1].StartTime - 1;
                            }
                            clusterStream = new MemoryStream();
                        }
                    }
                    else if (subtitles.Count > 0)
                    {
                        var lastSub = subtitles[subtitles.Count - 1];
                        if (lastSub.StartTime == lastSub.EndTime)
                        {
                            lastSub.EndTime = (long)((p.Start - 1) * 90.0);
                            if (lastSub.EndTime - lastSub.StartTime > 1000000)
                                lastSub.EndTime = lastSub.StartTime;
                        }
                    }
                }

                if (noOfErrors > 0)
                {
                    MessageBox.Show(string.Format("{0} error(s) occurred during extraction of bdsup\r\n\r\n{1}", noOfErrors, lastError));
                }

                using (var formSubOcr = new VobSubOcr())
                {
                    formSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, matroska.Path);
                    if (_loading)
                    {
                        formSubOcr.Icon = (Icon)Icon.Clone();
                        formSubOcr.ShowInTaskbar = true;
                        formSubOcr.ShowIcon = true;
                    }
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle);

                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = string.Empty;
                        Text = Title;

                        Configuration.Settings.Save();
                        return true;
                    }
                }
                return false;
            }

            private bool ContainsBluRayStartSegment(byte[] buffer)
            {
                const int epochStart = 0x80;
                var position = 0;
                while (position + 3 <= buffer.Length)
                {
                    var segmentType = buffer[position];
                    if (segmentType == epochStart)
                        return true;
                    int length = BluRaySupParser.BigEndianInt16(buffer, position + 1) + 3;
                    position += length;
                }
                return false;
            }

            private void ImportSubtitleFromDvbSupFile(string fileName)
            {
                using (var formSubOcr = new VobSubOcr())
                {
                    var subtitles = TransportStreamParser.GetDvbSup(fileName);
                    formSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName);
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle);

                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = string.Empty;
                        Text = Title;

                        Configuration.Settings.Save();
                    }
                }
            }

            private bool ImportSubtitleFromTransportStream(string fileName)
            {
                ShowStatus(_language.ParsingTransportStream);
                Refresh();
                var tsParser = new TransportStreamParser();
                tsParser.Parse(fileName, (pos, total) => UpdateProgress(pos, total, _language.ParsingTransportStreamFile));
                ShowStatus(string.Empty);
                TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress);

                if (tsParser.SubtitlePacketIds.Count == 0)
                {
                    MessageBox.Show(_language.NoSubtitlesFound);
                    _exitWhenLoaded = _loading;
                    return false;
                }

                int packedId = tsParser.SubtitlePacketIds[0];
                if (tsParser.SubtitlePacketIds.Count > 1)
                {
                    using (var subChooser = new TransportStreamSubtitleChooser())
                    {
                        subChooser.Initialize(tsParser, fileName);
                        if (subChooser.ShowDialog(this) == DialogResult.Cancel)
                            return false;
                        packedId = tsParser.SubtitlePacketIds[subChooser.SelectedIndex];
                    }
                }
                var subtitles = tsParser.GetDvbSubtitles(packedId);

                using (var formSubOcr = new VobSubOcr())
                {
                    formSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName);
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle);

                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = string.Empty;
                        if (!string.IsNullOrEmpty(formSubOcr.FileName))
                        {
                            _fileName = Path.GetFileNameWithoutExtension(formSubOcr.FileName);
                            _converted = true;
                        }
                        Text = Title;

                        Configuration.Settings.Save();
                        return true;
                    }
                    _exitWhenLoaded = _loading;
                    return false;
                }
            }

            #region Teletext

            /*
            private readonly static String[] colors = {
            "{\\c&HC0C0C0&}",   // black /gray
            "{\\c&H4040FF&}",   // red
            "{\\c&H00FF00&}",   // green
            "{\\c&H00FFFF&}",   // yellow
            "{\\c&HFF409B&}",   // blue //DM15032004 081.6 int18 changed
            "{\\c&HFF00FF&}",   // magenta
            "{\\c&HFFFF00&}",   // cyan
            "{\\c&HFFFFFF&}",   // white
            };

            public static byte ByteReverse(byte n)
            {
                n = (byte)(((n >> 1) & 0x55) | ((n << 1) & 0xaa));
                n = (byte)(((n >> 2) & 0x33) | ((n << 2) & 0xcc));
                n = (byte)(((n >> 4) & 0x0f) | ((n << 4) & 0xf0));
                return n;
            }

            private static string GetTeletext(byte[] _buffer, int offset)
            {
                string text = string.Empty;
                bool ascii = false;
                const int color = 0;
                bool toggle = false;
                for (int c = offset, i = 0; c < _buffer.Length; c++, i++)
                {
                    //var char_value = _buffer[c];

                    var char_value = 0x7F & ByteReverse(_buffer[c]);

                    if (char_value >> 3 == 0) //0x0..7
                    {
                        ascii = true;
                        text += ((color == 1) ? colors[char_value] : string.Empty); // + (char)active_set[32];
                    }
                    else if (char_value >> 4 == 0) //0x8..F
                    {
                        text += " "; //(char)active_set[32];
                    }
                    else if (char_value >> 7 == 1) //0x80..FF
                    {
                        text += " "; //(char)active_set[32];
                    }
                    else if (char_value < 27) //0x10..1A
                    {
                        ascii = false;
                        text += " "; //(char)active_set[32];
                    }
                    else if (char_value < 32) //0x1B..1F
                    {
                        if (char_value == 0x1B) //ESC
                        {
                            if (toggle)
                            {
                                //  active_set = CharSet.getActive_G0_Set(primary_set_mapping, primary_national_set_mapping, row);
                                //  active_national_set = CharSet.getActiveNationalSubset(primary_set_mapping, primary_national_set_mapping, row);
                            }
                            else
                            {
                                //active_set = CharSet.getActive_G0_Set(secondary_set_mapping, secondary_national_set_mapping, row);
                                //active_national_set = CharSet.getActiveNationalSubset(secondary_set_mapping, secondary_national_set_mapping, row);
                            }
                            toggle = !toggle;
                        }

                        text += " "; //(char)active_set[32];
                        continue;
                    }
                    else if (char_value == 0x7F) //0x7F
                    {
                        text += " "; // (char)active_set[32];
                        continue;
                    }

                    if (!ascii)
                    {
                        text += " "; // (char)active_set[32];
                        continue;
                    }

                    //if (active_national_set != null)
                    //{
                    //    // all chars 0x20..7F
                    //    switch (char_value) // special national characters
                    //    {
                    //        case 0x23:
                    //            text += (char)active_national_set[0];
                    //            continue loopi;
                    //        case 0x24:
                    //            text += (char)active_national_set[1];
                    //            continue loopi;
                    //        case 0x40:
                    //            text += (char)active_national_set[2];
                    //            continue loopi;
                    //        case 0x5b:
                    //            text += (char)active_national_set[3];
                    //            continue loopi;
                    //        case 0x5c:
                    //            text += (char)active_national_set[4];
                    //            continue loopi;
                    //        case 0x5d:
                    //            text += (char)active_national_set[5];
                    //            continue loopi;
                    //        case 0x5e:
                    //            text += (char)active_national_set[6];
                    //            continue loopi;
                    //        case 0x5f:
                    //            text += (char)active_national_set[7];
                    //            continue loopi;
                    //        case 0x60:
                    //            text += (char)active_national_set[8];
                    //            continue loopi;
                    //        case 0x7b:
                    //            text += (char)active_national_set[9];
                    //            continue loopi;
                    //        case 0x7c:
                    //            text += (char)active_national_set[10];
                    //            continue loopi;
                    //        case 0x7d:
                    //            text += (char)active_national_set[11];
                    //            continue loopi;
                    //        case 0x7e:
                    //            text += (char)active_national_set[12];
                    //            continue loopi;
                    //    }
                    //}

                    text += Encoding.Default.GetString(new byte[] { (byte)char_value }); //(char)active_set[char_value];
                    //continue loopi;
                }

                if (color == 1)
                    return colors[7] + text.Trim();
                else
                    return text;
            }
            */

            #endregion Teletext

            private bool ImportSubtitleFromMp4(string fileName)
            {
                var mp4Parser = new MP4Parser(fileName);
                var mp4SubtitleTracks = mp4Parser.GetSubtitleTracks();
                if (mp4SubtitleTracks.Count == 0)
                {
                    MessageBox.Show(_language.NoSubtitlesFound);
                    return false;
                }
                else if (mp4SubtitleTracks.Count == 1)
                {
                    LoadMp4Subtitle(fileName, mp4SubtitleTracks[0]);
                    return true;
                }
                else
                {
                    using (var subtitleChooser = new MatroskaSubtitleChooser("mp4"))
                    {
                        subtitleChooser.Initialize(mp4SubtitleTracks);
                        if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                        {
                            LoadMp4Subtitle(fileName, mp4SubtitleTracks[subtitleChooser.SelectedIndex]);
                            return true;
                        }
                    }
                    return false;
                }
            }

            private bool ImportSubtitleFromDivX(string fileName)
            {
                var count = 0;
                var list = new List<XSub>();
                using (var f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var searchBuffer = new byte[2048];
                    long pos = 0;
                    long length = f.Length - 50;
                    while (pos < length)
                    {
                        f.Position = pos;
                        int readCount = f.Read(searchBuffer, 0, searchBuffer.Length);
                        for (int i = 0; i < readCount; i++)
                        {
                            if (searchBuffer[i] != 0x5b || (i + 4 < readCount && (searchBuffer[i + 1] < 0x30 || searchBuffer[i + 1] > 0x39 || searchBuffer[i + 3] != 0x3a)))
                            {
                                continue;
                            }

                            f.Position = pos + i + 1;

                            var buffer = new byte[26];
                            f.Read(buffer, 0, buffer.Length);

                            if (buffer[2] == 0x3a && // :
                                buffer[5] == 0x3a && // :
                                buffer[8] == 0x2e && // .
                                buffer[12] == 0x2d && // -
                                buffer[15] == 0x3a && // :
                                buffer[18] == 0x3a && // :
                                buffer[21] == 0x2e && // .
                                buffer[25] == 0x5d)   // ]
                            { // subtitle time code
                                string timeCode = Encoding.ASCII.GetString(buffer, 0, 25);

                                f.Read(buffer, 0, 2);
                                int width = BitConverter.ToUInt16(buffer, 0);
                                f.Read(buffer, 0, 2);
                                int height = BitConverter.ToUInt16(buffer, 0);
                                f.Read(buffer, 0, 2);
                                int x = BitConverter.ToUInt16(buffer, 0);
                                f.Read(buffer, 0, 2);
                                int y = BitConverter.ToUInt16(buffer, 0);
                                f.Read(buffer, 0, 2);
                                int xEnd = BitConverter.ToUInt16(buffer, 0);
                                f.Read(buffer, 0, 2);
                                int yEnd = BitConverter.ToUInt16(buffer, 0);
                                f.Read(buffer, 0, 2);
                                int RleLength = BitConverter.ToUInt16(buffer, 0);

                                var colorBuffer = new byte[4 * 3]; // four colors with rgb (3 bytes)
                                f.Read(colorBuffer, 0, colorBuffer.Length);

                                buffer = new byte[RleLength];
                                int bytesRead = f.Read(buffer, 0, buffer.Length);

                                if (width > 0 && height > 0 && bytesRead == buffer.Length)
                                {
                                    var xSub = new XSub(timeCode, width, height, colorBuffer, buffer);
                                    list.Add(xSub);
                                    count++;
                                }
                            }
                        }
                        pos += searchBuffer.Length;
                    }
                }

                if (count == 0)
                {
                    return false;
                }

                using (var formSubOcr = new VobSubOcr())
                {
                    formSubOcr.Initialize(list, Configuration.Settings.VobSubOcr, fileName); // TODO: language???
                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                        _subtitleListViewIndex = -1;
                        FileNew();
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                            _subtitle.Paragraphs.Add(p);

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.GetFileNameWithoutExtension(fileName);
                        _converted = true;
                        Text = Title;

                        Configuration.Settings.Save();
                        if (!Configuration.Settings.General.DisableVideoAutoLoading)
                        {
                            OpenVideo(fileName);
                        }
                    }
                }
                return true;
            }

            private static Subtitle LoadMp4SubtitleForSync(Trak mp4SubtitleTrack)
            {
                var subtitle = new Subtitle();
                if (mp4SubtitleTrack.Mdia.IsVobSubSubtitle)
                {
                    return subtitle;
                }
                else
                {
                    for (int i = 0; i < mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes.Count; i++)
                    {
                        if (mp4SubtitleTrack.Mdia.Minf.Stbl.Texts.Count > i)
                        {
                            var start = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.StartTimeCodes[i]);
                            var end = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes[i]);
                            string text = mp4SubtitleTrack.Mdia.Minf.Stbl.Texts[i];
                            var p = new Paragraph(text, start.TotalMilliseconds, end.TotalMilliseconds);
                            if (p.EndTime.TotalMilliseconds - p.StartTime.TotalMilliseconds > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds)
                                p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds;

                            if (mp4SubtitleTrack.Mdia.IsClosedCaption && string.IsNullOrEmpty(text))
                            {
                                // do not add empty lines
                            }
                            else
                            {
                                subtitle.Paragraphs.Add(p);
                            }
                        }
                    }
                }
                return subtitle;
            }

            private void LoadMp4Subtitle(string fileName, Trak mp4SubtitleTrack)
            {
                if (mp4SubtitleTrack.Mdia.IsVobSubSubtitle)
                {
                    var subPicturesWithTimeCodes = new List<VobSubOcr.SubPicturesWithSeparateTimeCodes>();
                    for (int i = 0; i < mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes.Count; i++)
                    {
                        if (mp4SubtitleTrack.Mdia.Minf.Stbl.SubPictures.Count > i)
                        {
                            var start = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.StartTimeCodes[i]);
                            var end = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes[i]);
                            subPicturesWithTimeCodes.Add(new VobSubOcr.SubPicturesWithSeparateTimeCodes(mp4SubtitleTrack.Mdia.Minf.Stbl.SubPictures[i], start, end));
                        }
                    }

                    using (var formSubOcr = new VobSubOcr())
                    {
                        formSubOcr.Initialize(subPicturesWithTimeCodes, Configuration.Settings.VobSubOcr, fileName); // TODO: language???
                        if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                        {
                            MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                            _subtitleListViewIndex = -1;
                            FileNew();
                            _subtitle.WasLoadedWithFrameNumbers = false;
                            foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                                _subtitle.Paragraphs.Add(p);

                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            _subtitleListViewIndex = -1;
                            SubtitleListview1.FirstVisibleIndex = -1;
                            SubtitleListview1.SelectIndexAndEnsureVisible(0);

                            _fileName = Path.GetFileNameWithoutExtension(fileName);
                            _converted = true;
                            Text = Title;

                            Configuration.Settings.Save();
                        }
                    }
                }
                else
                {
                    MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                    _subtitleListViewIndex = -1;
                    FileNew();

                    for (int i = 0; i < mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes.Count; i++)
                    {
                        if (mp4SubtitleTrack.Mdia.Minf.Stbl.Texts.Count > i)
                        {
                            var start = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.StartTimeCodes[i]);
                            var end = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes[i]);
                            string text = mp4SubtitleTrack.Mdia.Minf.Stbl.Texts[i];
                            var p = new Paragraph(text, start.TotalMilliseconds, end.TotalMilliseconds);
                            if (p.EndTime.TotalMilliseconds - p.StartTime.TotalMilliseconds > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds)
                                p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds;

                            if (mp4SubtitleTrack.Mdia.IsClosedCaption && string.IsNullOrEmpty(text))
                            {
                                // do not add empty lines
                            }
                            else
                            {
                                _subtitle.Paragraphs.Add(p);
                            }
                        }
                    }

                    SetEncoding(Encoding.UTF8);
                    ShowStatus(_language.SubtitleImportedFromMatroskaFile);
                    _subtitle.Renumber();
                    _subtitle.WasLoadedWithFrameNumbers = false;
                    if (fileName.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase) || fileName.EndsWith(".m4v", StringComparison.OrdinalIgnoreCase))
                    {
                        _fileName = fileName.Substring(0, fileName.Length - 4);
                        Text = Title + " - " + _fileName;
                    }
                    else
                    {
                        Text = Title;
                    }
                    _fileDateTime = new DateTime();

                    _converted = true;

                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    if (_subtitle.Paragraphs.Count > 0)
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);
                    ShowSource();
                }
            }

            private void SubtitleListview1_DragEnter(object sender, DragEventArgs e)
            {
                // make sure they're actually dropping files (not text or anything else)
                if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
                    e.Effect = DragDropEffects.All;
            }

            private void SubtitleListview1_DragDrop(object sender, DragEventArgs e)
            {
                _dragAndDropFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (_dragAndDropFiles.Length == 1)
                {
                    _dragAndDropTimer.Start();
                }
                else
                {
                    MessageBox.Show(_language.DropOnlyOneFile);
                }
            }

            private void DoSubtitleListview1Drop(object sender, EventArgs e)
            {
                _dragAndDropTimer.Stop();

                if (ContinueNewOrExit())
                {
                    string fileName = _dragAndDropFiles[0];
                    var file = new FileInfo(fileName);

                    // Do not allow directory drop
                    if (FileUtil.IsDirectory(fileName))
                    {
                        MessageBox.Show(_language.ErrorDirectoryDropNotAllowed, file.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    var dirName = Path.GetDirectoryName(fileName);
                    saveFileDialog1.InitialDirectory = dirName;
                    openFileDialog1.InitialDirectory = dirName;
                    var ext = file.Extension.ToLowerInvariant();

                    if (ext == ".mkv" || ext == ".mks")
                    {
                        using (var matroska = new MatroskaFile(fileName))
                        {
                            if (matroska.IsValid)
                            {
                                var subtitleList = matroska.GetTracks(true);
                                if (subtitleList.Count == 0)
                                {
                                    MessageBox.Show(_language.NoSubtitlesFound);
                                }
                                else if (subtitleList.Count > 1)
                                {
                                    using (var subtitleChooser = new MatroskaSubtitleChooser("mkv"))
                                    {
                                        subtitleChooser.Initialize(subtitleList);
                                        if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                        {
                                            if (LoadMatroskaSubtitle(subtitleList[subtitleChooser.SelectedIndex], matroska, false) &&
                                                (ext.Equals(".mkv", StringComparison.Ordinal) || ext.Equals(".mks", StringComparison.Ordinal)) &&
                                                !Configuration.Settings.General.DisableVideoAutoLoading)
                                            {
                                                OpenVideo(fileName);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    if (LoadMatroskaSubtitle(subtitleList[0], matroska, false) &&
                                        (ext.Equals(".mkv", StringComparison.Ordinal) || ext.Equals(".mks", StringComparison.Ordinal)) &&
                                        !Configuration.Settings.General.DisableVideoAutoLoading)
                                    {
                                        OpenVideo(fileName);
                                    }
                                }
                                return;
                            }
                        }
                    }
                    else if (ext == ".mp4" || ext == ".m4v" || ext == ".3gp")
                    {
                        var mp4Parser = new MP4Parser(fileName);
                        var mp4SubtitleTracks = mp4Parser.GetSubtitleTracks();
                        if (mp4SubtitleTracks.Count > 0)
                        {
                            ImportSubtitleFromMp4(fileName);
                            return;
                        }
                    }
                    else if (ext == ".vob" || ext == ".ifo")
                    {
                        ImportDvdSubtitle(fileName);
                        return;
                    }
                    else if (ext == ".idx")
                    {
                        var subFileName = fileName.Substring(0, fileName.Length - 3) + "sub";
                        if (File.Exists(subFileName) && FileUtil.IsVobSub(subFileName))
                        {
                            ImportAndOcrVobSubSubtitleNew(subFileName, _loading);
                            return;
                        }
                    }

                    if (file.Length < Subtitle.MaxFileSize)
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else if (file.Length < 150000000 && ext == ".sub" && IsVobSubFile(fileName, true)) // max 150 mb
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else if (file.Length < 250000000 && ext == ".sup" && FileUtil.IsBluRaySup(fileName)) // max 250 mb
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else if ((ext == ".ts" || ext == ".rec" || ext == ".mpg" || ext == ".mpeg") && FileUtil.IsTransportStream(fileName))
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else if (ext == ".m2ts" && FileUtil.IsM2TransportStream(fileName))
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else
                    {
                        MessageBox.Show(string.Format(_language.DropFileXNotAccepted, fileName));
                    }
                }
            }

            private void TextBoxSourceDragEnter(object sender, DragEventArgs e)
            {
                // make sure they're actually dropping files (not text or anything else)
                if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
                    e.Effect = DragDropEffects.All;
            }

            private void TextBoxSourceDragDrop(object sender, DragEventArgs e)
            {
                var files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files.Length == 1)
                {
                    if (ContinueNewOrExit())
                    {
                        OpenSubtitle(files[0], null);
                    }
                }
                else
                {
                    MessageBox.Show(_language.DropOnlyOneFile);
                }
            }

            private void ToolStripMenuItemManualAnsiClick(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                openFileDialog1.Title = _language.OpenAnsiSubtitle;
                openFileDialog1.FileName = string.Empty;
                openFileDialog1.Filter = UiUtil.SubtitleExtensionFilter.Value;
                if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    var chooseEncoding = new ChooseEncoding();
                    chooseEncoding.Initialize(openFileDialog1.FileName);
                    if (chooseEncoding.ShowDialog(this) == DialogResult.OK)
                    {
                        Encoding encoding = chooseEncoding.GetEncoding();
                        SetEncoding(Encoding.UTF8);
                        OpenSubtitle(openFileDialog1.FileName, encoding);
                        _converted = true;
                    }
                }
            }

            private void ChangeCasingToolStripMenuItem_Click(object sender, EventArgs e)
            {
                ChangeCasing(false);
            }

            private void ChangeCasing(bool onlySelectedLines)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                SaveSubtitleListviewIndices();
                using (var changeCasing = new ChangeCasing())
                {
                    if (onlySelectedLines)
                        changeCasing.Text += " - " + _language.SelectedLines;
                    ReloadFromSourceView();
                    if (changeCasing.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeChangeCasing);

                        Cursor.Current = Cursors.WaitCursor;
                        var selectedLines = new Subtitle();
                        selectedLines.WasLoadedWithFrameNumbers = _subtitle.WasLoadedWithFrameNumbers;
                        if (onlySelectedLines)
                        {
                            foreach (int index in SubtitleListview1.SelectedIndices)
                                selectedLines.Paragraphs.Add(new Paragraph(_subtitle.Paragraphs[index]));
                        }
                        else
                        {
                            foreach (var p in _subtitle.Paragraphs)
                                selectedLines.Paragraphs.Add(new Paragraph(p));
                        }

                        bool saveChangeCaseChanges = true;
                        var casingNamesLinesChanged = 0;
                        changeCasing.FixCasing(selectedLines, LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle));
                        if (changeCasing.ChangeNamesToo)
                        {
                            using (var changeCasingNames = new ChangeCasingNames())
                            {
                                changeCasingNames.Initialize(selectedLines);
                                if (changeCasingNames.ShowDialog(this) == DialogResult.OK)
                                {
                                    changeCasingNames.FixCasing();
                                    casingNamesLinesChanged = changeCasingNames.LinesChanged;

                                    if (changeCasing.LinesChanged == 0)
                                        ShowStatus(string.Format(_language.CasingCompleteMessageOnlyNames, casingNamesLinesChanged, _subtitle.Paragraphs.Count));
                                    else
                                        ShowStatus(string.Format(_language.CasingCompleteMessage, changeCasing.LinesChanged, _subtitle.Paragraphs.Count, casingNamesLinesChanged));
                                }
                                else
                                {
                                    saveChangeCaseChanges = false;
                                }
                            }
                        }
                        else
                        {
                            ShowStatus(string.Format(_language.CasingCompleteMessageNoNames, changeCasing.LinesChanged, _subtitle.Paragraphs.Count));
                        }

                        if (saveChangeCaseChanges)
                        {
                            if (onlySelectedLines)
                            {
                                int i = 0;
                                foreach (int index in SubtitleListview1.SelectedIndices)
                                {
                                    _subtitle.Paragraphs[index].Text = selectedLines.Paragraphs[i].Text;
                                    i++;
                                }
                            }
                            else
                            {
                                for (int i = 0; i < _subtitle.Paragraphs.Count; i++)
                                {
                                    _subtitle.Paragraphs[i].Text = selectedLines.Paragraphs[i].Text;
                                }
                            }
                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            if (changeCasing.LinesChanged > 0 || casingNamesLinesChanged > 0)
                            {
                                _subtitleListViewIndex = -1;
                                RestoreSubtitleListviewIndices();
                                UpdateSourceView();
                            }
                        }
                        Cursor.Current = Cursors.Default;
                    }
                }
            }

            private void ToolStripMenuItemChangeFrameRateClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                int lastSelectedIndex = 0;
                if (SubtitleListview1.SelectedItems.Count > 0)
                    lastSelectedIndex = SubtitleListview1.SelectedItems[0].Index;

                ReloadFromSourceView();
                using (var changeFrameRate = new ChangeFrameRate())
                {
                    changeFrameRate.Initialize(CurrentFrameRate.ToString());
                    if (changeFrameRate.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeChangeFrameRate);

                        double oldFrameRate = changeFrameRate.OldFrameRate;
                        double newFrameRate = changeFrameRate.NewFrameRate;
                        _subtitle.ChangeFrameRate(oldFrameRate, newFrameRate);

                        ShowStatus(string.Format(_language.FrameRateChangedFromXToY, oldFrameRate, newFrameRate));
                        toolStripComboBoxFrameRate.Text = newFrameRate.ToString();

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(lastSelectedIndex);
                    }
                }
            }

            private bool IsVobSubFile(string subFileName, bool verbose)
            {
                try
                {
                    if (FileUtil.IsVobSub(subFileName))
                    {
                        if (!verbose)
                            return true;

                        var idxFileName = Path.Combine(Path.GetDirectoryName(subFileName), Path.GetFileNameWithoutExtension(subFileName) + ".idx");
                        if (File.Exists(idxFileName))
                            return true;

                        var dr = MessageBox.Show(string.Format(_language.IdxFileNotFoundWarning, idxFileName), _title, MessageBoxButtons.YesNo);
                        return dr == DialogResult.Yes;
                    }
                    if (verbose)
                        MessageBox.Show(string.Format(_language.InvalidVobSubHeader, subFileName));
                }
                catch (Exception ex)
                {
                    if (verbose)
                        MessageBox.Show(ex.Message);
                }
                return false;
            }

            private void ImportAndOcrSpDvdSup(string fileName, bool showInTaskbar)
            {
                var spList = new List<SpHeader>();

                using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var buffer = new byte[SpHeader.SpHeaderLength];
                    int bytesRead = fs.Read(buffer, 0, buffer.Length);
                    var header = new SpHeader(buffer);

                    while (header.Identifier == "SP" && bytesRead > 0 && header.NextBlockPosition > 4)
                    {
                        buffer = new byte[header.NextBlockPosition];
                        bytesRead = fs.Read(buffer, 0, buffer.Length);
                        if (bytesRead == buffer.Length)
                        {
                            header.AddPicture(buffer);
                            spList.Add(header);
                        }

                        buffer = new byte[SpHeader.SpHeaderLength];
                        bytesRead = fs.Read(buffer, 0, buffer.Length);
                        header = new SpHeader(buffer);
                    }
                }

                using (var vobSubOcr = new VobSubOcr())
                {
                    if (showInTaskbar)
                    {
                        vobSubOcr.Icon = (Icon)this.Icon.Clone();
                        vobSubOcr.ShowInTaskbar = true;
                        vobSubOcr.ShowIcon = true;
                    }
                    vobSubOcr.Initialize(fileName, null, Configuration.Settings.VobSubOcr, spList);
                    if (vobSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingVobSubFile);
                        FileNew();
                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in vobSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.ChangeExtension(vobSubOcr.FileName, new SubRip().Extension);
                        SetTitle();
                        _converted = true;

                        Configuration.Settings.Save();
                    }
                }
            }

            private void ImportAndOcrVobSubSubtitleNew(string fileName, bool showInTaskbar)
            {
                if (!IsVobSubFile(fileName, true))
                {
                    return;
                }

                using (var vobSubOcr = new VobSubOcr())
                {
                    if (showInTaskbar)
                    {
                        vobSubOcr.Icon = (Icon)Icon.Clone();
                        vobSubOcr.ShowInTaskbar = true;
                        vobSubOcr.ShowIcon = true;
                    }
                    if (vobSubOcr.Initialize(fileName, Configuration.Settings.VobSubOcr, this) && vobSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingVobSubFile);
                        FileNew();
                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in vobSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.ChangeExtension(vobSubOcr.FileName, new SubRip().Extension);
                        SetTitle();
                        _converted = true;

                        Configuration.Settings.Save();
                    }
                    else
                    {
                        _exitWhenLoaded = _loading;
                    }
                }
            }

            private void ToolStripMenuItemMergeLinesClick(object sender, EventArgs e)
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count >= 1)
                    MergeAfterToolStripMenuItemClick(null, null);
            }

            private void VisualSyncSelectedLinesToolStripMenuItemClick(object sender, EventArgs e)
            {
                ShowVisualSync(true);
            }

            private void GoogleTranslateSelectedLinesToolStripMenuItemClick(object sender, EventArgs e)
            {
                TranslateViaGoogle(true, true);
            }

            private void SaveSubtitleListviewIndices()
            {
                _selectedIndices = new List<int>();
                foreach (int index in SubtitleListview1.SelectedIndices)
                    _selectedIndices.Add(index);
            }

            private void RestoreSubtitleListviewIndices()
            {
                _subtitleListViewIndex = -1;
                if (_selectedIndices != null)
                {
                    SubtitleListview1.SelectNone();
                    int i = 0;
                    foreach (int index in _selectedIndices)
                    {
                        if (index >= 0 && index < SubtitleListview1.Items.Count)
                        {
                            SubtitleListview1.Items[index].Selected = true;
                            if (i == 0)
                                SubtitleListview1.Items[index].EnsureVisible();
                        }
                        i++;
                    }
                }
            }

            private void ShowSelectedLinesEarlierlaterToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                if (_showEarlierOrLater != null && !_showEarlierOrLater.IsDisposed)
                {
                    _showEarlierOrLater.WindowState = FormWindowState.Normal;
                    _showEarlierOrLater.Focus();
                    return;
                }

                bool waveformEnabled = timerWaveform.Enabled;
                timerWaveform.Stop();
                timer1.Stop();

                _showEarlierOrLater = new ShowEarlierLater();
                if (!_showEarlierOrLater.IsPositionAndSizeSaved)
                {
                    _showEarlierOrLater.Top = Top + 100;
                    _showEarlierOrLater.Left = Left + (Width / 2) - (_showEarlierOrLater.Width / 3);
                }
                _showEarlierOrLater.Initialize(ShowEarlierOrLater, true);
                MakeHistoryForUndo(_language.BeforeShowSelectedLinesEarlierLater);
                _showEarlierOrLater.Show(this);

                timerWaveform.Enabled = waveformEnabled;
                timer1.Start();

                RefreshSelectedParagraph();
            }

            public static Control FindFocusedControl(Control control)
            {
                var container = control as ContainerControl;
                while (container != null)
                {
                    control = container.ActiveControl;
                    container = control as ContainerControl;
                }
                return control;
            }

            internal void MainKeyDown(object sender, KeyEventArgs e)
            {
                if (e.Modifiers == Keys.Alt && e.KeyCode == (Keys.RButton | Keys.ShiftKey) && textBoxListViewText.Focused)
                { // annoying that focus leaves textbox while typing, when pressing Alt alone
                    e.SuppressKeyPress = true;
                    return;
                }

                if (e.Modifiers == Keys.Alt && e.KeyCode == (Keys.RButton | Keys.ShiftKey))
                    return;

                if (e.Modifiers == Keys.Shift && e.KeyCode == Keys.ShiftKey)
                    return;
                if (e.Modifiers == Keys.Control && e.KeyCode == (Keys.LButton | Keys.ShiftKey))
                    return;
                if (e.Modifiers == (Keys.Control | Keys.Shift) && e.KeyCode == Keys.ShiftKey)
                    return;

                var fc = FindFocusedControl(this);
                if (fc != null && e.Modifiers != Keys.Control && e.Modifiers != (Keys.Control | Keys.Shift) && e.Modifiers != (Keys.Control | Keys.Shift | Keys.Alt))
                {
                    // do not check for shortcuts if text is being entered and a textbox is focused
                    if ((fc.Name == textBoxListViewText.Name || fc.Name == textBoxListViewTextAlternate.Name || fc.Name == textBoxSearchWord.Name) && e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z)
                        return;

                    // do not check for shortcuts if a number is being entered and a time box is focused
                    if (fc.Parent != null && (fc.Parent.Name == timeUpDownStartTime.Name || fc.Parent.Name == numericUpDownDuration.Name) &&
                        (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9 || e.KeyValue >= 48 && e.KeyValue <= 57))
                        return;
                }

                bool inListView = tabControlSubtitle.SelectedIndex == TabControlListView;

                if (e.KeyCode == Keys.Escape && !_cancelWordSpellCheck)
                {
                    _cancelWordSpellCheck = true;
                }
                else if (inListView && (Keys.Shift | Keys.Control) == e.Modifiers && e.KeyCode == Keys.B)
                {
                    AutoBalanceLinesAndAllow2PlusLines();
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer != null && audioVisualizer.Visible && e.KeyData == _waveformVerticalZoom)
                {
                    audioVisualizer.VerticalZoomFactor *= 1.1;
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer != null && audioVisualizer.Visible && e.KeyData == _waveformVerticalZoomOut)
                {
                    audioVisualizer.VerticalZoomFactor /= 1.1;
                    e.SuppressKeyPress = true;
                }
                if (audioVisualizer != null && audioVisualizer.Visible && e.KeyData == _waveformZoomIn)
                {
                    audioVisualizer.ZoomIn();
                    e.SuppressKeyPress = true;
                }
                if (audioVisualizer != null && audioVisualizer.Visible && e.KeyData == _waveformZoomOut)
                {
                    audioVisualizer.ZoomOut();
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _videoPlayFirstSelected && !string.IsNullOrEmpty(_videoFileName))
                {
                    PlayFirstSelectedSubtitle();
                }
                else if (audioVisualizer != null && audioVisualizer.Visible && (e.KeyData == _waveformPlaySelection || e.KeyData == _waveformPlaySelectionEnd))
                {
                    WaveformPlaySelection(nearEnd: e.KeyData == _waveformPlaySelectionEnd);
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer != null && audioVisualizer.Visible && e.KeyData == _waveformSearchSilenceForward)
                {
                    audioVisualizer.FindDataBelowThreshold(Configuration.Settings.VideoControls.WaveformSeeksSilenceMaxVolume, Configuration.Settings.VideoControls.WaveformSeeksSilenceDurationSeconds);
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer != null && audioVisualizer.Visible && e.KeyData == _waveformSearchSilenceBack)
                {
                    audioVisualizer.FindDataBelowThresholdBack(Configuration.Settings.VideoControls.WaveformSeeksSilenceMaxVolume, Configuration.Settings.VideoControls.WaveformSeeksSilenceDurationSeconds);
                    e.SuppressKeyPress = true;
                }
                else if (_mainInsertAfter == e.KeyData && inListView)
                {
                    InsertAfter();
                    e.SuppressKeyPress = true;
                    textBoxListViewText.Focus();
                }
                else if (_mainInsertBefore == e.KeyData && inListView)
                {
                    InsertBefore();
                    e.SuppressKeyPress = true;
                    textBoxListViewText.Focus();
                }
                else if (_mainMergeDialog == e.KeyData && inListView)
                {
                    MergeDialogs();
                    e.SuppressKeyPress = true;
                }
                else if (_mainListViewToggleDashes == e.KeyData && inListView)
                {
                    ToggleDashes();
                    e.SuppressKeyPress = true;
                }
                else if (!toolStripMenuItemReverseRightToLeftStartEnd.Visible && _mainEditReverseStartAndEndingForRTL == e.KeyData && inListView)
                {
                    ReverseStartAndEndingForRtl();
                    e.SuppressKeyPress = true;
                }
                else if (toolStripMenuItemUndo.ShortcutKeys == e.KeyData) // undo
                {
                    toolStripMenuItemUndo_Click(sender, e);
                    e.SuppressKeyPress = true;
                }
                else if (toolStripMenuItemRedo.ShortcutKeys == e.KeyData) // redo
                {
                    toolStripMenuItemRedo_Click(sender, e);
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyCode == Keys.Down && e.Modifiers == Keys.Alt)
                {
                    if (AutoRepeatContinueOn || AutoRepeatOn)
                        PlayNext();
                    else
                        ButtonNextClick(null, null);
                }
                else if (e.KeyCode == Keys.Up && e.Modifiers == Keys.Alt)
                {
                    if (AutoRepeatContinueOn || AutoRepeatOn)
                        PlayPrevious();
                    else
                        ButtonPreviousClick(null, null);
                    e.SuppressKeyPress = true;
                    e.Handled = true;
                }
                else if (_mainGeneralGoToNextSubtitle == e.KeyData)
                {
                    ButtonNextClick(null, null);
                    e.SuppressKeyPress = true;
                    e.Handled = true;
                }
                else if (_mainGeneralGoToPrevSubtitle == e.KeyData)
                {
                    if (AutoRepeatContinueOn || AutoRepeatOn)
                        PlayPrevious();
                    else
                        ButtonPreviousClick(null, null);
                    e.SuppressKeyPress = true;
                    e.Handled = true;
                }
                else if (_mainGeneralGoToStartOfCurrentSubtitle == e.KeyData)
                {
                    if (SubtitleListview1.SelectedItems.Count == 1 && mediaPlayer.VideoPlayer != null)
                    {
                        mediaPlayer.CurrentPosition = _subtitle.Paragraphs[SubtitleListview1.SelectedItems[0].Index].StartTime.TotalSeconds;
                        e.SuppressKeyPress = true;
                    }
                    e.SuppressKeyPress = true;
                }
                else if (_mainGeneralGoToEndOfCurrentSubtitle == e.KeyData)
                {
                    if (SubtitleListview1.SelectedItems.Count == 1 && mediaPlayer.VideoPlayer != null)
                    {
                        mediaPlayer.CurrentPosition = _subtitle.Paragraphs[SubtitleListview1.SelectedItems[0].Index].EndTime.TotalSeconds;
                        e.SuppressKeyPress = true;
                    }
                    e.SuppressKeyPress = true;
                }
                else if (_mainGoToPreviousSubtitleAndFocusVideo == e.KeyData)
                {
                    int newIndex = _subtitleListViewIndex - 1;
                    if (newIndex >= 0)
                    {
                        foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                            item.Selected = false;
                        SubtitleListview1.Items[newIndex].Selected = true;
                        SubtitleListview1.Items[newIndex].EnsureVisible();
                        textBoxListViewText.Focus();
                        textBoxListViewText.SelectAll();
                        _subtitleListViewIndex = newIndex;
                        GotoSubtitleIndex(newIndex);
                        ShowSubtitle();
                        e.SuppressKeyPress = true;
                    }
                }
                else if (_mainGoToNextSubtitleAndFocusVideo == e.KeyData)
                {
                    int newIndex = _subtitleListViewIndex + 1;
                    if (newIndex < _subtitle.Paragraphs.Count)
                    {
                        foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                            item.Selected = false;
                        SubtitleListview1.Items[newIndex].Selected = true;
                        SubtitleListview1.Items[newIndex].EnsureVisible();
                        textBoxListViewText.Focus();
                        textBoxListViewText.SelectAll();
                        _subtitleListViewIndex = newIndex;
                        GotoSubtitleIndex(newIndex);
                        ShowSubtitle();
                        e.SuppressKeyPress = true;
                    }
                }
                else if (_mainUnbreakNoSpace == e.KeyData)
                {
                    Unbreak(true);
                }
                else if (_mainGeneralFileSaveAll == e.KeyData)
                {
                    ToolStripButtonSaveClick(sender, e);
                    e.SuppressKeyPress = true;
                }
                else if (_mainToggleFocus == e.KeyData && inListView)
                {
                    if (SubtitleListview1.Focused)
                        textBoxListViewText.Focus();
                    else
                        SubtitleListview1.Focus();
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyCode == Keys.Home && e.Modifiers == Keys.Alt)
                {
                    SubtitleListview1.FirstVisibleIndex = -1;
                    SubtitleListview1.SelectIndexAndEnsureVisible(0);
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyCode == Keys.End && e.Modifiers == Keys.Alt)
                {
                    SubtitleListview1.SelectIndexAndEnsureVisible(SubtitleListview1.Items.Count - 1);
                    e.SuppressKeyPress = true;
                }
                else if (_mainGeneralGoToFirstSelectedLine == e.KeyData) //Locate first selected line in subtitle listview
                {
                    if (SubtitleListview1.SelectedItems.Count > 0)
                        SubtitleListview1.SelectedItems[0].EnsureVisible();
                    e.SuppressKeyPress = true;
                }
                else if (_mainGeneralGoToFirstEmptyLine == e.KeyData) //Go to first empty line - if any
                {
                    GoToFirstEmptyLine();
                    e.SuppressKeyPress = true;
                }
                else if (_mainGeneralMergeSelectedLines == e.KeyData)
                {
                    if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count >= 1)
                    {
                        e.SuppressKeyPress = true;
                        if (SubtitleListview1.SelectedItems.Count == 2)
                            MergeAfterToolStripMenuItemClick(null, null);
                        else
                            MergeSelectedLines();
                    }
                }
                else if (_mainGeneralMergeSelectedLinesOnlyFirstText == e.KeyData)
                {
                    if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count >= 1)
                    {
                        e.SuppressKeyPress = true;
                        MergeSelectedLinesOnlyFirstText();
                    }
                }
                else if (_mainGeneralMergeWithNext == e.KeyData)
                {
                    if (SubtitleListview1.SelectedItems.Count >= 1)
                    {
                        var idx = SubtitleListview1.SelectedItems[0].Index;
                        if (idx >= 0 && _subtitle.Paragraphs.Count > idx + 1)
                        {
                            SubtitleListview1.SelectIndexAndEnsureVisible(idx);
                            MergeAfterToolStripMenuItemClick(null, null);
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (_mainGeneralMergeWithPrevious == e.KeyData)
                {
                    if (SubtitleListview1.SelectedItems.Count >= 1)
                    {
                        var idx = SubtitleListview1.SelectedItems[0].Index;
                        if (idx > 0)
                        {
                            SubtitleListview1.SelectIndexAndEnsureVisible(idx - 1);
                            MergeAfterToolStripMenuItemClick(null, null);
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (_mainGeneralToggleTranslationMode == e.KeyData)
                { // toggle translator mode
                    EditToolStripMenuItemDropDownOpening(null, null);
                    toolStripMenuItemTranslationMode_Click(null, null);
                }
                else if (e.KeyData == _videoPlayPauseToggle)
                {
                    if (mediaPlayer.VideoPlayer != null)
                    {
                        _endSeconds = -1;
                        mediaPlayer.TogglePlayPause();
                        e.SuppressKeyPress = true;
                        e.Handled = true;
                    }
                }
                else if (e.KeyData == _videoPause)
                {
                    if (mediaPlayer.VideoPlayer != null)
                    {
                        _endSeconds = -1;
                        mediaPlayer.Pause();
                        e.SuppressKeyPress = true;
                        e.Handled = true;
                    }
                }
                else if (e.Modifiers == (Keys.Control | Keys.Shift) && e.KeyCode == Keys.Right)
                {
                    if (!textBoxListViewText.Focused && !textBoxListViewTextAlternate.Focused)
                    {
                        mediaPlayer.CurrentPosition += 1.0;
                        e.SuppressKeyPress = true;
                    }
                }
                else if (e.Modifiers == (Keys.Control | Keys.Shift) && e.KeyCode == Keys.Left)
                {
                    if (!textBoxListViewText.Focused && !textBoxListViewTextAlternate.Focused)
                    {
                        mediaPlayer.CurrentPosition -= 1.0;
                        e.SuppressKeyPress = true;
                    }
                }
                else if (e.Modifiers == Keys.None && e.KeyCode == Keys.Space)
                {
                    if (!textBoxListViewText.Focused && !textBoxListViewTextAlternate.Focused && !textBoxSource.Focused && mediaPlayer.VideoPlayer != null)
                    {
                        if (audioVisualizer != null && audioVisualizer.Focused || mediaPlayer.Focused || SubtitleListview1.Focused)
                        {
                            _endSeconds = -1;
                            mediaPlayer.TogglePlayPause();
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.D1)
                {
                    if (SubtitleListview1.SelectedItems.Count > 0 && _subtitle != null && mediaPlayer.VideoPlayer != null)
                    {
                        var p = _subtitle.GetParagraphOrDefault(SubtitleListview1.SelectedItems[0].Index);
                        if (p != null)
                        {
                            mediaPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.D2)
                {
                    if (SubtitleListview1.SelectedItems.Count > 0 && _subtitle != null && mediaPlayer.VideoPlayer != null)
                    {
                        var p = _subtitle.GetParagraphOrDefault(SubtitleListview1.SelectedItems[0].Index);
                        if (p != null)
                        {
                            mediaPlayer.CurrentPosition = p.EndTime.TotalSeconds;
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.D3)
                {
                    if (SubtitleListview1.SelectedItems.Count > 0 && _subtitle != null && mediaPlayer.VideoPlayer != null)
                    {
                        int index = SubtitleListview1.SelectedItems[0].Index - 1;
                        var p = _subtitle.GetParagraphOrDefault(index);
                        if (p != null)
                        {
                            SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                            mediaPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.D4)
                {
                    if (SubtitleListview1.SelectedItems.Count > 0 && _subtitle != null && mediaPlayer.VideoPlayer != null)
                    {
                        int index = SubtitleListview1.SelectedItems[0].Index + 1;
                        var p = _subtitle.GetParagraphOrDefault(index);
                        if (p != null)
                        {
                            SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                            mediaPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (e.Modifiers == Keys.None && e.KeyCode == Keys.F4)
                {
                    if (SubtitleListview1.SelectedItems.Count > 0 && _subtitle != null && mediaPlayer.VideoPlayer != null)
                    {
                        mediaPlayer.Pause();
                        var p = _subtitle.GetParagraphOrDefault(SubtitleListview1.SelectedItems[0].Index);
                        if (p != null)
                        {
                            if (Math.Abs(mediaPlayer.CurrentPosition - p.StartTime.TotalSeconds) < 0.1)
                                mediaPlayer.CurrentPosition = p.EndTime.TotalSeconds;
                            else
                                mediaPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (e.Modifiers == Keys.None && e.KeyCode == Keys.F5)
                {
                    if (SubtitleListview1.SelectedItems.Count > 0 && _subtitle != null && mediaPlayer.VideoPlayer != null)
                    {
                        var p = _subtitle.GetParagraphOrDefault(SubtitleListview1.SelectedItems[0].Index);
                        if (p != null)
                        {
                            mediaPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                            ShowSubtitle();
                            mediaPlayer.Play();
                            _endSeconds = p.EndTime.TotalSeconds;
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (e.Modifiers == Keys.None && e.KeyCode == Keys.F6)
                {
                    if (mediaPlayer.VideoPlayer != null)
                    {
                        GotoSubPositionAndPause();
                    }
                }
                else if (e.Modifiers == Keys.None && e.KeyCode == Keys.F7)
                {
                    if (mediaPlayer.VideoPlayer != null)
                    {
                        GoBackSeconds(3);
                    }
                }
                else if (e.Modifiers == Keys.None && e.KeyCode == Keys.F8)
                {
                    if (mediaPlayer.VideoPlayer != null)
                    {
                        _endSeconds = -1;
                        mediaPlayer.TogglePlayPause();
                        e.SuppressKeyPress = true;
                    }
                }
                else if (e.Modifiers == (Keys.Control | Keys.Alt | Keys.Shift) && e.KeyCode == Keys.W) // watermark
                {
                    var enc = GetCurrentEncoding();
                    if (enc != Encoding.UTF8 && enc != Encoding.UTF32 && enc != Encoding.Unicode && enc != Encoding.UTF7)
                    {
                        MessageBox.Show(Configuration.Settings.Language.Watermark.ErrorUnicodeEncodingOnly);
                    }
                    else
                    {
                        using (var watermarkForm = new Watermark())
                        {
                            MakeHistoryForUndo(Configuration.Settings.Language.Watermark.BeforeWatermark);
                            watermarkForm.Initialize(_subtitle, FirstSelectedIndex);
                            if (watermarkForm.ShowDialog(this) == DialogResult.OK)
                            {
                                watermarkForm.AddOrRemove(_subtitle);
                                RefreshSelectedParagraph();
                            }
                        }
                    }
                    e.SuppressKeyPress = true;
                }
                else if (e.Modifiers == (Keys.Control | Keys.Alt | Keys.Shift) && e.KeyCode == Keys.F) // Toggle HHMMSSFF / HHMMSSMMM
                {
                    Configuration.Settings.General.UseTimeFormatHHMMSSFF = !Configuration.Settings.General.UseTimeFormatHHMMSSFF;
                    RefreshTimeCodeMode();
                }
                else if (_mainGeneralSwitchTranslationAndOriginal == e.KeyData) // switch original/current
                {
                    if (_subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0 && _networkSession == null)
                    {
                        int firstIndex = FirstSelectedIndex;
                        double firstMs = -1;
                        if (firstIndex >= 0)
                            firstMs = _subtitle.Paragraphs[firstIndex].StartTime.TotalMilliseconds;

                        var temp = _subtitle;
                        _subtitle = _subtitleAlternate;
                        _subtitleAlternate = temp;

                        var tempName = _fileName;
                        _fileName = _subtitleAlternateFileName;
                        _subtitleAlternateFileName = tempName;

                        var tempChangeSubText = _changeSubtitleToString;
                        _changeSubtitleToString = _changeAlternateSubtitleToString;
                        _changeAlternateSubtitleToString = tempChangeSubText;

                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);

                        _subtitleListViewIndex = -1;
                        if (firstIndex >= 0 && _subtitle.Paragraphs.Count > firstIndex && Math.Abs(_subtitle.Paragraphs[firstIndex].StartTime.TotalMilliseconds - firstMs) < 0.01)
                            SubtitleListview1.SelectIndexAndEnsureVisible(firstIndex);
                        else
                            RefreshSelectedParagraph();

                        SetTitle();

                        _fileDateTime = new DateTime();
                    }
                }
                else if (_mainGeneralMergeTranslationAndOriginal == e.KeyData) // Merge translation and original
                {
                    if (_subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0 && _networkSession == null)
                    {
                        if (ContinueNewOrExit())
                        {
                            var subtitle = new Subtitle();
                            foreach (var p in _subtitle.Paragraphs)
                            {
                                var newP = new Paragraph(p);
                                var original = Utilities.GetOriginalParagraph(_subtitle.GetIndex(p), p, _subtitleAlternate.Paragraphs);
                                if (original != null)
                                    newP.Text += Environment.NewLine + Environment.NewLine + original.Text;
                                subtitle.Paragraphs.Add(newP);
                            }
                            RemoveAlternate(true);
                            FileNew();
                            _subtitle = subtitle;
                            _subtitleListViewIndex = -1;
                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            SubtitleListview1.SelectIndexAndEnsureVisible(0);

                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (e.KeyData == _toggleVideoDockUndock)
                {
                    if (_isVideoControlsUndocked)
                        RedockVideoControlsToolStripMenuItemClick(null, null);
                    else
                        UndockVideoControlsToolStripMenuItemClick(null, null);
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video1FrameLeft)
                {
                    var libMpv = mediaPlayer.VideoPlayer as LibMpvDynamic;
                    if (libMpv != null)
                    {
                        libMpv.GetPreviousFrame();
                    }
                    else
                    {
                        MoveVideoSeconds(-1.0 / Configuration.Settings.General.CurrentFrameRate);
                    }
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video1FrameRight)
                {
                    var libMpv = mediaPlayer.VideoPlayer as LibMpvDynamic;
                    if (libMpv != null)
                    {
                        libMpv.GetNextFrame();
                    }
                    else
                    {
                        MoveVideoSeconds(1.0 / Configuration.Settings.General.CurrentFrameRate);
                    }
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video1FrameLeftWithPlay)
                {
                    double startSeconds = mediaPlayer.CurrentPosition - (1.0 / Configuration.Settings.General.CurrentFrameRate);
                    _endSeconds = startSeconds + (1.0 / Configuration.Settings.General.CurrentFrameRate);
                    _endSecondsNewPosition = startSeconds;
                    mediaPlayer.CurrentPosition = startSeconds;
                    UiUtil.ShowSubtitle(_subtitle, mediaPlayer);
                    mediaPlayer.Play();
                    _endSecondsNewPositionTicks = DateTime.UtcNow.Ticks;
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video1FrameRightWithPlay)
                {
                    double startSeconds = mediaPlayer.CurrentPosition + (1.0 / Configuration.Settings.General.CurrentFrameRate);
                    _endSeconds = startSeconds + (1.0 / Configuration.Settings.General.CurrentFrameRate);
                    _endSecondsNewPosition = startSeconds;
                    mediaPlayer.CurrentPosition = startSeconds;
                    UiUtil.ShowSubtitle(_subtitle, mediaPlayer);
                    mediaPlayer.Play();
                    _endSecondsNewPositionTicks = DateTime.UtcNow.Ticks;
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video100MsLeft)
                {
                    MoveVideoSeconds(-0.1);
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video100MsRight)
                {
                    MoveVideoSeconds(0.1);
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video500MsLeft)
                {
                    MoveVideoSeconds(-0.5);
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video500MsRight)
                {
                    MoveVideoSeconds(0.5);
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video1000MsLeft)
                {
                    MoveVideoSeconds(-1.0);
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video1000MsRight)
                {
                    MoveVideoSeconds(1.0);
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video5000MsLeft)
                {
                    MoveVideoSeconds(-5.0);
                    e.SuppressKeyPress = true;
                }
                else if (mediaPlayer.VideoPlayer != null && e.KeyData == _video5000MsRight)
                {
                    MoveVideoSeconds(5.0);
                    e.SuppressKeyPress = true;
                }
                else if (_mainToolsBeamer == e.KeyData)
                {
                    var beamer = new Beamer(this, _subtitle, _subtitleListViewIndex);
                    beamer.ShowDialog(this);
                }
                else if (e.KeyData == _mainVideoFullscreen) // fullscreen
                {
                    GoFullscreen();
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer.Focused && audioVisualizer.NewSelectionParagraph != null && e.KeyData == _waveformAddTextAtHere)
                {
                    addParagraphHereToolStripMenuItem_Click(null, null);
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer.Focused && audioVisualizer.NewSelectionParagraph != null && e.KeyData == _waveformAddTextAtHereFromClipboard)
                {
                    addParagraphAndPasteToolStripMenuItem_Click(null, null);
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer.Focused && e.KeyData == _waveformFocusListView)
                {
                    SubtitleListview1.Focus();
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _waveformGoToNextSubtitle)
                {
                    var cp = mediaPlayer.CurrentPosition * TimeCode.BaseUnit;
                    foreach (var p in _subtitle.Paragraphs)
                    {
                        if (p.StartTime.TotalMilliseconds > cp)
                        {
                            mediaPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                            SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.Paragraphs.IndexOf(p));
                            if (p.StartTime.TotalSeconds > audioVisualizer.EndPositionSeconds + 0.2)
                            {
                                audioVisualizer.StartPositionSeconds = mediaPlayer.CurrentPosition - 0.2;
                            }
                            break;
                        }
                    }
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer.SceneChanges != null && e.KeyData == _waveformGoToPreviousSceneChange)
                {
                    var cp = mediaPlayer.CurrentPosition - 0.01;
                    foreach (var sceneChange in audioVisualizer.SceneChanges.Reverse<double>())
                    {
                        if (sceneChange < cp)
                        {
                            mediaPlayer.CurrentPosition = sceneChange;
                            break;
                        }
                    }
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer.SceneChanges != null && e.KeyData == _waveformGoToNextSceneChange)
                {
                    var cp = mediaPlayer.CurrentPosition + 0.01;
                    foreach (var sceneChange in audioVisualizer.SceneChanges)
                    {
                        if (sceneChange > cp)
                        {
                            mediaPlayer.CurrentPosition = sceneChange;
                            break;
                        }
                    }
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer.SceneChanges != null && mediaPlayer.IsPaused && e.KeyData == _waveformToggleSceneChange)
                {
                    var cp = mediaPlayer.CurrentPosition;
                    var idx = audioVisualizer?.GetSceneChangeIndex(cp);
                    if (idx >= 0)
                    { // remove scene change
                        if (idx < audioVisualizer.SceneChanges.Count)
                        {
                            audioVisualizer.SceneChanges[idx.Value] = -1;
                            SceneChangeHelper.SaveSceneChanges(_videoFileName, audioVisualizer.SceneChanges.Where(p => p > 0).ToList());
                        }
                    }
                    else
                    { // add scene change
                        var list = audioVisualizer.SceneChanges.Where(p => p > 0).ToList();
                        list.Add(cp);
                        list.Sort();
                        audioVisualizer.SceneChanges = list;
                        SceneChangeHelper.SaveSceneChanges(_videoFileName, list);
                    }
                    e.SuppressKeyPress = true;
                }
                else if (audioVisualizer.Focused && e.KeyCode == Keys.Delete)
                {
                    ToolStripMenuItemDeleteClick(null, null);
                    e.SuppressKeyPress = true;
                }
                else if (_mainToolsAutoDuration == e.KeyData)
                {
                    MakeAutoDuration();
                    e.SuppressKeyPress = true;
                }
                else if (e.Modifiers == (Keys.Control | Keys.Alt | Keys.Shift) && e.KeyCode == Keys.I)
                {
                    using (var form = new ImportUnknownFormat(string.Empty))
                    {
                        if (form.ShowDialog(this) == DialogResult.OK)
                        {
                            if (form.ImportedSubitle?.Paragraphs.Count > 0)
                            {
                                _subtitle = form.ImportedSubitle;
                                _fileName = null;
                                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            }
                        }
                    }
                    e.SuppressKeyPress = true;
                }
                else if ((textBoxListViewText.Focused || (SubtitleListview1.Focused && SubtitleListview1.SelectedItems.Count == 1) || (audioVisualizer.Focused && SubtitleListview1.SelectedItems.Count == 1)) && _mainTextBoxMoveLastWordDown == e.KeyData)
                {
                    MoveLastWordDown();
                    e.SuppressKeyPress = true;
                }
                else if ((textBoxListViewText.Focused || (SubtitleListview1.Focused && SubtitleListview1.SelectedItems.Count == 1) || (audioVisualizer.Focused && SubtitleListview1.SelectedItems.Count == 1)) && _mainTextBoxMoveFirstWordFromNextUp == e.KeyData)
                {
                    MoveFirstWordInNextUp();
                    e.SuppressKeyPress = true;
                }
                else if ((textBoxListViewText.Focused || (SubtitleListview1.Focused && SubtitleListview1.SelectedItems.Count == 1) || (audioVisualizer.Focused && SubtitleListview1.SelectedItems.Count == 1)) && _mainTextBoxMoveLastWordDownCurrent == e.KeyData)
                {
                    MoveWordUpDownInCurrent(true);
                    e.SuppressKeyPress = true;
                }
                else if ((textBoxListViewText.Focused || (SubtitleListview1.Focused && SubtitleListview1.SelectedItems.Count == 1) || (audioVisualizer.Focused && SubtitleListview1.SelectedItems.Count == 1)) && _mainTextBoxMoveFirstWordUpCurrent == e.KeyData)
                {
                    MoveWordUpDownInCurrent(false);
                    e.SuppressKeyPress = true;
                }
                else if (_mainAutoCalcCurrentDuration == e.KeyData && (tabControlButtons.SelectedTab == tabPageAdjust || tabControlButtons.SelectedTab == tabPageCreate))
                {
                    e.SuppressKeyPress = true;
                    if (SubtitleListview1.SelectedItems.Count >= 1)
                    {
                        var idx = SubtitleListview1.SelectedItems[0].Index;
                        _subtitle.RecalculateDisplayTime(Configuration.Settings.General.SubtitleMaximumCharactersPerSeconds, idx);
                        SetDurationInSeconds(_subtitle.Paragraphs[idx].Duration.TotalSeconds);
                    }
                }
                else if (_mainAdjustExtendCurrentSubtitle == e.KeyData && (tabControlButtons.SelectedTab == tabPageAdjust || tabControlButtons.SelectedTab == tabPageCreate))
                {
                    if (SubtitleListview1.SelectedItems.Count == 1)
                    {
                        var idx = SubtitleListview1.SelectedItems[0].Index;
                        var p = _subtitle.Paragraphs[idx];
                        var next = _subtitle.GetParagraphOrDefault(idx + 1);
                        if (next == null || next.StartTime.TotalMilliseconds > p.EndTime.TotalMilliseconds + Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds + Configuration.Settings.General.MinimumMillisecondsBetweenLines)
                        {
                            p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds;
                        }
                        else if (next != null && next.StartTime.TotalMilliseconds > p.EndTime.TotalMilliseconds)
                        {
                            p.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                        }
                        RefreshSelectedParagraph();
                        e.SuppressKeyPress = true;
                    }
                    e.SuppressKeyPress = true;
                }

                // TABS - MUST BE LAST
                else if (tabControlButtons.SelectedTab == tabPageAdjust)
                {
                    if (_mainAdjustSelected100MsForward == e.KeyData)
                    {
                        ShowEarlierOrLater(100, SelectionChoice.SelectionOnly);
                        e.SuppressKeyPress = true;
                    }
                    else if (_mainAdjustSelected100MsBack == e.KeyData)
                    {
                        ShowEarlierOrLater(-100, SelectionChoice.SelectionOnly);
                        e.SuppressKeyPress = true;
                    }
                    else if (_mainAdjustAdjustStartXMsBack == e.KeyData)
                    {
                        MoveStartCurrent(-Configuration.Settings.Tools.MoveStartEndMs);
                        e.SuppressKeyPress = true;
                    }
                    else if (_mainAdjustAdjustStartXMsForward == e.KeyData)
                    {
                        MoveStartCurrent(Configuration.Settings.Tools.MoveStartEndMs);
                        e.SuppressKeyPress = true;
                    }
                    else if (_mainAdjustAdjustEndXMsBack == e.KeyData)
                    {
                        MoveEndCurrent(-Configuration.Settings.Tools.MoveStartEndMs);
                        e.SuppressKeyPress = true;
                    }
                    else if (_mainAdjustAdjustEndXMsForward == e.KeyData)
                    {
                        MoveEndCurrent(Configuration.Settings.Tools.MoveStartEndMs);
                        e.SuppressKeyPress = true;
                    }
                    else if (mediaPlayer.VideoPlayer != null)
                    {
                        if (_mainAdjustSetStartAndOffsetTheRest == e.KeyData)
                        {
                            ButtonSetStartAndOffsetRestClick(null, null);
                            e.SuppressKeyPress = true;
                        }
                        else if (_mainAdjustSetEndAndOffsetTheRest == e.KeyData)
                        {
                            SetEndAndOffsetTheRest(false);
                            e.SuppressKeyPress = true;
                        }
                        else if (_mainAdjustSetEndAndOffsetTheRestAndGoToNext == e.KeyData)
                        {
                            SetEndAndOffsetTheRest(true);
                            e.SuppressKeyPress = true;
                        }
                        else if (_mainAdjustSetEndAndGotoNext == e.KeyData)
                        {
                            ShowNextSubtitleLabel();
                            ButtonSetEndAndGoToNextClick(null, null);
                            e.SuppressKeyPress = true;
                        }
                        else if (e.Modifiers == Keys.None && e.KeyCode == Keys.F9)
                        {
                            ButtonSetStartAndOffsetRestClick(null, null);
                            e.SuppressKeyPress = true;
                        }
                        else if (e.Modifiers == Keys.None && e.KeyCode == Keys.F10)
                        {
                            ShowNextSubtitleLabel();
                            ButtonSetEndAndGoToNextClick(null, null);
                            e.SuppressKeyPress = true;
                        }
                        else if ((e.Modifiers == Keys.None && e.KeyCode == Keys.F11) || _mainAdjustSetStart == e.KeyData)
                        {
                            buttonSetStartTime_Click(null, null);
                            e.SuppressKeyPress = true;
                        }
                        else if (_mainAdjustSetStartKeepDuration == e.KeyData)
                        {
                            SetStartTime(true);
                            e.SuppressKeyPress = true;
                        }
                        else if (e.Modifiers == Keys.None && e.KeyCode == Keys.F11)
                        {
                            SetStartTime(false);
                            e.SuppressKeyPress = true;
                        }
                        else if ((e.Modifiers == Keys.None && e.KeyCode == Keys.F12) || _mainAdjustSetEnd == e.KeyData)
                        {
                            StopAutoDuration();
                            ButtonSetEndClick(null, null);
                            e.SuppressKeyPress = true;
                        }
                        else if (_mainAdjustInsertViaEndAutoStartAndGoToNext == e.KeyData)
                        {
                            ShowNextSubtitleLabel();
                            SetCurrentViaEndPositionAndGotoNext(FirstSelectedIndex);
                            e.SuppressKeyPress = true;
                        }
                        else if (_mainAdjustSetStartAutoDurationAndGoToNext == e.KeyData)
                        {
                            //             ShowNextSubtitleLabel();
                            SetCurrentStartAutoDurationAndGotoNext(FirstSelectedIndex);
                            e.SuppressKeyPress = true;
                        }
                        else if (_mainAdjustSetEndNextStartAndGoToNext == e.KeyData)
                        {
                            ShowNextSubtitleLabel();
                            SetCurrentEndNextStartAndGoToNext(FirstSelectedIndex);
                            e.SuppressKeyPress = true;
                        }
                        else if (_mainAdjustStartDownEndUpAndGoToNext == e.KeyData && _mainAdjustStartDownEndUpAndGoToNextParagraph == null)
                        {
                            ShowNextSubtitleLabel();
                            _mainAdjustStartDownEndUpAndGoToNextParagraph = _subtitle.GetParagraphOrDefault(FirstSelectedIndex);
                            SetStartTime(true);
                            e.SuppressKeyPress = true;
                        }
                    }
                }
                else if (tabControlButtons.SelectedTab == tabPageCreate && mediaPlayer.VideoPlayer != null)
                {
                    if (e.Modifiers == Keys.Control && e.KeyCode == Keys.F9)
                    {
                        InsertNewTextAtVideoPosition();
                        e.SuppressKeyPress = true;
                    }
                    else if ((e.Modifiers == Keys.Shift && e.KeyCode == Keys.F9) || _mainCreateInsertSubAtVideoPos == e.KeyData)
                    {
                        var p = InsertNewTextAtVideoPosition();
                        p.Text = string.Empty; // p.StartTime.ToShortString();
                        SubtitleListview1.SetText(_subtitle.GetIndex(p), p.Text);
                        textBoxListViewText.Text = p.Text;
                        e.SuppressKeyPress = true;
                    }
                    else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.F9)
                    {
                        StopAutoDuration();
                        ButtonSetEndClick(null, null);
                        e.SuppressKeyPress = true;
                    }
                    else if (e.Modifiers == Keys.None && e.KeyCode == Keys.F9)
                    {
                        ButtonInsertNewTextClick(null, null);
                        e.SuppressKeyPress = true;
                    }
                    else if ((e.Modifiers == Keys.None && e.KeyCode == Keys.F10) || _mainCreatePlayFromJustBefore == e.KeyData)
                    {
                        buttonBeforeText_Click(null, null);
                        e.SuppressKeyPress = true;
                    }
                    else if ((e.Modifiers == Keys.None && e.KeyCode == Keys.F11) || _mainCreateSetStart == e.KeyData)
                    {
                        buttonSetStartTime_Click(null, null);
                        e.SuppressKeyPress = true;
                    }
                    else if ((e.Modifiers == Keys.None && e.KeyCode == Keys.F12) || _mainCreateSetEnd == e.KeyData)
                    {
                        StopAutoDuration();
                        ButtonSetEndClick(null, null);
                        e.SuppressKeyPress = true;
                    }
                    else if (_mainCreateSetEndAddNewAndGoToNew == e.KeyData)
                    {
                        StopAutoDuration();
                        e.SuppressKeyPress = true;

                        if (SubtitleListview1.SelectedItems.Count == 1)
                        {
                            double videoPosition = mediaPlayer.CurrentPosition;
                            if (!mediaPlayer.IsPaused)
                                videoPosition -= Configuration.Settings.General.SetStartEndHumanDelay / TimeCode.BaseUnit;
                            int index = SubtitleListview1.SelectedItems[0].Index;
                            MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.VideoControls.BeforeChangingTimeInWaveformX, "#" + _subtitle.Paragraphs[index].Number + " " + _subtitle.Paragraphs[index].Text));

                            var p = _subtitle.Paragraphs[index];
                            p.EndTime = TimeCode.FromSeconds(videoPosition);
                            if (p.Duration.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines > Configuration.Settings.General.SubtitleMinimumDisplayMilliseconds)
                            {
                                var newEndTime = new TimeCode(p.EndTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines);
                                double charactersPerSecond = Utilities.GetCharactersPerSecond(new Paragraph(p) { EndTime = newEndTime });
                                if (charactersPerSecond <= Configuration.Settings.General.SubtitleMaximumCharactersPerSeconds)
                                {
                                    p.EndTime = newEndTime;
                                }
                            }
                            SubtitleListview1.SetStartTimeAndDuration(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                            SetDurationInSeconds(_subtitle.Paragraphs[index].Duration.TotalSeconds);
                            ButtonInsertNewTextClick(null, null);
                        }
                    }
                    else if (_mainCreateStartDownEndUp == e.KeyData)
                    {
                        if (_mainCreateStartDownEndUpParagraph == null)
                            _mainCreateStartDownEndUpParagraph = InsertNewTextAtVideoPosition();
                        e.SuppressKeyPress = true;
                    }
                    else if (_mainAdjustSelected100MsForward == e.KeyData)
                    {
                        ShowEarlierOrLater(100, SelectionChoice.SelectionOnly);
                        e.SuppressKeyPress = true;
                    }
                    else if (_mainAdjustSelected100MsBack == e.KeyData)
                    {
                        ShowEarlierOrLater(-100, SelectionChoice.SelectionOnly);
                        e.SuppressKeyPress = true;
                    }
                }
                else if (tabControlButtons.SelectedTab == tabPageTranslate)
                {
                    if (_mainTranslateCustomSearch1 == e.KeyData)
                    {
                        e.SuppressKeyPress = true;
                        RunCustomSearch(Configuration.Settings.VideoControls.CustomSearchUrl1);
                    }
                    else if (_mainTranslateCustomSearch2 == e.KeyData)
                    {
                        e.SuppressKeyPress = true;
                        RunCustomSearch(Configuration.Settings.VideoControls.CustomSearchUrl2);
                    }
                    else if (_mainTranslateCustomSearch3 == e.KeyData)
                    {
                        e.SuppressKeyPress = true;
                        RunCustomSearch(Configuration.Settings.VideoControls.CustomSearchUrl3);
                    }
                    else if (_mainTranslateCustomSearch4 == e.KeyData)
                    {
                        e.SuppressKeyPress = true;
                        RunCustomSearch(Configuration.Settings.VideoControls.CustomSearchUrl4);
                    }
                    else if (_mainTranslateCustomSearch5 == e.KeyData)
                    {
                        e.SuppressKeyPress = true;
                        RunCustomSearch(Configuration.Settings.VideoControls.CustomSearchUrl5);
                    }
                    else if (_mainTranslateCustomSearch6 == e.KeyData)
                    {
                        e.SuppressKeyPress = true;
                        RunCustomSearch(Configuration.Settings.VideoControls.CustomSearchUrl6);
                    }
                }
                // put new entries above tabs
            }

            private void MoveWordUpDownInCurrent(bool down)
            {
                int firstIndex = FirstSelectedIndex;
                if (firstIndex < 0)
                {
                    return;
                }

                var p = _subtitle.GetParagraphOrDefault(firstIndex);
                if (p == null)
                {
                    return;
                }

                var lines = p.Text.SplitToLines();
                if (lines.Count == 1)
                {
                    lines.Add(string.Empty);
                }
                if (lines.Count != 2)
                {
                    return;
                }

                var line1Words = lines[0].Split(' ').ToList();
                var line2Words = lines[1].Split(' ').ToList();
                if (down)
                {
                    if (line1Words.Count > 0)
                    {
                        line2Words.Insert(0, line1Words[line1Words.Count - 1]);
                        line1Words.RemoveAt(line1Words.Count - 1);
                    }
                }
                else // up
                {
                    if (line2Words.Count > 0)
                    {
                        line1Words.Add(line2Words[0]);
                        line2Words.RemoveAt(0);
                    }
                }
                var newText = (string.Join(" ", line1Words.ToArray()).Trim() + Environment.NewLine +
                               string.Join(" ", line2Words.ToArray()).Trim()).Trim();
                if (newText != p.Text)
                {
                    var oldText = p.Text;
                    MakeHistoryForUndo(_language.BeforeLineUpdatedInListView);
                    var textCaretPos = textBoxListViewText.SelectionStart;
                    p.Text = newText;
                    SubtitleListview1.SetText(firstIndex, p.Text);
                    textBoxListViewText.Text = p.Text;

                    // keep cursor position
                    KeepCursorMoveWordUpdown(down, newText, oldText, textCaretPos);
                }
            }

            private void KeepCursorMoveWordUpdown(bool down, string newText, string oldText, int textCaretPos)
            {
                if (textCaretPos > textBoxListViewText.Text.Length)
                {
                    // set cursor at end of textbox
                    textBoxListViewText.SelectionStart = textCaretPos;
                    int end = textBoxListViewText.Text.Length;
                    textBoxListViewText.SelectionStart = end;
                    textBoxListViewText.SelectionLength = 0;
                    return;
                }

                int indexOfNewLine = newText.IndexOf(Environment.NewLine);
                int oldIndexOfNewLine = oldText.IndexOf(Environment.NewLine);

                if (down)
                {
                    if (indexOfNewLine == -1 && oldIndexOfNewLine > 0 && textCaretPos > oldIndexOfNewLine)
                    {
                        textCaretPos--;
                    }
                    else if (textCaretPos > indexOfNewLine && textCaretPos > oldIndexOfNewLine && oldIndexOfNewLine >= 0 ||
                             textCaretPos < indexOfNewLine && (oldIndexOfNewLine == -1 || textCaretPos < oldIndexOfNewLine) ||
                             textCaretPos < oldIndexOfNewLine && indexOfNewLine == -1)
                    {
                    }
                    else
                    {
                        textCaretPos++;
                    }
                }
                else // up
                {
                    if (textCaretPos <= oldIndexOfNewLine || textCaretPos > oldIndexOfNewLine && textCaretPos > indexOfNewLine && indexOfNewLine >= 0)
                    {
                    }
                    else
                    {
                        textCaretPos--;
                    }
                }
                if (textBoxListViewText.Text.Length > textCaretPos && '\n' == textBoxListViewText.Text[textCaretPos])
                    textCaretPos--;
                if (textCaretPos >= 0)
                {
                    textBoxListViewText.SelectionStart = textCaretPos;
                    textBoxListViewText.SelectionStart = textCaretPos;
                    textBoxListViewText.SelectionStart = textCaretPos;
                }
            }

            private void MoveStartCurrent(int ms)
            {
                var i = _subtitleListViewIndex;
                if (i < 0 || i >= _subtitle.Paragraphs.Count || ms == 0)
                    return;

                var p = _subtitle.GetParagraphOrDefault(i);
                if (ms > 0)
                {
                    if (p.StartTime.TotalMilliseconds + ms + 100 > p.EndTime.TotalMilliseconds)
                    {
                        return; // do not allow duration smaller than 100ms
                    }
                    p.StartTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + ms;
                }
                else
                {
                    if (p.Duration.TotalMilliseconds + Math.Abs(ms) > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds)
                        return;

                    if (p.StartTime.TotalMilliseconds + ms < 0)
                        return;

                    var prev = _subtitle.GetParagraphOrDefault(i - 1);
                    if (prev == null || p.StartTime.TotalMilliseconds - (Math.Abs(ms) + Configuration.Settings.General.MinimumMillisecondsBetweenLines) > prev.EndTime.TotalMilliseconds)
                    {
                        p.StartTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + ms;
                    }
                    else
                    {
                        var newStartMs = prev.EndTime.TotalMilliseconds + Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                        if (newStartMs < p.StartTime.TotalMilliseconds)
                        {
                            p.StartTime.TotalMilliseconds = newStartMs;
                        }
                    }
                }
                SubtitleListview1.SetDuration(i, p, _subtitle.GetParagraphOrDefault(i + 1));
            }

            private void MoveEndCurrent(int ms)
            {
                var i = _subtitleListViewIndex;
                if (i < 0 || i >= _subtitle.Paragraphs.Count || ms == 0)
                    return;

                var p = _subtitle.GetParagraphOrDefault(i);
                if (ms > 0)
                {
                    if (p.Duration.TotalMilliseconds + ms > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds)
                        return;

                    var next = _subtitle.GetParagraphOrDefault(i + 1);
                    if (next == null || p.StartTime.TotalMilliseconds - (Math.Abs(ms) + Configuration.Settings.General.MinimumMillisecondsBetweenLines) < next.StartTime.TotalMilliseconds)
                    {
                        p.EndTime.TotalMilliseconds = p.EndTime.TotalMilliseconds + ms;
                    }
                    else
                    {
                        var newEndMs = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                        if (newEndMs > p.EndTime.TotalMilliseconds)
                        {
                            p.EndTime.TotalMilliseconds = newEndMs;
                        }
                    }
                }
                else
                {
                    if (p.EndTime.TotalMilliseconds + ms - 100 < p.StartTime.TotalMilliseconds)
                    {
                        return; // do not allow duration smaller than 100ms
                    }
                    p.EndTime.TotalMilliseconds = p.EndTime.TotalMilliseconds + ms;
                }
                SubtitleListview1.SetDuration(i, p, _subtitle.GetParagraphOrDefault(i + 1));
            }

            private void ShowNextSubtitleLabel()
            {
                if (audioVisualizer.Visible && audioVisualizer.WavePeaks != null && audioVisualizer.Width > 300 && _subtitleListViewIndex >= 0)
                {
                    var next = _subtitle.GetParagraphOrDefault(_subtitleListViewIndex + 1);
                    if (next != null && !string.IsNullOrEmpty(next.Text))
                    {
                        labelNextWord.Top = audioVisualizer.Top;
                        labelNextWord.Text = string.Format(_language.NextX, next.Text.Replace(Environment.NewLine, " "));
                        labelNextWord.Left = audioVisualizer.Width / 2 - labelNextWord.Width / 2 + audioVisualizer.Left;
                        labelNextWord.Visible = true;
                        _labelNextTicks = DateTime.UtcNow.Ticks;
                    }
                    else
                    {
                        labelNextWord.Visible = false;
                    }
                }
                else
                {
                    labelNextWord.Visible = false;
                }
            }

            private void MergeSelectedLinesOnlyFirstText()
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 1)
                {
                    var deleteIndices = new List<int>();
                    bool first = true;
                    int firstIndex = 0;
                    int next = 0;
                    string text = string.Empty;
                    double endTime = 0;
                    foreach (int index in SubtitleListview1.SelectedIndices)
                    {
                        if (first)
                        {
                            firstIndex = index;
                            next = index + 1;
                        }
                        else
                        {
                            deleteIndices.Add(index);
                            if (next != index)
                                return;
                            next++;
                        }
                        first = false;
                        if (string.IsNullOrEmpty(text))
                            text = _subtitle.Paragraphs[index].Text.Trim();
                        endTime = _subtitle.Paragraphs[index].EndTime.TotalMilliseconds;
                    }

                    SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                    MakeHistoryForUndo(_language.BeforeMergeLines);

                    var currentParagraph = _subtitle.Paragraphs[firstIndex];
                    currentParagraph.Text = text;
                    currentParagraph.EndTime.TotalMilliseconds = endTime;

                    var nextParagraph = _subtitle.GetParagraphOrDefault(next);
                    if (nextParagraph != null && currentParagraph.EndTime.TotalMilliseconds > nextParagraph.StartTime.TotalMilliseconds && currentParagraph.StartTime.TotalMilliseconds < nextParagraph.StartTime.TotalMilliseconds)
                    {
                        currentParagraph.EndTime.TotalMilliseconds = nextParagraph.StartTime.TotalMilliseconds - 1;
                    }

                    // original subtitle
                    if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                    {
                        var original = Utilities.GetOriginalParagraph(firstIndex, currentParagraph, _subtitleAlternate.Paragraphs);
                        if (original != null)
                        {
                            string originalText = string.Empty;
                            for (int i = 0; i < deleteIndices.Count; i++)
                            {
                                var originalNext = Utilities.GetOriginalParagraph(deleteIndices[i], _subtitle.Paragraphs[deleteIndices[i]], _subtitleAlternate.Paragraphs);
                                if (originalNext != null && string.IsNullOrEmpty(originalText))
                                    originalText = originalNext.Text;
                            }
                            for (int i = deleteIndices.Count - 1; i >= 0; i--)
                            {
                                var originalNext = Utilities.GetOriginalParagraph(deleteIndices[i], _subtitle.Paragraphs[deleteIndices[i]], _subtitleAlternate.Paragraphs);
                                if (originalNext != null)
                                    _subtitleAlternate.Paragraphs.Remove(originalNext);
                            }
                            original.Text = originalText;
                            original.EndTime.TotalMilliseconds = currentParagraph.EndTime.TotalMilliseconds;
                            _subtitleAlternate.Renumber();
                        }
                    }

                    if (_networkSession != null)
                    {
                        _networkSession.TimerStop();
                        _networkSession.UpdateLine(firstIndex, currentParagraph);
                        NetworkGetSendUpdates(deleteIndices, 0, null);
                    }
                    else
                    {
                        for (int i = deleteIndices.Count - 1; i >= 0; i--)
                            _subtitle.Paragraphs.RemoveAt(deleteIndices[i]);
                        _subtitle.Renumber();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    }
                    ShowSource();
                    ShowStatus(_language.LinesMerged);
                    SubtitleListview1.SelectIndexAndEnsureVisible(firstIndex, true);
                    SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                    RefreshSelectedParagraph();
                }
            }

            private void GoToFirstEmptyLine()
            {
                var index = FirstSelectedIndex + 1;
                for (; index < _subtitle.Paragraphs.Count; index++)
                {
                    if (string.IsNullOrWhiteSpace(_subtitle.Paragraphs[index].Text))
                    {
                        SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                        return;
                    }
                }
            }

            private void PlayFirstSelectedSubtitle()
            {
                if (_subtitleListViewIndex >= 0 && mediaPlayer.VideoPlayer != null)
                {
                    GotoSubtitleIndex(_subtitleListViewIndex);
                    var paragraph = _subtitle.Paragraphs[_subtitleListViewIndex];
                    double startSeconds = paragraph.StartTime.TotalSeconds;
                    _endSeconds = paragraph.EndTime.TotalSeconds;
                    mediaPlayer.CurrentPosition = startSeconds;
                    ShowSubtitle();
                    mediaPlayer.Play();
                }
            }

            private void SetEndAndOffsetTheRest(bool goToNext)
            {
                if (SubtitleListview1.SelectedItems.Count == 1)
                {
                    bool oldSync = checkBoxSyncListViewWithVideoWhilePlaying.Checked;
                    checkBoxSyncListViewWithVideoWhilePlaying.Checked = false;

                    int index = SubtitleListview1.SelectedItems[0].Index;
                    double videoPosition = mediaPlayer.CurrentPosition;
                    if (!mediaPlayer.IsPaused)
                        videoPosition -= Configuration.Settings.General.SetStartEndHumanDelay / TimeCode.BaseUnit;

                    var tc = TimeCode.FromSeconds(videoPosition);

                    double offset = tc.TotalMilliseconds - _subtitle.Paragraphs[index].EndTime.TotalMilliseconds;
                    if (_subtitle.Paragraphs[index].StartTime.TotalMilliseconds + 100 > tc.TotalMilliseconds || offset > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds)
                        return;

                    MakeHistoryForUndo(_language.BeforeSetEndTimeAndOffsetTheRest + @"  " + _subtitle.Paragraphs[index].Number + @" - " + tc);

                    numericUpDownDuration.ValueChanged -= NumericUpDownDurationValueChanged;
                    _subtitle.Paragraphs[index].EndTime.TotalSeconds = videoPosition;
                    SubtitleListview1.SetDuration(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1));
                    checkBoxSyncListViewWithVideoWhilePlaying.Checked = oldSync;
                    numericUpDownDuration.Value = (decimal)_subtitle.Paragraphs[index].Duration.TotalSeconds;
                    numericUpDownDuration.ValueChanged += NumericUpDownDurationValueChanged;

                    for (int i = index + 1; i < SubtitleListview1.Items.Count; i++)
                    {
                        if (!_subtitle.Paragraphs[i].StartTime.IsMaxTime)
                        {
                            _subtitle.Paragraphs[i].StartTime = new TimeCode(_subtitle.Paragraphs[i].StartTime.TotalMilliseconds + offset);
                            _subtitle.Paragraphs[i].EndTime = new TimeCode(_subtitle.Paragraphs[i].EndTime.TotalMilliseconds + offset);
                            SubtitleListview1.SetDuration(i, _subtitle.Paragraphs[i], _subtitle.GetParagraphOrDefault(i + 1));
                        }
                    }

                    if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                    {
                        var original = Utilities.GetOriginalParagraph(index, _subtitle.Paragraphs[index], _subtitleAlternate.Paragraphs);
                        if (original != null)
                        {
                            index = _subtitleAlternate.GetIndex(original);
                            for (int i = index; i < _subtitleAlternate.Paragraphs.Count; i++)
                            {
                                if (!_subtitleAlternate.Paragraphs[i].StartTime.IsMaxTime)
                                {
                                    _subtitleAlternate.Paragraphs[i].StartTime = new TimeCode(_subtitleAlternate.Paragraphs[i].StartTime.TotalMilliseconds + offset);
                                    _subtitleAlternate.Paragraphs[i].EndTime = new TimeCode(_subtitleAlternate.Paragraphs[i].EndTime.TotalMilliseconds + offset);
                                }
                            }
                        }
                    }
                    if (IsFramesRelevant && CurrentFrameRate > 0)
                    {
                        _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                            ShowSource();
                    }

                    checkBoxSyncListViewWithVideoWhilePlaying.Checked = oldSync;

                    if (goToNext)
                    {
                        SubtitleListview1.SelectIndexAndEnsureVisible(index + 1);
                    }
                }
            }

            private void MoveVideoSeconds(double seconds)
            {
                var oldPosition = mediaPlayer.CurrentPosition;
                var newPosition = oldPosition + seconds;
                if (mediaPlayer.IsPaused && Configuration.Settings.General.MoveVideo100Or500MsPlaySmallSample)
                {
                    mediaPlayer.CurrentPosition = newPosition;
                    mediaPlayer.Play();
                    System.Threading.Thread.Sleep(99);
                    mediaPlayer.Stop();
                }
                mediaPlayer.CurrentPosition = newPosition;
            }

            private void RunCustomSearch(string url)
            {
                if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(textBoxSearchWord.Text))
                {
                    if (url.Contains("{0}"))
                        url = string.Format(url, Utilities.UrlEncode(textBoxSearchWord.Text));
                    System.Diagnostics.Process.Start(url);
                }
            }

            private void GoFullscreen()
            {
                if (mediaPlayer.VideoPlayer == null)
                    return;

                mediaPlayer.ShowFullScreenControls();
                bool setRedockOnFullscreenEnd = false;

                if (_videoPlayerUndocked == null || _videoPlayerUndocked.IsDisposed)
                {
                    UndockVideoControlsToolStripMenuItemClick(null, null);
                    setRedockOnFullscreenEnd = true;
                }

                if (_videoPlayerUndocked != null && !_videoPlayerUndocked.IsDisposed)
                {
                    _videoPlayerUndocked.Focus();
                    _videoPlayerUndocked.GoFullscreen();
                    if (setRedockOnFullscreenEnd)
                        _videoPlayerUndocked.RedockOnFullscreenEnd = true;
                }
            }

            private void RefreshTimeCodeMode()
            {
                if (Configuration.Settings.General.UseTimeFormatHHMMSSFF)
                {
                    numericUpDownDuration.DecimalPlaces = 2;
                    numericUpDownDuration.Increment = (decimal)(0.01);

                    toolStripSeparatorFrameRate.Visible = true;
                    toolStripLabelFrameRate.Visible = true;
                    toolStripComboBoxFrameRate.Visible = true;
                    toolStripButtonGetFrameRate.Visible = true;
                }
                else
                {
                    numericUpDownDuration.DecimalPlaces = 3;
                    numericUpDownDuration.Increment = (decimal)(0.1);

                    toolStripSeparatorFrameRate.Visible = Configuration.Settings.General.ShowFrameRate;
                    toolStripLabelFrameRate.Visible = Configuration.Settings.General.ShowFrameRate;
                    toolStripComboBoxFrameRate.Visible = Configuration.Settings.General.ShowFrameRate;
                    toolStripButtonGetFrameRate.Visible = Configuration.Settings.General.ShowFrameRate;
                }

                SaveSubtitleListviewIndices();
                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                RestoreSubtitleListviewIndices();
                RefreshSelectedParagraph();
            }

            private void ReverseStartAndEndingForRtl()
            {
                MakeHistoryForUndo(toolStripMenuItemReverseRightToLeftStartEnd.Text);
                int selectedIndex = FirstSelectedIndex;
                foreach (int index in SubtitleListview1.SelectedIndices)
                {
                    var p = _subtitle.Paragraphs[index];
                    p.Text = Utilities.ReverseStartAndEndingForRightToLeft(p.Text);
                    SubtitleListview1.SetText(index, p.Text);
                    if (index == selectedIndex)
                        textBoxListViewText.Text = p.Text;
                }
            }

            private void MergeDialogs()
            {
                if (SubtitleListview1.SelectedItems.Count == 2 && SubtitleListview1.SelectedIndices[0] + 1 == SubtitleListview1.SelectedIndices[1])
                    MergeWithLineAfter(true);
            }

            private void ToggleDashes()
            {
                var index = FirstSelectedIndex;
                if (index >= 0)
                {
                    var hasStartDash = false;
                    var p = _subtitle.Paragraphs[index];
                    var lines = p.Text.SplitToLines();
                    foreach (var line in lines)
                    {
                        var trimmed = line.TrimStart();
                        if (trimmed.StartsWith('-') || trimmed.StartsWith("<i>-", StringComparison.Ordinal) || trimmed.StartsWith("<i> -", StringComparison.Ordinal))
                        {
                            hasStartDash = true;
                            break;
                        }
                    }
                    MakeHistoryForUndo(_language.BeforeToggleDialogDashes);
                    if (hasStartDash)
                        RemoveDashes();
                    else
                        AddDashes();
                }
            }

            private void AddDashes()
            {
                foreach (int index in SubtitleListview1.SelectedIndices)
                {
                    var p = _subtitle.Paragraphs[index];
                    var lines = p.Text.SplitToLines();
                    var sb = new StringBuilder();
                    foreach (var line in lines)
                    {
                        if (line.TrimStart().StartsWith('-') || line.TrimStart().StartsWith("<i>-", StringComparison.Ordinal) || line.TrimStart().StartsWith("<i> -", StringComparison.Ordinal))
                            sb.AppendLine(line);
                        else if (line.TrimStart().StartsWith("<i>", StringComparison.Ordinal) && line.Trim().Length > 3)
                            sb.AppendLine("<i>- " + line.Substring(3).TrimStart());
                        else
                            sb.AppendLine("- " + line);
                    }
                    var text = sb.ToString().Trim();
                    _subtitle.Paragraphs[index].Text = text;
                    SubtitleListview1.SetText(index, text);
                    if (index == _subtitleListViewIndex)
                        textBoxListViewText.Text = text;
                }
            }

            private void RemoveDashes()
            {
                foreach (int index in SubtitleListview1.SelectedIndices)
                {
                    var p = _subtitle.Paragraphs[index];
                    var lines = p.Text.SplitToLines();
                    var sb = new StringBuilder();
                    foreach (var line in lines)
                    {
                        if (line.TrimStart().StartsWith('-'))
                            sb.AppendLine(line.TrimStart().TrimStart('-').TrimStart());
                        else if (line.TrimStart().StartsWith("<i>-", StringComparison.Ordinal) || line.TrimStart().StartsWith("<i> -", StringComparison.Ordinal))
                            sb.AppendLine("<i>" + line.TrimStart().Substring(3).TrimStart().TrimStart('-').TrimStart());
                        else
                            sb.AppendLine(line);
                    }
                    string text = sb.ToString().Trim();
                    _subtitle.Paragraphs[index].Text = text;
                    SubtitleListview1.SetText(index, text);
                    if (index == _subtitleListViewIndex)
                        textBoxListViewText.Text = text;
                }
            }

            private void SetTitle()
            {
                Text = Title;

                string separator = " - ";
                if (!string.IsNullOrEmpty(_fileName))
                {
                    Text = Text + separator + _fileName;
                    separator = " + ";
                }

                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    Text = Text + separator;
                    if (string.IsNullOrEmpty(_fileName))
                        Text = Text + _language.New + " + ";
                    if (!string.IsNullOrEmpty(_subtitleAlternateFileName))
                        Text = Text + _subtitleAlternateFileName;
                    else
                        Text = Text + _language.New;
                }
            }

            private void SubtitleListview1KeyDown(object sender, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control) //Ctrl+c = Copy to clipboard
                {
                    var tmp = new Subtitle();
                    foreach (int i in SubtitleListview1.SelectedIndices)
                    {
                        var p = _subtitle.GetParagraphOrDefault(i);
                        if (p != null)
                            tmp.Paragraphs.Add(new Paragraph(p));
                    }
                    if (tmp.Paragraphs.Count > 0)
                    {
                        Clipboard.SetText(tmp.ToText(new SubRip()));
                    }
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _mainListViewCopyText)
                {
                    var sb = new StringBuilder();
                    foreach (int i in SubtitleListview1.SelectedIndices)
                    {
                        var p = _subtitle.GetParagraphOrDefault(i);
                        if (p != null)
                            sb.AppendLine(p.Text + Environment.NewLine);
                    }
                    if (sb.Length > 0)
                    {
                        Clipboard.SetText(sb.ToString().Trim());
                    }
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _mainListViewAutoDuration)
                {
                    MakeAutoDurationSelectedLines();
                }
                else if (e.KeyData == _mainListViewFocusWaveform)
                {
                    if (audioVisualizer.CanFocus)
                    {
                        audioVisualizer.Focus();
                        e.SuppressKeyPress = true;
                    }
                }
                else if (e.KeyData == _mainListViewGoToNextError)
                {
                    GoToNextSynaxError();
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) //Ctrl+V = Paste from clipboard
                {
                    if (Clipboard.ContainsText())
                    {
                        var text = Clipboard.GetText();
                        var tmp = new Subtitle();
                        var format = new SubRip();
                        var list = new List<string>(text.SplitToLines());
                        format.LoadSubtitle(tmp, list, null);
                        if (SubtitleListview1.SelectedItems.Count == 1 && tmp.Paragraphs.Count > 0)
                        {
                            MakeHistoryForUndo(_language.BeforeInsertLine);
                            _makeHistoryPaused = true;
                            Paragraph lastParagraph = null;
                            Paragraph lastTempParagraph = null;
                            var selectedIndices = new List<int>();
                            int firstIndex = FirstSelectedIndex;
                            foreach (var p in tmp.Paragraphs)
                            {
                                firstIndex++;
                                selectedIndices.Add(firstIndex);
                                InsertAfter();
                                textBoxListViewText.Text = p.Text;
                                if (lastParagraph != null)
                                {
                                    double millisecondsBetween = p.StartTime.TotalMilliseconds - lastTempParagraph.EndTime.TotalMilliseconds;
                                    timeUpDownStartTime.TimeCode = new TimeCode(lastParagraph.EndTime.TotalMilliseconds + millisecondsBetween);
                                }
                                SetDurationInSeconds(p.Duration.TotalSeconds);
                                lastParagraph = _subtitle.GetParagraphOrDefault(_subtitleListViewIndex);
                                lastTempParagraph = p;
                            }
                            SubtitleListview1.SelectIndexAndEnsureVisible(selectedIndices[0], true);
                            foreach (var idx in selectedIndices)
                            {
                                SubtitleListview1.Items[idx].Selected = true;
                            }
                            RestartHistory();
                        }
                        else if (SubtitleListview1.Items.Count == 0 && tmp.Paragraphs.Count > 0)
                        { // insert into empty subtitle
                            MakeHistoryForUndo(_language.BeforeInsertLine);
                            foreach (var p in tmp.Paragraphs)
                            {
                                _subtitle.Paragraphs.Add(p);
                            }
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                        }
                        else if (SubtitleListview1.Items.Count > 1 && tmp.Paragraphs.Count > 0)
                        {
                            // multiple lines selected - first delete, then insert
                            int firstIndex = FirstSelectedIndex;
                            if (firstIndex >= 0)
                            {
                                MakeHistoryForUndo(_language.BeforeInsertLine);
                                _makeHistoryPaused = true;

                                DeleteSelectedLines();
                                var selectedIndices = new List<int>();
                                foreach (var p in tmp.Paragraphs)
                                {
                                    _subtitle.Paragraphs.Insert(firstIndex, p);
                                    selectedIndices.Add(firstIndex);
                                    firstIndex++;
                                }
                                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                                SubtitleListview1.SelectIndexAndEnsureVisible(selectedIndices[0], true);
                                foreach (var idx in selectedIndices)
                                {
                                    SubtitleListview1.Items[idx].Selected = true;
                                }
                                RestartHistory();
                            }
                        }
                        else if (list.Count >= 1 && list.Count < 4)
                        {
                            // less than 4 lines of text, just insert into first selected
                            textBoxListViewText.Text = text.Trim();
                        }
                        else if (list.Count > 1 && list.Count < 2000)
                        {
                            MakeHistoryForUndo(_language.BeforeInsertLine);
                            _makeHistoryPaused = true;
                            foreach (var line in list)
                            {
                                if (!string.IsNullOrWhiteSpace(line))
                                {
                                    InsertAfter();
                                    textBoxListViewText.Text = Utilities.AutoBreakLine(line);
                                }
                            }
                            RestartHistory();
                        }
                    }
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyCode == Keys.X && e.Modifiers == Keys.Control) //Ctrl+X = Cut to clipboard
                {
                    var tmp = new Subtitle();
                    foreach (int i in SubtitleListview1.SelectedIndices)
                    {
                        var p = _subtitle.GetParagraphOrDefault(i);
                        if (p != null)
                            tmp.Paragraphs.Add(new Paragraph(p));
                    }
                    e.SuppressKeyPress = true;
                    _cutText = tmp.ToText(new SubRip());
                    ToolStripMenuItemDeleteClick(null, null);
                }
                else if (e.KeyCode == Keys.A && e.Modifiers == Keys.Control) //SelectAll
                {
                    foreach (ListViewItem item in SubtitleListview1.Items)
                        item.Selected = true;
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyCode == Keys.D && e.Modifiers == Keys.Control) //SelectFirstSelectedItemOnly
                {
                    int itemsCount = SubtitleListview1.SelectedItems.Count - 1;
                    if (itemsCount > 0)
                    {
                        do
                        {
                            SubtitleListview1.SelectedItems[itemsCount--].Selected = false;
                        }
                        while (itemsCount > 0);
                        e.SuppressKeyPress = true;
                    }
                }
                else if (e.KeyCode == Keys.Delete && SubtitleListview1.SelectedItems.Count > 0) //Delete
                {
                    ToolStripMenuItemDeleteClick(null, null);
                }
                else if (e.KeyData == _mainInsertBefore)
                {
                    InsertBefore();
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _mainInsertAfter)
                {
                    InsertAfter();
                    e.SuppressKeyPress = true;
                }
                else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Home)
                {
                    SubtitleListview1.FirstVisibleIndex = -1;
                    SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                    e.SuppressKeyPress = true;
                }
                else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.End)
                {
                    SubtitleListview1.SelectIndexAndEnsureVisible(SubtitleListview1.Items.Count - 1, true);
                    e.SuppressKeyPress = true;
                }
                else if (e.Modifiers == Keys.None && e.KeyCode == Keys.Enter)
                {
                    SubtitleListview1_MouseDoubleClick(null, null);
                }
            }

            private void GoToNextSynaxError()
            {
                int idx = FirstSelectedIndex + 1;
                try
                {
                    for (int i = idx; i < _subtitle.Paragraphs.Count - 1; i++)
                    {
                        var item = SubtitleListview1.Items[i];
                        if (item.SubItems[SubtitleListview1.ColumnIndexDuration].BackColor == Configuration.Settings.Tools.ListViewSyntaxErrorColor ||
                            item.SubItems[SubtitleListview1.ColumnIndexText].BackColor == Configuration.Settings.Tools.ListViewSyntaxErrorColor ||
                            item.SubItems[SubtitleListview1.ColumnIndexStart].BackColor == Configuration.Settings.Tools.ListViewSyntaxErrorColor ||
                            (SubtitleListview1.ColumnIndexCps >= 0 && item.SubItems[SubtitleListview1.ColumnIndexCps].BackColor == Configuration.Settings.Tools.ListViewSyntaxErrorColor) ||
                            (SubtitleListview1.ColumnIndexWpm >= 0 && item.SubItems[SubtitleListview1.ColumnIndexWpm].BackColor == Configuration.Settings.Tools.ListViewSyntaxErrorColor))
                        {
                            SubtitleListview1.SelectIndexAndEnsureVisible(i, true);
                            return;
                        }
                    }
                }
                catch
                {
                }
            }

            private void RestartHistory()
            {
                _listViewTextUndoLast = null;
                _listViewTextUndoIndex = -1;
                _listViewTextTicks = -1;
                _listViewAlternateTextUndoLast = null;
                _listViewAlternateTextTicks = -1;
                _undoIndex = _subtitle.HistoryItems.Count - 1;
                _makeHistoryPaused = false;
            }

            private void AutoBalanceLinesAndAllow2PlusLines()
            {
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    MakeHistoryForUndo(_language.BeforeAutoBalanceSelectedLines);
                    string language = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle);
                    string languageOriginal = string.Empty;
                    if (_subtitleAlternate != null)
                        LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitleAlternate);
                    foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                    {
                        var p = _subtitle.GetParagraphOrDefault(item.Index);
                        if (p != null)
                        {
                            string s = Utilities.AutoBreakLineMoreThanTwoLines(p.Text, Configuration.Settings.General.SubtitleLineMaximumLength, language);
                            if (s != p.Text)
                            {
                                p.Text = s;
                                SubtitleListview1.SetText(item.Index, p.Text);
                            }
                            if (_subtitleAlternate != null)
                            {
                                var original = Utilities.GetOriginalParagraph(item.Index, p, _subtitleAlternate.Paragraphs);
                                if (original != null)
                                {
                                    string s2 = Utilities.AutoBreakLineMoreThanTwoLines(original.Text, Configuration.Settings.General.SubtitleLineMaximumLength, languageOriginal);
                                    if (s2 != original.Text)
                                    {
                                        original.Text = s2;
                                        SubtitleListview1.SetAlternateText(item.Index, original.Text);
                                    }
                                }
                            }
                        }
                    }
                    ShowSource();
                    RefreshSelectedParagraph();
                }
            }

            private void AdjustDisplayTimeForSelectedLinesToolStripMenuItemClick(object sender, EventArgs e)
            {
                AdjustDisplayTime(true);
            }

            private void FixCommonErrorsInSelectedLinesToolStripMenuItemClick(object sender, EventArgs e)
            {
                FixCommonErrors(true);
            }

            private void FindDoubleWordsToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }
                var regex = new Regex(@"\b(\w+)\s+\1\b");
                _clearLastFind = true;
                if (_findHelper != null)
                {
                    _clearLastFindType = _findHelper.FindReplaceType.FindType;
                    _clearLastFindText = _findHelper.FindText;
                }
                _findHelper = new FindReplaceDialogHelper(new ReplaceType { FindType = FindType.RegEx }, string.Format(_language.DoubleWordsViaRegEx, regex), regex, string.Empty, _subtitleListViewIndex);

                ReloadFromSourceView();
                FindNext();
            }

            private void ChangeCasingForSelectedLinesToolStripMenuItemClick(object sender, EventArgs e)
            {
                ChangeCasing(true);
            }

            private void CenterFormOnCurrentScreen()
            {
                var screen = Screen.FromControl(this);
                Left = screen.Bounds.X + ((screen.Bounds.Width - Width) / 2);
                Top = screen.Bounds.Y + ((screen.Bounds.Height - Height) / 2);
            }

            private void SortSubtitle(SubtitleSortCriteria subtitleSortCriteria, string description)
            {
                Paragraph firstSelectedParagraph = null;
                if (SubtitleListview1.SelectedItems.Count > 0)
                    firstSelectedParagraph = _subtitle.Paragraphs[SubtitleListview1.SelectedItems[0].Index];

                _subtitleListViewIndex = -1;
                MakeHistoryForUndo(string.Format(_language.BeforeSortX, description));
                _subtitle.Sort(subtitleSortCriteria);
                if (descendingToolStripMenuItem.Checked)
                    _subtitle.Paragraphs.Reverse();
                ShowSource();
                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                SubtitleListview1.SelectIndexAndEnsureVisible(firstSelectedParagraph);
                ShowStatus(string.Format(_language.SortedByX, description));
            }

            private void SortNumberToolStripMenuItemClick(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.Number, (sender as ToolStripItem).Text);
            }

            private void SortStartTimeToolStripMenuItemClick(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.StartTime, (sender as ToolStripItem).Text);
            }

            private void SortEndTimeToolStripMenuItemClick(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.EndTime, (sender as ToolStripItem).Text);
            }

            private void SortDisplayTimeToolStripMenuItemClick(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.Duration, (sender as ToolStripItem).Text);
            }

            private void SortTextMaxLineLengthToolStripMenuItemClick(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.TextMaxLineLength, (sender as ToolStripItem).Text);
            }

            private void SortTextTotalLengthToolStripMenuItemClick(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.TextTotalLength, (sender as ToolStripItem).Text);
            }

            private void SortTextNumberOfLinesToolStripMenuItemClick(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.TextNumberOfLines, (sender as ToolStripItem).Text);
            }

            private void SortTextAlphabeticallytoolStripMenuItemClick(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.Text, (sender as ToolStripItem).Text);
            }

            private void textCharssecToolStripMenuItem_Click(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.TextCharactersPerSeconds, (sender as ToolStripItem).Text);
            }

            private void ChangeLanguageToolStripMenuItemClick(object sender, EventArgs e)
            {
                using (var cl = new ChooseLanguage())
                {
                    if (cl.ShowDialog(this) == DialogResult.OK)
                    {
                        SetLanguage(cl.CultureName);
                        Configuration.Settings.Save();
                    }
                }
            }

            private void SetLanguage(string cultureName)
            {
                if (string.IsNullOrEmpty(cultureName))
                {
                    cultureName = "en-US";
                }
                if (cultureName != "en-US")
                {
                    try
                    {
                        Configuration.Settings.Language = Language.Load(Path.Combine(Configuration.BaseDirectory, "Languages", cultureName + ".xml"));
                    }
                    catch (Exception ex)
                    {
                        var cap = "Language file load error";
                        var msg = "Could not load language file " + cultureName + ".xml" +
                                  "\n\nError Message:\n" + ex.Message +
                                  "\n\nStack Trace:\n" + ex.StackTrace;
                        MessageBox.Show(this, msg, cap);
                        cultureName = "en-US";
                    }
                }
                if (cultureName == "en-US")
                {
                    Configuration.Settings.Language = new Language(); // default is en-US
                }
                Configuration.Settings.General.Language = cultureName;
                _languageGeneral = Configuration.Settings.Language.General;
                _language = Configuration.Settings.Language.Main;
                InitializeLanguage();
            }

            private void ToolStripMenuItemCompareClick(object sender, EventArgs e)
            {
                var compareForm = new Compare();
                if (_subtitleAlternate != null && _subtitleAlternateFileName != null)
                    compareForm.Initialize(_subtitle, _fileName, _subtitleAlternate, _subtitleAlternateFileName);
                else
                    compareForm.Initialize(_subtitle, _fileName, _languageGeneral.CurrentSubtitle);
                compareForm.Show(this);
            }

            private void ToolStripMenuItemAutoBreakLinesClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var autoBreakUnbreakLines = new AutoBreakUnbreakLines())
                {
                    var selectedLines = new Subtitle();
                    foreach (int index in SubtitleListview1.SelectedIndices)
                        selectedLines.Paragraphs.Add(_subtitle.Paragraphs[index]);
                    autoBreakUnbreakLines.Initialize(selectedLines, true);

                    if (autoBreakUnbreakLines.ShowDialog() == DialogResult.OK && autoBreakUnbreakLines.FixedText.Count > 0)
                    {
                        MakeHistoryForUndo(_language.BeforeAutoBalanceSelectedLines);
                        SubtitleListview1.BeginUpdate();
                        foreach (int index in SubtitleListview1.SelectedIndices)
                        {
                            var p = _subtitle.GetParagraphOrDefault(index);
                            if (autoBreakUnbreakLines.FixedText.ContainsKey(p.ID))
                            {
                                p.Text = autoBreakUnbreakLines.FixedText[p.ID];
                                SubtitleListview1.SetText(index, p.Text);
                                SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, index, p);
                            }
                        }
                        SubtitleListview1.EndUpdate();
                        RefreshSelectedParagraph();
                        ShowStatus(string.Format(_language.NumberOfLinesAutoBalancedX, autoBreakUnbreakLines.FixedText.Count));
                    }
                }
            }

            private void ToolStripMenuItemUnbreakLinesClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var autoBreakUnbreakLines = new AutoBreakUnbreakLines())
                {
                    var selectedLines = new Subtitle();
                    foreach (int index in SubtitleListview1.SelectedIndices)
                        selectedLines.Paragraphs.Add(_subtitle.Paragraphs[index]);
                    autoBreakUnbreakLines.Initialize(selectedLines, false);

                    if (autoBreakUnbreakLines.ShowDialog() == DialogResult.OK && autoBreakUnbreakLines.FixedText.Count > 0)
                    {
                        MakeHistoryForUndo(_language.BeforeRemoveLineBreaksInSelectedLines);

                        SubtitleListview1.BeginUpdate();
                        foreach (int index in SubtitleListview1.SelectedIndices)
                        {
                            var p = _subtitle.GetParagraphOrDefault(index);
                            if (autoBreakUnbreakLines.FixedText.ContainsKey(p.ID))
                            {
                                p.Text = autoBreakUnbreakLines.FixedText[p.ID];
                                SubtitleListview1.SetText(index, p.Text);
                                SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, index, p);
                            }
                        }
                        SubtitleListview1.EndUpdate();
                        RefreshSelectedParagraph();
                        ShowStatus(string.Format(_language.NumberOfWithRemovedLineBreakX, autoBreakUnbreakLines.FixedText.Count));
                    }
                }
            }

            private void MultipleReplaceToolStripMenuItemClick(object sender, EventArgs e)
            {
                using (var multipleReplace = new MultipleReplace())
                {
                    multipleReplace.Initialize(_subtitle);
                    if (multipleReplace.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeMultipleReplace);
                        SaveSubtitleListviewIndices();

                        for (int i = 0; i < _subtitle.Paragraphs.Count; i++)
                        {
                            _subtitle.Paragraphs[i].Text = multipleReplace.FixedSubtitle.Paragraphs[i].Text;
                        }

                        _subtitle.RemoveParagraphsByIndices(multipleReplace.DeleteIndices);
                        _subtitle.Renumber();

                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                        RefreshSelectedParagraph();
                        ShowSource();
                        ShowStatus(string.Format(_language.NumberOfLinesReplacedX, multipleReplace.FixCount));
                    }
                }
            }

            private void ToolStripMenuItemImportDvdSubtitlesClick(object sender, EventArgs e)
            {
                if (!ContinueNewOrExit())
                {
                    return;
                }

                ImportDvdSubtitle(null);
            }

            private void ImportDvdSubtitle(string fileName)
            {
                using (var formSubRip = new DvdSubRip(Handle, fileName))
                {
                    if (formSubRip.ShowDialog(this) == DialogResult.OK)
                    {
                        using (var showSubtitles = new DvdSubRipChooseLanguage())
                        {
                            showSubtitles.Initialize(formSubRip.MergedVobSubPacks, formSubRip.Palette, formSubRip.Languages, formSubRip.SelectedLanguage);
                            if (formSubRip.Languages.Count == 1 || showSubtitles.ShowDialog(this) == DialogResult.OK)
                            {
                                using (var formSubOcr = new VobSubOcr())
                                {
                                    var subs = formSubRip.MergedVobSubPacks;
                                    if (showSubtitles.SelectedVobSubMergedPacks != null)
                                        subs = showSubtitles.SelectedVobSubMergedPacks;
                                    formSubOcr.Initialize(subs, formSubRip.Palette, Configuration.Settings.VobSubOcr, formSubRip.SelectedLanguage);
                                    if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                                    {
                                        MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle);
                                        FileNew();
                                        _subtitle.Paragraphs.Clear();
                                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                                        _subtitle.WasLoadedWithFrameNumbers = false;
                                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                                        foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs)
                                        {
                                            _subtitle.Paragraphs.Add(p);
                                        }

                                        ShowSource();
                                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                                        _subtitleListViewIndex = -1;
                                        SubtitleListview1.FirstVisibleIndex = -1;
                                        SubtitleListview1.SelectIndexAndEnsureVisible(0, true);

                                        _fileName = string.Empty;
                                        Text = Title;

                                        Configuration.Settings.Save();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            private void ToolStripMenuItemSubIdxClick1(object sender, EventArgs e)
            {
                if (ContinueNewOrExit())
                {
                    openFileDialog1.Title = _language.OpenVobSubFile;
                    openFileDialog1.FileName = string.Empty;
                    openFileDialog1.Filter = _language.VobSubFiles + "|*.sub";
                    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                    {
                        ImportAndOcrVobSubSubtitleNew(openFileDialog1.FileName, false);
                        openFileDialog1.InitialDirectory = Path.GetDirectoryName(openFileDialog1.FileName);
                    }
                }
            }

            private void SubtitleListview1_MouseDoubleClick(object sender, MouseEventArgs e)
            {
                if (Configuration.Settings.General.ListViewDoubleClickAction == 1)
                {
                    GotoSubPositionAndPause();
                }
                else if (Configuration.Settings.General.ListViewDoubleClickAction == 2)
                {
                    if (AutoRepeatContinueOn || AutoRepeatOn)
                        PlayCurrent();
                    else
                        buttonBeforeText_Click(null, null);
                }
                else if (Configuration.Settings.General.ListViewDoubleClickAction == 3)
                {
                    GotoSubPositionAndPause(-0.5);
                }
                else if (Configuration.Settings.General.ListViewDoubleClickAction == 4)
                {
                    GotoSubPositionAndPause(-1.0);
                }
                else if (Configuration.Settings.General.ListViewDoubleClickAction == 5)
                {
                    if (AutoRepeatContinueOn || AutoRepeatOn)
                        PlayCurrent();
                    else
                    {
                        if (SubtitleListview1.SelectedItems.Count > 0)
                        {
                            int index = SubtitleListview1.SelectedItems[0].Index;

                            mediaPlayer.Pause();
                            double pos = _subtitle.Paragraphs[index].StartTime.TotalSeconds;
                            if (pos > 1)
                                mediaPlayer.CurrentPosition = (_subtitle.Paragraphs[index].StartTime.TotalSeconds) - 1.0;
                            else
                                mediaPlayer.CurrentPosition = _subtitle.Paragraphs[index].StartTime.TotalSeconds;
                            mediaPlayer.Play();
                        }
                    }
                }
                else if (Configuration.Settings.General.ListViewDoubleClickAction == 6)
                {
                    GotoSubPositionAndPause();
                    textBoxListViewText.Focus();
                }
                else if (Configuration.Settings.General.ListViewDoubleClickAction == 7)
                {
                    textBoxListViewText.Focus();
                }
            }

            private void AddWordToNameListToolStripMenuItemClick(object sender, EventArgs e)
            {
                using (var addToNamesList = new AddToNameList())
                {
                    addToNamesList.Initialize(_subtitle, textBoxListViewText.SelectedText);
                    if (addToNamesList.ShowDialog(this) == DialogResult.OK)
                        ShowStatus(string.Format(_language.NameXAddedToNameList, addToNamesList.NewName));
                    else if (!string.IsNullOrEmpty(addToNamesList.NewName))
                        ShowStatus(string.Format(_language.NameXNotAddedToNameList, addToNamesList.NewName));
                }
            }

            private bool IsUnicode
            {
                get
                {
                    var enc = GetCurrentEncoding();
                    return enc == Encoding.UTF8 || enc == Encoding.Unicode || enc == Encoding.UTF7 || enc == Encoding.UTF32 || enc == Encoding.BigEndianUnicode;
                }
            }

            private void EditToolStripMenuItemDropDownOpening(object sender, EventArgs e)
            {
                toolStripMenuItemRtlUnicodeControlChars.Visible = IsUnicode;
                if (!IsUnicode || _subtitleListViewIndex == -1)
                {
                    toolStripMenuItemInsertUnicodeCharacter.Visible = false;
                    toolStripSeparatorInsertUnicodeCharacter.Visible = false;
                }
                else
                {
                    if (toolStripMenuItemInsertUnicodeCharacter.DropDownItems.Count == 0)
                    {
                        foreach (var s in Configuration.Settings.Tools.UnicodeSymbolsToInsert.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            toolStripMenuItemInsertUnicodeCharacter.DropDownItems.Add(s, null, InsertUnicodeGlyphAllowMultiLine);
                            if (Environment.OSVersion.Version.Major < 6 && Configuration.Settings.General.SubtitleFontName == Utilities.WinXP2KUnicodeFontName) // 6 == Vista/Win2008Server/Win7
                                toolStripMenuItemInsertUnicodeCharacter.DropDownItems[toolStripMenuItemInsertUnicodeCharacter.DropDownItems.Count - 1].Font = new Font(Utilities.WinXP2KUnicodeFontName, toolStripMenuItemInsertUnicodeSymbol.Font.Size);
                        }
                    }
                    toolStripMenuItemInsertUnicodeCharacter.Visible = toolStripMenuItemInsertUnicodeCharacter.DropDownItems.Count > 0;
                    toolStripSeparatorInsertUnicodeCharacter.Visible = toolStripMenuItemInsertUnicodeCharacter.DropDownItems.Count > 0;
                }
                lock (_syncUndo)
                {
                    toolStripMenuItemUndo.Enabled = _subtitle != null && _subtitle.CanUndo && _undoIndex >= 0;
                    toolStripMenuItemRedo.Enabled = _subtitle != null && _subtitle.CanUndo && _undoIndex < _subtitle.HistoryItems.Count - 1;
                }
                showHistoryforUndoToolStripMenuItem.Enabled = _subtitle != null && _subtitle.CanUndo;
                toolStripMenuItemShowOriginalInPreview.Visible = SubtitleListview1.IsAlternateTextColumnVisible;

                if (_networkSession != null)
                {
                    toolStripMenuItemUndo.Enabled = false;
                    toolStripMenuItemRedo.Enabled = false;
                    showHistoryforUndoToolStripMenuItem.Enabled = false;
                }
            }

            private void InsertUnicodeGlyph(object sender, EventArgs e)
            {
                var item = sender as ToolStripItem;
                if (item != null)
                    PasteIntoActiveTextBox(item.Text);
            }

            private void InsertUnicodeGlyphAllowMultiLine(object sender, EventArgs e)
            {
                var item = sender as ToolStripItem;
                if (item != null)
                    PasteIntoActiveTextBox(item.Text, true);
            }

            private void ToolStripMenuItemAutoMergeShortLinesClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var formMergeShortLines = new MergeShortLines())
                {
                    formMergeShortLines.Initialize(_subtitle);
                    if (formMergeShortLines.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeMergeShortLines);
                        _subtitle.Paragraphs.Clear();
                        foreach (var p in formMergeShortLines.MergedSubtitle.Paragraphs)
                            _subtitle.Paragraphs.Add(p);
                        ShowStatus(string.Format(_language.MergedShortLinesX, formMergeShortLines.NumberOfMerges));
                        SaveSubtitleListviewIndices();
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void toolStripMenuItemAutoSplitLongLines_Click(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var splitLongLines = new SplitLongLines())
                {
                    splitLongLines.Initialize(_subtitle);
                    if (splitLongLines.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeSplitLongLines);
                        _subtitle.Paragraphs.Clear();
                        foreach (var p in splitLongLines.SplittedSubtitle.Paragraphs)
                            _subtitle.Paragraphs.Add(p);
                        ShowStatus(string.Format(_language.LongLinesSplitX, splitLongLines.NumberOfSplits));
                        SaveSubtitleListviewIndices();
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void SetMinimalDisplayTimeDifferenceToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                using (var setMinDisplayDiff = new SetMinimumDisplayTimeBetweenParagraphs())
                {
                    setMinDisplayDiff.Initialize(_subtitle);
                    if (setMinDisplayDiff.ShowDialog() == DialogResult.OK && setMinDisplayDiff.FixCount > 0)
                    {
                        MakeHistoryForUndo(_language.BeforeSetMinimumDisplayTimeBetweenParagraphs);
                        _subtitle.Paragraphs.Clear();
                        foreach (var p in setMinDisplayDiff.FixedSubtitle.Paragraphs)
                            _subtitle.Paragraphs.Add(p);
                        _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        ShowStatus(string.Format(_language.XMinimumDisplayTimeBetweenParagraphsChanged, setMinDisplayDiff.FixCount));
                        SaveSubtitleListviewIndices();
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void ToolStripMenuItemImportTextClick(object sender, EventArgs e)
            {
                ImportPlainText(null);
            }

            private void ImportPlainText(string fileName)
            {
                using (var importText = new ImportText(fileName, this))
                {
                    if (importText.ShowDialog(this) == DialogResult.OK)
                    {
                        if (ContinueNewOrExit())
                        {
                            MakeHistoryForUndo(_language.BeforeImportText);

                            ResetSubtitle();
                            if (!string.IsNullOrEmpty(importText.VideoFileName))
                            {
                                if (!Configuration.Settings.General.DisableVideoAutoLoading)
                                {
                                    OpenVideo(importText.VideoFileName);
                                }
                                _fileName = importText.VideoFileName;
                                _converted = true;
                            }

                            _subtitleListViewIndex = -1;
                            if (importText.Format != null)
                            {
                                SetCurrentFormat(importText.Format);
                            }
                            _subtitle = new Subtitle(importText.FixedSubtitle.Paragraphs, _subtitle.HistoryItems);
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                            ShowStatus(_language.TextImported);
                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                        }
                    }
                }
            }

            private void toolStripMenuItemPointSync_Click(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }
                using (var pointSync = new SyncPointsSync())
                {
                    pointSync.Initialize(_subtitle, _fileName, _videoFileName, _videoAudioTrackNumber);
                    mediaPlayer.Pause();
                    if (pointSync.ShowDialog(this) == DialogResult.OK)
                    {
                        _subtitleListViewIndex = -1;
                        MakeHistoryForUndo(_language.BeforePointSynchronization);
                        _subtitle.Paragraphs.Clear();
                        foreach (var p in pointSync.FixedSubtitle.Paragraphs)
                            _subtitle.Paragraphs.Add(p);
                        _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        ShowStatus(_language.PointSynchronizationDone);
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    }
                    Activate();
                    _videoFileName = pointSync.VideoFileName;
                }
            }

            private void pointSyncViaOtherSubtitleToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }
                using (var pointSync = new SyncPointsSync())
                {
                    openFileDialog1.Title = _language.OpenOtherSubtitle;
                    openFileDialog1.FileName = string.Empty;
                    openFileDialog1.Filter = UiUtil.SubtitleExtensionFilter.Value;
                    if (openFileDialog1.ShowDialog() == DialogResult.OK && File.Exists(openFileDialog1.FileName))
                    {
                        var file = new FileInfo(openFileDialog1.FileName);
                        var fileName = file.FullName;
                        var extension = file.Extension.ToLowerInvariant();

                        // TODO: Check for mkv etc
                        if (extension == ".sub")
                        {
                            if (IsVobSubFile(fileName, false))
                            {
                                MessageBox.Show(_language.NoSupportHereVobSub);
                                return;
                            }
                        }

                        if (extension == ".sup")
                        {
                            if (FileUtil.IsBluRaySup(fileName))
                            {
                                MessageBox.Show(_language.NoSupportHereBluRaySup);
                                return;
                            }
                            else if (FileUtil.IsSpDvdSup(fileName))
                            {
                                MessageBox.Show(_language.NoSupportHereDvdSup);
                                return;
                            }
                        }

                        var sub = new Subtitle();
                        if (extension == ".mkv" || extension == ".mks")
                        {
                            using (var matroska = new MatroskaFile(fileName))
                            {
                                if (matroska.IsValid)
                                {
                                    var subtitleList = matroska.GetTracks(true);
                                    if (subtitleList.Count > 1)
                                    {
                                        using (var subtitleChooser = new MatroskaSubtitleChooser("mkv"))
                                        {
                                            subtitleChooser.Initialize(subtitleList);
                                            if (_loading)
                                            {
                                                subtitleChooser.Icon = (Icon)Icon.Clone();
                                                subtitleChooser.ShowInTaskbar = true;
                                                subtitleChooser.ShowIcon = true;
                                            }
                                            if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                            {
                                                sub = LoadMatroskaSubtitleForSync(subtitleList[subtitleChooser.SelectedIndex], matroska);
                                            }
                                        }
                                    }
                                    else if (subtitleList.Count > 0)
                                    {
                                        sub = LoadMatroskaSubtitleForSync(subtitleList[0], matroska);
                                    }
                                    else
                                    {
                                        MessageBox.Show(_language.NoSubtitlesFound);
                                        return;
                                    }
                                }
                            }
                        }

                        if (extension == ".divx" || extension == ".avi")
                        {
                            MessageBox.Show(_language.NoSupportHereDivx);
                            return;
                        }

                        if ((extension == ".mp4" || extension == ".m4v" || extension == ".3gp") && file.Length > 10000)
                        {
                            var mp4Parser = new MP4Parser(fileName);
                            var mp4SubtitleTracks = mp4Parser.GetSubtitleTracks();
                            if (mp4SubtitleTracks.Count == 0)
                            {
                                MessageBox.Show(_language.NoSubtitlesFound);
                                return;
                            }
                            else if (mp4SubtitleTracks.Count == 1)
                            {
                                sub = LoadMp4SubtitleForSync(mp4SubtitleTracks[0]);
                            }
                            else
                            {
                                using (var subtitleChooser = new MatroskaSubtitleChooser("mp4"))
                                {
                                    subtitleChooser.Initialize(mp4SubtitleTracks);
                                    if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                    {
                                        sub = LoadMp4SubtitleForSync(mp4SubtitleTracks[0]);
                                    }
                                }
                            }
                        }

                        if (file.Length > 1024 * 1024 * 10 && sub.Paragraphs.Count == 0) // max 10 mb
                        {
                            var text = string.Format(_language.FileXIsLargerThan10MB + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, fileName);
                            if (MessageBox.Show(this, text, Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                                return;
                        }

                        sub.Renumber();
                        if (sub.Paragraphs.Count == 0)
                        {
                            Encoding enc;
                            SubtitleFormat f = sub.LoadSubtitle(fileName, out enc, null);
                            if (f == null)
                            {
                                ShowUnknownSubtitle();
                                return;
                            }
                        }

                        pointSync.Initialize(_subtitle, _fileName, _videoFileName, _videoAudioTrackNumber, fileName, sub);
                        mediaPlayer.Pause();
                        if (pointSync.ShowDialog(this) == DialogResult.OK)
                        {
                            _subtitleListViewIndex = -1;
                            MakeHistoryForUndo(_language.BeforePointSynchronization);
                            _subtitle.Paragraphs.Clear();
                            foreach (var p in pointSync.FixedSubtitle.Paragraphs)
                                _subtitle.Paragraphs.Add(p);
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                            ShowStatus(_language.PointSynchronizationDone);
                            ShowSource();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        }
                        _videoFileName = pointSync.VideoFileName;
                    }
                }
            }

            private void toolStripMenuItemImportTimeCodes_Click(object sender, EventArgs e)
            {
                if (_subtitle.Paragraphs.Count < 1)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                openFileDialog1.Title = _languageGeneral.OpenSubtitle;
                openFileDialog1.FileName = string.Empty;
                openFileDialog1.Filter = UiUtil.SubtitleExtensionFilter.Value;
                if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    Encoding encoding;
                    var timeCodeSubtitle = new Subtitle();
                    SubtitleFormat format = null;

                    if (format == null &&
                        openFileDialog1.FileName.EndsWith(".sup", StringComparison.OrdinalIgnoreCase) &&
                        FileUtil.IsBluRaySup(openFileDialog1.FileName))
                    {
                        var log = new StringBuilder();
                        var subtitles = BluRaySupParser.ParseBluRaySup(openFileDialog1.FileName, log);
                        if (subtitles.Count > 0)
                        {
                            foreach (var sup in subtitles)
                            {
                                timeCodeSubtitle.Paragraphs.Add(new Paragraph(sup.StartTimeCode, sup.EndTimeCode, string.Empty));
                            }
                            format = new SubRip(); // just to set format to something
                        }
                    }

                    if (format == null)
                    {
                        format = timeCodeSubtitle.LoadSubtitle(openFileDialog1.FileName, out encoding, null);
                    }

                    if (format == null)
                    {
                        var formats = new SubtitleFormat[]
                        {
                            new FinalCutProImage(),
                            new SpuImage(),
                            new Ebu(),
                            new BdnXml(),
                            new Pac(),
                            new Cavena890(),
                            new TimeCodesOnly1(),
                            new TimeCodesOnly2()
                        };
                        format = timeCodeSubtitle.LoadBinaryFormatsformats(formats, openFileDialog1.FileName);
                    }

                    if (format == null)
                    {
                        ShowUnknownSubtitle();
                        return;
                    }

                    if (timeCodeSubtitle.Paragraphs.Count != _subtitle.Paragraphs.Count)
                    {
                        var text = string.Format(_language.ImportTimeCodesDifferentNumberOfLinesWarning, timeCodeSubtitle.Paragraphs.Count, _subtitle.Paragraphs.Count);
                        if (MessageBox.Show(this, text, _title, MessageBoxButtons.YesNo) == DialogResult.No)
                            return;
                    }

                    MakeHistoryForUndo(_language.BeforeTimeCodeImport);

                    if (GetCurrentSubtitleFormat().IsFrameBased)
                        timeCodeSubtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                    else
                        timeCodeSubtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                    int count = 0;
                    for (int i = 0; i < timeCodeSubtitle.Paragraphs.Count; i++)
                    {
                        var existing = _subtitle.GetParagraphOrDefault(i);

                        var newTimeCode = timeCodeSubtitle.GetParagraphOrDefault(i);
                        if (existing == null || newTimeCode == null)
                            break;

                        Paragraph original = null;
                        if (existing != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle &&
                            _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                        {
                            original = Utilities.GetOriginalParagraph(i, existing, _subtitleAlternate.Paragraphs);
                        }

                        existing.StartTime.TotalMilliseconds = newTimeCode.StartTime.TotalMilliseconds;
                        existing.EndTime.TotalMilliseconds = newTimeCode.EndTime.TotalMilliseconds;
                        existing.StartFrame = newTimeCode.StartFrame;
                        existing.EndFrame = newTimeCode.EndFrame;

                        if (original != null)
                        {
                            original.StartTime.TotalMilliseconds = newTimeCode.StartTime.TotalMilliseconds;
                            original.EndTime.TotalMilliseconds = newTimeCode.EndTime.TotalMilliseconds;
                            original.StartFrame = newTimeCode.StartFrame;
                            original.EndFrame = newTimeCode.EndFrame;
                        }

                        count++;
                    }
                    ShowStatus(string.Format(_language.TimeCodeImportedFromXY, Path.GetFileName(openFileDialog1.FileName), count));
                    SaveSubtitleListviewIndices();
                    ShowSource();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    RestoreSubtitleListviewIndices();
                }
            }

            private void toolStripMenuItemTranslationMode_Click(object sender, EventArgs e)
            {
                if (_subtitle == null || _subtitle.Paragraphs.Count == 0)
                    return;

                if (SubtitleListview1.IsAlternateTextColumnVisible)
                {
                    SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.TextAlternate);
                    SubtitleListview1.AutoSizeAllColumns(this);
                    _subtitleAlternate = new Subtitle();
                    _subtitleAlternateFileName = null;

                    buttonUnBreak.Visible = true;
                    buttonAutoBreak.Visible = true;
                    textBoxListViewTextAlternate.Visible = false;
                    labelAlternateText.Visible = false;
                    labelAlternateCharactersPerSecond.Visible = false;
                    labelTextAlternateLineLengths.Visible = false;
                    labelAlternateSingleLine.Visible = false;
                    labelTextAlternateLineTotal.Visible = false;
                    textBoxListViewText.Width = (groupBoxEdit.Width - (textBoxListViewText.Left + 8 + buttonUnBreak.Width));
                    textBoxListViewText.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

                    labelCharactersPerSecond.Left = textBoxListViewText.Left + (textBoxListViewText.Width - labelCharactersPerSecond.Width);
                    labelTextLineTotal.Left = textBoxListViewText.Left + (textBoxListViewText.Width - labelTextLineTotal.Width);
                }
                else
                {
                    OpenAlternateSubtitle();
                }
                SetTitle();
            }

            private void OpenAlternateSubtitle()
            {
                if (ContinueNewOrExitAlternate())
                {
                    SaveSubtitleListviewIndices();
                    openFileDialog1.Title = _languageGeneral.OpenOriginalSubtitleFile;
                    openFileDialog1.FileName = string.Empty;
                    openFileDialog1.Filter = UiUtil.SubtitleExtensionFilter.Value;
                    if (openFileDialog1.ShowDialog(this) != DialogResult.OK)
                        return;

                    if (!LoadAlternateSubtitleFile(openFileDialog1.FileName))
                        return;

                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    RestoreSubtitleListviewIndices();

                    Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                    Configuration.Settings.Save();
                    UpdateRecentFilesUI();
                    MainResize();
                }
            }

            private bool LoadAlternateSubtitleFile(string fileName)
            {
                if (!File.Exists(fileName))
                    return false;

                var file = new FileInfo(fileName);

                if (file.Extension.Equals(".sub", StringComparison.OrdinalIgnoreCase) && IsVobSubFile(fileName, false))
                    return false;

                if (file.Length > 1024 * 1024 * 10) // max 10 mb
                {
                    var text = string.Format(_language.FileXIsLargerThan10MB + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, fileName);
                    if (MessageBox.Show(this, text, Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                        return false;
                }

                Encoding encoding;
                _subtitleAlternate = new Subtitle();
                _subtitleAlternateFileName = fileName;
                SubtitleFormat format = _subtitleAlternate.LoadSubtitle(fileName, out encoding, null);

                if (format == null)
                {
                    var ebu = new Ebu();
                    if (ebu.IsMine(null, fileName))
                    {
                        ebu.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = ebu;
                    }
                }
                if (format == null)
                {
                    var pac = new Pac();
                    if (pac.IsMine(null, fileName))
                    {
                        pac.BatchMode = true;
                        pac.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = pac;
                    }
                }
                if (format == null)
                {
                    var cavena890 = new Cavena890();
                    if (cavena890.IsMine(null, fileName))
                    {
                        cavena890.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = cavena890;
                    }
                }
                if (format == null)
                {
                    var spt = new Spt();
                    if (spt.IsMine(null, fileName))
                    {
                        spt.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = spt;
                    }
                }
                if (format == null)
                {
                    var cheetahCaption = new CheetahCaption();
                    if (cheetahCaption.IsMine(null, fileName))
                    {
                        cheetahCaption.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = cheetahCaption;
                    }
                }
                if (format == null)
                {
                    var capMakerPlus = new CapMakerPlus();
                    if (capMakerPlus.IsMine(null, fileName))
                    {
                        capMakerPlus.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = capMakerPlus;
                    }
                }
                if (format == null)
                {
                    var captionate = new Captionate();
                    if (captionate.IsMine(null, fileName))
                    {
                        captionate.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = captionate;
                    }
                }
                if (format == null)
                {
                    var ultech130 = new Ultech130();
                    if (ultech130.IsMine(null, fileName))
                    {
                        ultech130.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = ultech130;
                    }
                }
                if (format == null)
                {
                    var nciCaption = new NciCaption();
                    if (nciCaption.IsMine(null, fileName))
                    {
                        nciCaption.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = nciCaption;
                    }
                }
                if (format == null)
                {
                    var tsb4 = new TSB4();
                    if (tsb4.IsMine(null, fileName))
                    {
                        tsb4.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = tsb4;
                    }
                }
                if (format == null)
                {
                    var avidStl = new AvidStl();
                    if (avidStl.IsMine(null, fileName))
                    {
                        avidStl.LoadSubtitle(_subtitleAlternate, null, fileName);
                        format = avidStl;
                    }
                }

                if (format == null)
                    return false;

                if (format.IsFrameBased)
                    _subtitleAlternate.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                else
                    _subtitleAlternate.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                SetupAlternateEdit();
                FixRightToLeftDependingOnLanguage();
                return true;
            }

            private void SetupAlternateEdit()
            {
                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate.Paragraphs.Count > 1)
                {
                    InsertMissingParagraphs(_subtitle, _subtitleAlternate);
                    InsertMissingParagraphs(_subtitleAlternate, _subtitle);

                    buttonUnBreak.Visible = false;
                    buttonAutoBreak.Visible = false;
                    buttonSplitLine.Visible = false;

                    textBoxListViewText.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
                    textBoxListViewText.Width = (groupBoxEdit.Width - (textBoxListViewText.Left + 10)) / 2;
                    textBoxListViewTextAlternate.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
                    textBoxListViewTextAlternate.Left = textBoxListViewText.Left + textBoxListViewText.Width + 3;
                    textBoxListViewTextAlternate.Width = textBoxListViewText.Width;
                    textBoxListViewTextAlternate.Visible = true;
                    labelAlternateText.Text = _languageGeneral.OriginalText;
                    labelAlternateText.Visible = true;
                    labelAlternateCharactersPerSecond.Visible = true;
                    labelTextAlternateLineLengths.Visible = true;
                    labelAlternateSingleLine.Visible = true;
                    labelTextAlternateLineTotal.Visible = true;

                    labelCharactersPerSecond.Left = textBoxListViewText.Left + (textBoxListViewText.Width - labelCharactersPerSecond.Width);
                    labelTextLineTotal.Left = textBoxListViewText.Left + (textBoxListViewText.Width - labelTextLineTotal.Width);
                    Main_Resize(null, null);
                    _changeAlternateSubtitleToString = _subtitleAlternate.ToText(new SubRip()).Trim();

                    SetTitle();
                }

                SubtitleListview1.ShowAlternateTextColumn(_languageGeneral.OriginalText);
                SubtitleListview1.AutoSizeAllColumns(this);
            }

            private static void InsertMissingParagraphs(Subtitle masterSubtitle, Subtitle insertIntoSubtitle)
            {
                int index = 0;
                foreach (var p in masterSubtitle.Paragraphs)
                {
                    var insertParagraph = Utilities.GetOriginalParagraph(index, p, insertIntoSubtitle.Paragraphs);
                    if (insertParagraph == null)
                    {
                        insertParagraph = new Paragraph(p);
                        insertParagraph.Text = string.Empty;
                        insertIntoSubtitle.InsertParagraphInCorrectTimeOrder(insertParagraph);
                    }
                    index++;
                }
                insertIntoSubtitle.Renumber();
            }

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            private void OpenVideo(string fileName)
            {
                if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
                {
                    if (_loading)
                    {
                        _videoFileName = fileName;
                        return;
                    }

                    var fi = new FileInfo(fileName);
                    if (fi.Length < 1000)
                        return;

                    ShowSubtitleTimer.Stop();
                    Cursor = Cursors.WaitCursor;
                    VideoFileName = fileName;
                    if (mediaPlayer.VideoPlayer != null)
                    {
                        mediaPlayer.PauseAndDisposePlayer();
                    }
                    _endSeconds = -1;

                    _videoInfo = ShowVideoInfo(fileName);
                    if (_videoInfo.FramesPerSecond > 0)
                        toolStripComboBoxFrameRate.Text = string.Format("{0:0.###}", _videoInfo.FramesPerSecond);

                    UiUtil.InitializeVideoPlayerAndContainer(fileName, _videoInfo, mediaPlayer, VideoLoaded, VideoEnded);
                    mediaPlayer.Volume = 0;
                    mediaPlayer.ShowFullscreenButton = Configuration.Settings.General.VideoPlayerShowFullscreenButton;
                    mediaPlayer.OnButtonClicked -= MediaPlayer_OnButtonClicked;
                    mediaPlayer.OnButtonClicked += MediaPlayer_OnButtonClicked;

                    if (_videoInfo.VideoCodec != null)
                        labelVideoInfo.Text = Path.GetFileName(fileName) + " " + _videoInfo.Width + "x" + _videoInfo.Height + " " + _videoInfo.VideoCodec.Trim();
                    else
                        labelVideoInfo.Text = Path.GetFileName(fileName) + " " + _videoInfo.Width + "x" + _videoInfo.Height;

                    if (_videoInfo.FramesPerSecond > 0)
                        labelVideoInfo.Text = labelVideoInfo.Text + " " + string.Format("{0:0.0##}", _videoInfo.FramesPerSecond);

                    string peakWaveFileName = WavePeakGenerator.GetPeakWaveFileName(fileName);
                    string spectrogramFolder = Nikse.SubtitleEdit.Core.WavePeakGenerator.SpectrogramDrawer.GetSpectrogramFolder(fileName);
                    if (File.Exists(peakWaveFileName))
                    {
                        audioVisualizer.WavePeaks = WavePeakData.FromDisk(peakWaveFileName);
                        audioVisualizer.Spectrogram = SpectrogramData.FromDisk(spectrogramFolder);
                        audioVisualizer.SceneChanges = SceneChangeHelper.FromDisk(_videoFileName);
                        toolStripComboBoxWaveform_SelectedIndexChanged(null, null);
                        SetWaveformPosition(0, 0, 0);
                        timerWaveform.Start();
                    }
                    Cursor = Cursors.Default;

                    SetUndockedWindowsTitle();
                    ShowSubtitleTimer.Start();
                }
            }

            private void MediaPlayer_OnButtonClicked(object sender, EventArgs e)
            {
                var pb = sender as PictureBox;
                if (pb != null && pb.Name == "_pictureBoxFullscreenOver")
                {
                    if (_videoPlayerUndocked != null && !_videoPlayerUndocked.IsDisposed && _videoPlayerUndocked.IsFullscreen)
                        _videoPlayerUndocked.NoFullscreen();
                    else
                        GoFullscreen();
                }
            }

            private void SetWaveformPosition(double startPositionSeconds, double currentVideoPositionSeconds, int subtitleIndex)
            {
                if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible && Configuration.Settings.General.ShowOriginalAsPreviewIfAvailable)
                {
                    int index = -1;
                    if (SubtitleListview1.SelectedItems.Count > 0 && _subtitle.Paragraphs.Count > 0)
                    {
                        int i = SubtitleListview1.SelectedItems[0].Index;
                        var p = Utilities.GetOriginalParagraph(i, _subtitle.Paragraphs[i], _subtitleAlternate.Paragraphs);
                        index = _subtitleAlternate.GetIndex(p);
                    }
                    audioVisualizer.SetPosition(startPositionSeconds, _subtitleAlternate, currentVideoPositionSeconds, index, SubtitleListview1.SelectedIndices);
                }
                else
                {
                    audioVisualizer.SetPosition(startPositionSeconds, _subtitle, currentVideoPositionSeconds, subtitleIndex, SubtitleListview1.SelectedIndices);
                }
            }

            private void VideoLoaded(object sender, EventArgs e)
            {
                if (_loading)
                {
                    Application.DoEvents();
                }

                mediaPlayer.Volume = Configuration.Settings.General.VideoPlayerDefaultVolume;
                timer1.Start();

                trackBarWaveformPosition.Maximum = (int)mediaPlayer.Duration;

                if (_videoLoadedGoToSubPosAndPause)
                {
                    Application.DoEvents();
                    _videoLoadedGoToSubPosAndPause = false;
                    GotoSubPositionAndPause();
                }
                mediaPlayer.Pause();
                mediaPlayer.UpdatePlayerName();
            }

            private void VideoEnded(object sender, EventArgs e)
            {
                mediaPlayer.Pause();
            }

            private static VideoInfo ShowVideoInfo(string fileName)
            {
                return UiUtil.GetVideoInfo(fileName);
            }

            private void TryToFindAndOpenVideoFile(string fileNameNoExtension)
            {
                string movieFileName = null;

                foreach (var extension in Utilities.VideoFileExtensions)
                {
                    var fileName = fileNameNoExtension + extension;
                    if (File.Exists(fileName))
                    {
                        bool skipLoad = false;
                        if (extension == ".m2ts" && new FileInfo(fileName).Length < 2000000)
                        {
                            var textSt = new TextST();
                            skipLoad = textSt.IsMine(null, fileName); // don't load TextST files as video/audio file
                        }

                        if (!skipLoad)
                        {
                            movieFileName = fileName;
                            break;
                        }
                    }
                }

                if (movieFileName != null)
                {
                    OpenVideo(movieFileName);
                }
                else
                {
                    var index = fileNameNoExtension.LastIndexOf('.');
                    if (index > 0)
                    {
                        TryToFindAndOpenVideoFile(fileNameNoExtension.Remove(index));
                    }
                }
            }

            internal void GoBackSeconds(double seconds)
            {
                if (mediaPlayer.CurrentPosition > seconds)
                    mediaPlayer.CurrentPosition -= seconds;
                else
                    mediaPlayer.CurrentPosition = 0;
                ShowSubtitle();
            }

            private void ButtonStartHalfASecondBackClick(object sender, EventArgs e)
            {
                GoBackSeconds(0.5);
            }

            private void ButtonStartThreeSecondsBackClick(object sender, EventArgs e)
            {
                GoBackSeconds(3.0);
            }

            private void ButtonStartOneMinuteBackClick(object sender, EventArgs e)
            {
                GoBackSeconds(60);
            }

            private void ButtonStartHalfASecondAheadClick(object sender, EventArgs e)
            {
                GoBackSeconds(-0.5);
            }

            private void ButtonStartThreeSecondsAheadClick(object sender, EventArgs e)
            {
                GoBackSeconds(-3);
            }

            private void ButtonStartOneMinuteAheadClick(object sender, EventArgs e)
            {
                GoBackSeconds(-60);
            }

            private void ShowSubtitleTimerTick(object sender, EventArgs e)
            {
                ShowSubtitleTimer.Stop();
                int oldIndex = FirstSelectedIndex;
                int index = ShowSubtitle();
                if (index != -1 && checkBoxSyncListViewWithVideoWhilePlaying.Checked && oldIndex != index)
                {
                    if ((DateTime.UtcNow.Ticks - _lastTextKeyDownTicks) > 10000 * 700) // only if last typed char was entered > 700 milliseconds
                    {
                        if (_endSeconds <= 0 || !checkBoxAutoRepeatOn.Checked)
                        {
                            if (!timerAutoDuration.Enabled && !mediaPlayer.IsPaused && (mediaPlayer.CurrentPosition > 0.2 || index > 0))
                            {
                                SubtitleListview1.BeginUpdate();
                                SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                                SubtitleListview1.EndUpdate();
                            }
                        }
                    }
                }

                if (string.CompareOrdinal(_changeSubtitleToString, _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName)) != 0)
                {
                    if (!Text.EndsWith('*'))
                        Text = Text.TrimEnd() + "*";
                }
                else
                {
                    if (Text.EndsWith('*'))
                        Text = Text.TrimEnd('*').TrimEnd();
                }
                ShowSubtitleTimer.Start();
            }

            private void HideVideoPlayer()
            {
                mediaPlayer.Pause();

                int textHeight = splitContainerListViewAndText.Height - splitContainerListViewAndText.SplitterDistance;

                splitContainer1.Panel2Collapsed = true;
                splitContainerMain.Panel2Collapsed = true;
                Main_Resize(null, null);

                splitContainerListViewAndText.SplitterDistance = splitContainerListViewAndText.Height - textHeight;
            }

            private void ShowVideoPlayer()
            {
                if (_isVideoControlsUndocked)
                {
                    ShowHideUndockedVideoControls();
                }
                else
                {
                    if (toolStripButtonToggleVideo.Checked && toolStripButtonToggleWaveform.Checked)
                    {
                        splitContainer1.Panel2Collapsed = false;
                        MoveVideoUp();
                    }
                    else
                    {
                        splitContainer1.Panel2Collapsed = true;
                        MoveVideoDown();
                    }

                    splitContainerMain.Panel2Collapsed = false;
                    if (toolStripButtonToggleVideo.Checked)
                    {
                        if (audioVisualizer.Visible)
                        {
                            audioVisualizer.Left = tabControlButtons.Left + tabControlButtons.Width + 5;
                        }
                        else
                        {
                            panelVideoPlayer.Left = tabControlButtons.Left + tabControlButtons.Width + 5;
                        }
                    }
                    else if (audioVisualizer.Visible)
                    {
                        audioVisualizer.Left = tabControlButtons.Left + tabControlButtons.Width + 5;
                    }
                    audioVisualizer.Width = groupBoxVideo.Width - (audioVisualizer.Left + 10);

                    checkBoxSyncListViewWithVideoWhilePlaying.Left = tabControlButtons.Left + tabControlButtons.Width + 5;
                    panelWaveformControls.Left = audioVisualizer.Left;
                    trackBarWaveformPosition.Left = panelWaveformControls.Left + panelWaveformControls.Width + 5;
                    trackBarWaveformPosition.Width = audioVisualizer.Left + audioVisualizer.Width - trackBarWaveformPosition.Left + 5;
                }

                if (mediaPlayer.VideoPlayer == null && !string.IsNullOrEmpty(_fileName) && !Configuration.Settings.General.DisableVideoAutoLoading)
                    TryToFindAndOpenVideoFile(Path.Combine(Path.GetDirectoryName(_fileName), Path.GetFileNameWithoutExtension(_fileName)));
                Main_Resize(null, null);
            }

            private void ShowHideUndockedVideoControls()
            {
                if (_videoPlayerUndocked == null || _videoPlayerUndocked.IsDisposed)
                    UnDockVideoPlayer();
                _videoPlayerUndocked.Visible = false;
                if (toolStripButtonToggleVideo.Checked)
                {
                    _videoPlayerUndocked.Show(this);
                    if (_videoPlayerUndocked.WindowState == FormWindowState.Minimized)
                        _videoPlayerUndocked.WindowState = FormWindowState.Normal;
                }

                if (_waveformUndocked == null || _waveformUndocked.IsDisposed)
                    UnDockWaveform();
                _waveformUndocked.Visible = false;
                if (toolStripButtonToggleWaveform.Checked)
                {
                    _waveformUndocked.Show(this);
                    if (_waveformUndocked.WindowState == FormWindowState.Minimized)
                        _waveformUndocked.WindowState = FormWindowState.Normal;
                }

                if (toolStripButtonToggleVideo.Checked || toolStripButtonToggleWaveform.Checked)
                {
                    if (_videoControlsUndocked == null || _videoControlsUndocked.IsDisposed)
                        UnDockVideoButtons();
                    _videoControlsUndocked.Visible = false;
                    _videoControlsUndocked.Show(this);
                }
                else
                {
                    if (_videoControlsUndocked != null && !_videoControlsUndocked.IsDisposed)
                        _videoControlsUndocked.Visible = false;
                }
            }

            private void MoveVideoUp()
            {
                if (splitContainer1.Panel2.Controls.Count == 0)
                {
                    var control = panelVideoPlayer;
                    groupBoxVideo.Controls.Remove(control);
                    splitContainer1.Panel2.Controls.Add(control);
                }
                panelVideoPlayer.Top = 0;
                panelVideoPlayer.Left = 0;
                panelVideoPlayer.Height = splitContainer1.Panel2.Height - 2;
                panelVideoPlayer.Width = splitContainer1.Panel2.Width - 2;
            }

            private void MoveVideoDown()
            {
                if (splitContainer1.Panel2.Controls.Count > 0)
                {
                    var control = panelVideoPlayer;
                    splitContainer1.Panel2.Controls.Clear();
                    groupBoxVideo.Controls.Add(control);
                }
                panelVideoPlayer.Top = 32;
                panelVideoPlayer.Left = tabControlButtons.Left + tabControlButtons.Width + 5;
                panelVideoPlayer.Height = groupBoxVideo.Height - (panelVideoPlayer.Top + 5);
                panelVideoPlayer.Width = groupBoxVideo.Width - (panelVideoPlayer.Left + 5);
            }

            private void FixLargeFonts()
            {
                using (var graphics = CreateGraphics())
                {
                    var textSize = graphics.MeasureString(buttonPlayPrevious.Text, Font);
                    if (textSize.Height > buttonPlayPrevious.Height - 4)
                    {
                        int newButtonHeight = 22; //(int)(textSize.Height + 7 + 0.5);
                        UiUtil.SetButtonHeight(this, newButtonHeight, -4);

                        // List view
                        SubtitleListview1.InitializeTimestampColumnWidths(this);
                        const int adjustUp = 8;
                        SubtitleListview1.Height = SubtitleListview1.Height - adjustUp;
                        groupBoxEdit.Top = groupBoxEdit.Top - adjustUp;
                        groupBoxEdit.Height = groupBoxEdit.Height + adjustUp;
                        numericUpDownDuration.Left = timeUpDownStartTime.Left + timeUpDownStartTime.Width;
                        numericUpDownDuration.Width = numericUpDownDuration.Width + 5;
                        labelDuration.Left = numericUpDownDuration.Left - 3;
                        labelAutoDuration.Left = labelDuration.Left - (labelAutoDuration.Width - 5);

                        // Video controls - Create
                        timeUpDownVideoPosition.Left = labelVideoPosition.Left + labelVideoPosition.Width;
                        int buttonWidth = labelVideoPosition.Width + timeUpDownVideoPosition.Width;
                        buttonInsertNewText.Width = buttonWidth;
                        buttonBeforeText.Width = buttonWidth;
                        buttonGotoSub.Width = buttonWidth;
                        buttonSetStartTime.Width = buttonWidth;
                        buttonSetEnd.Width = buttonWidth;
                        int FKeyLeft = buttonInsertNewText.Left + buttonInsertNewText.Width;
                        labelCreateF9.Left = FKeyLeft;
                        labelCreateF10.Left = FKeyLeft;
                        labelCreateF11.Left = FKeyLeft;
                        labelCreateF12.Left = FKeyLeft;
                        buttonForward1.Left = buttonInsertNewText.Left + buttonInsertNewText.Width - buttonForward1.Width;
                        numericUpDownSec1.Width = buttonInsertNewText.Width - (numericUpDownSec1.Left + buttonForward1.Width);
                        buttonForward2.Left = buttonInsertNewText.Left + buttonInsertNewText.Width - buttonForward2.Width;
                        numericUpDownSec2.Width = buttonInsertNewText.Width - (numericUpDownSec2.Left + buttonForward2.Width);

                        // Video controls - Adjust
                        timeUpDownVideoPositionAdjust.Left = labelVideoPosition2.Left + labelVideoPosition2.Width;
                        buttonSetStartAndOffsetRest.Width = buttonWidth;
                        buttonSetEndAndGoToNext.Width = buttonWidth;
                        buttonAdjustSetStartTime.Width = buttonWidth;
                        buttonAdjustSetEndTime.Width = buttonWidth;
                        buttonAdjustPlayBefore.Width = buttonWidth;
                        buttonAdjustGoToPosAndPause.Width = buttonWidth;
                        labelAdjustF9.Left = FKeyLeft;
                        labelAdjustF10.Left = FKeyLeft;
                        labelAdjustF11.Left = FKeyLeft;
                        labelAdjustF12.Left = FKeyLeft;
                        buttonAdjustSecForward1.Left = buttonInsertNewText.Left + buttonInsertNewText.Width - buttonAdjustSecForward1.Width;
                        numericUpDownSecAdjust1.Width = buttonInsertNewText.Width - (numericUpDownSecAdjust2.Left + buttonAdjustSecForward1.Width);
                        buttonAdjustSecForward2.Left = buttonInsertNewText.Left + buttonInsertNewText.Width - buttonAdjustSecForward2.Width;
                        numericUpDownSecAdjust2.Width = buttonInsertNewText.Width - (numericUpDownSecAdjust2.Left + buttonAdjustSecForward2.Width);

                        tabControl1_SelectedIndexChanged(null, null);
                    }
                }
            }

            private void Main_Resize(object sender, EventArgs e)
            {
                if (_loading)
                    return;

                panelVideoPlayer.Invalidate();

                MainResize();

                // Due to strange bug in listview when maximizing
                SaveSubtitleListviewIndices();
                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                RestoreSubtitleListviewIndices();

                panelVideoPlayer.Refresh();
            }

            private void MainResize()
            {
                var tbText = textBoxListViewText;
                var tbOriginal = textBoxListViewTextAlternate;
                int firstLeft = 236;

                var lbText = labelText;
                var lbTextOriginal = labelAlternateText;

                var lbSingleLine = labelTextLineLengths;
                var lbSingleLineOriginal = labelTextAlternateLineLengths;

                tbText.Left = firstLeft;
                tbOriginal.Left = firstLeft;
                lbText.Left = firstLeft;
                lbTextOriginal.Left = firstLeft;
                tbText.Width = groupBoxEdit.Width - (tbText.Left + 10 + (groupBoxEdit.Width - buttonUnBreak.Left));

                if (Configuration.Settings.General.RightToLeftMode)
                {
                    tbText = textBoxListViewTextAlternate;
                    tbOriginal = textBoxListViewText;

                    lbText = labelAlternateText;
                    lbTextOriginal = labelText;

                    lbSingleLine = labelTextAlternateLineLengths;
                    lbSingleLineOriginal = labelTextLineLengths;
                }
                tbText.Left = firstLeft;
                lbText.Left = firstLeft;
                lbSingleLine.Left = firstLeft;

                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    tbText.Width = (groupBoxEdit.Width - (tbText.Left + 10)) / 2;
                    tbOriginal.Left = tbText.Left + tbText.Width + 3;
                    lbTextOriginal.Left = tbOriginal.Left;

                    tbOriginal.Width = tbText.Width;

                    labelAlternateCharactersPerSecond.Left = tbOriginal.Left + (tbOriginal.Width - labelAlternateCharactersPerSecond.Width);
                    lbSingleLineOriginal.Left = tbOriginal.Left;
                    labelAlternateSingleLine.Left = labelTextAlternateLineLengths.Left + labelTextAlternateLineLengths.Width;
                    labelTextAlternateLineTotal.Left = tbOriginal.Left + (tbOriginal.Width - labelTextAlternateLineTotal.Width);
                }

                labelAlternateCharactersPerSecond.Top = labelCharactersPerSecond.Top;
                labelCharactersPerSecond.Left = tbText.Left + (tbText.Width - labelCharactersPerSecond.Width);
                labelTextLineTotal.Left = tbText.Left + (tbText.Width - labelTextLineTotal.Width);
                SubtitleListview1.AutoSizeAllColumns(this);

                FixRightToLeftDependingOnLanguage();
            }

            private void FixRightToLeftDependingOnLanguage()
            {
                if (Configuration.Settings.General.RightToLeftMode)
                {
                    if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                    {
                        if (LanguageAutoDetect.CouldBeRightToLeftLanguge(_subtitleAlternate))
                        {
                            textBoxListViewTextAlternate.RightToLeft = RightToLeft.Yes;
                        }
                        else
                        {
                            textBoxListViewTextAlternate.RightToLeft = RightToLeft.No;
                        }
                    }
                    if (LanguageAutoDetect.CouldBeRightToLeftLanguge(_subtitle))
                    {
                        textBoxListViewText.RightToLeft = RightToLeft.Yes;
                        textBoxSource.RightToLeft = RightToLeft.Yes;
                    }
                    else
                    {

                        textBoxListViewText.RightToLeft = RightToLeft.No;
                        textBoxSource.RightToLeft = RightToLeft.No;
                    }
                }
                else
                {
                    textBoxListViewText.RightToLeft = RightToLeft.No;
                    textBoxSource.RightToLeft = RightToLeft.No;
                }
            }

            private void PlayCurrent()
            {
                if (_subtitleListViewIndex >= 0)
                {
                    GotoSubtitleIndex(_subtitleListViewIndex);
                    textBoxListViewText.Focus();
                    ReadyAutoRepeat();
                    PlayPart(_subtitle.Paragraphs[_subtitleListViewIndex]);
                }
            }

            private void ReadyAutoRepeat()
            {
                if (checkBoxAutoRepeatOn.Checked)
                {
                    _repeatCount = int.Parse(comboBoxAutoRepeat.Text);
                }
                else
                {
                    _repeatCount = -1;
                }
                if (mediaPlayer.VideoPlayer != null)
                    labelStatus.Text = _language.VideoControls.Playing;
            }

            private void PlayNext()
            {
                int newIndex = _subtitleListViewIndex + 1;
                if (newIndex < _subtitle.Paragraphs.Count)
                {
                    foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                        item.Selected = false;
                    SubtitleListview1.Items[newIndex].Selected = true;
                    SubtitleListview1.Items[newIndex].EnsureVisible();
                    SubtitleListview1.Items[newIndex].Focused = true;
                    textBoxListViewText.Focus();
                    textBoxListViewText.SelectAll();
                    _subtitleListViewIndex = newIndex;
                    GotoSubtitleIndex(newIndex);
                    ShowSubtitle();
                    PlayCurrent();
                }
            }

            private void PlayPrevious()
            {
                if (_subtitleListViewIndex > 0)
                {
                    int newIndex = _subtitleListViewIndex - 1;
                    foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                        item.Selected = false;
                    SubtitleListview1.Items[newIndex].Selected = true;
                    SubtitleListview1.Items[newIndex].EnsureVisible();
                    SubtitleListview1.Items[newIndex].Focused = true;
                    textBoxListViewText.Focus();
                    textBoxListViewText.SelectAll();
                    GotoSubtitleIndex(newIndex);
                    ShowSubtitle();
                    _subtitleListViewIndex = newIndex;
                    PlayCurrent();
                }
            }

            private void GotoSubtitleIndex(int index)
            {
                if (mediaPlayer.VideoPlayer != null && mediaPlayer.Duration > 0)
                {
                    mediaPlayer.CurrentPosition = _subtitle.Paragraphs[index].StartTime.TotalSeconds;
                }
            }

            private void PlayPart(Paragraph paragraph)
            {
                if (mediaPlayer.VideoPlayer != null)
                {
                    double startSeconds = paragraph.StartTime.TotalSeconds;
                    if (startSeconds > 0.05)
                        startSeconds -= 0.05; // go a little back

                    _endSeconds = paragraph.EndTime.TotalSeconds;
                    if (mediaPlayer.Duration > _endSeconds + 0.05)
                        _endSeconds += 0.05; // go a little forward

                    mediaPlayer.CurrentPosition = startSeconds;
                    ShowSubtitle();
                    mediaPlayer.Play();
                }
            }

            private void buttonSetStartTime_Click(object sender, EventArgs e)
            {
                SetStartTime(false);
            }

            private void SetStartTime(bool adjustEndTime)
            {
                if (SubtitleListview1.SelectedItems.Count == 1)
                {
                    timeUpDownStartTime.MaskedTextBox.TextChanged -= MaskedTextBoxTextChanged;
                    int index = SubtitleListview1.SelectedItems[0].Index;
                    var p = _subtitle.Paragraphs[index];
                    var oldParagraph = new Paragraph(p);
                    if (oldParagraph.StartTime.IsMaxTime || oldParagraph.EndTime.IsMaxTime)
                        adjustEndTime = true;
                    double videoPosition = mediaPlayer.CurrentPosition;
                    if (!mediaPlayer.IsPaused)
                        videoPosition -= Configuration.Settings.General.SetStartEndHumanDelay / TimeCode.BaseUnit;

                    MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.VideoControls.BeforeChangingTimeInWaveformX, "#" + p.Number + " " + p.Text));

                    timeUpDownStartTime.TimeCode = TimeCode.FromSeconds(videoPosition);

                    var duration = p.Duration.TotalMilliseconds;

                    p.StartTime.TotalMilliseconds = videoPosition * TimeCode.BaseUnit;
                    if (adjustEndTime)
                        p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + duration;
                    if (oldParagraph.StartTime.IsMaxTime)
                        p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + Utilities.GetOptimalDisplayMilliseconds(p.Text);

                    SubtitleListview1.SetStartTimeAndDuration(index, p, _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                    timeUpDownStartTime.TimeCode = p.StartTime;
                    timeUpDownStartTime.MaskedTextBox.TextChanged += MaskedTextBoxTextChanged;

                    if (!adjustEndTime)
                        SetDurationInSeconds(p.Duration.TotalSeconds);

                    UpdateOriginalTimeCodes(oldParagraph);
                    if (IsFramesRelevant && CurrentFrameRate > 0)
                    {
                        _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                            ShowSource();
                    }
                }
            }

            private void ButtonSetEndClick(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedItems.Count == 1)
                {
                    double videoPosition = mediaPlayer.CurrentPosition;
                    if (!mediaPlayer.IsPaused)
                        videoPosition -= Configuration.Settings.General.SetStartEndHumanDelay / TimeCode.BaseUnit;

                    int index = SubtitleListview1.SelectedItems[0].Index;
                    MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.VideoControls.BeforeChangingTimeInWaveformX, "#" + _subtitle.Paragraphs[index].Number + " " + _subtitle.Paragraphs[index].Text));

                    if (_subtitle.Paragraphs[index].StartTime.IsMaxTime)
                    {
                        timeUpDownStartTime.MaskedTextBox.TextChanged -= MaskedTextBoxTextChanged;
                        _subtitle.Paragraphs[index].EndTime.TotalSeconds = videoPosition;
                        _subtitle.Paragraphs[index].StartTime.TotalMilliseconds = _subtitle.Paragraphs[index].EndTime.TotalMilliseconds - Utilities.GetOptimalDisplayMilliseconds(_subtitle.Paragraphs[index].Text);
                        if (_subtitle.Paragraphs[index].StartTime.TotalMilliseconds < 0)
                            _subtitle.Paragraphs[index].StartTime.TotalMilliseconds = 0;
                        timeUpDownStartTime.TimeCode = _subtitle.Paragraphs[index].StartTime;
                        SubtitleListview1.SetStartTimeAndDuration(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                        timeUpDownStartTime.MaskedTextBox.TextChanged += MaskedTextBoxTextChanged;
                    }
                    else
                    {
                        _subtitle.Paragraphs[index].EndTime = TimeCode.FromSeconds(videoPosition);
                        if (_subtitle.Paragraphs[index].Duration.TotalMilliseconds < Configuration.Settings.General.SubtitleMinimumDisplayMilliseconds)
                            _subtitle.Paragraphs[index].Duration.TotalMilliseconds = Configuration.Settings.General.SubtitleMinimumDisplayMilliseconds;
                    }
                    SubtitleListview1.SetStartTimeAndDuration(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                    SetDurationInSeconds(_subtitle.Paragraphs[index].Duration.TotalSeconds);
                }
            }

            private void ButtonInsertNewTextClick(object sender, EventArgs e)
            {
                mediaPlayer.Pause();

                var newParagraph = InsertNewTextAtVideoPosition();

                textBoxListViewText.Focus();
                timerAutoDuration.Start();

                ShowStatus(string.Format(_language.VideoControls.NewTextInsertAtX, newParagraph.StartTime.ToShortString()));
            }

            private Paragraph InsertNewTextAtVideoPosition()
            {
                // current movie Position
                double videoPositionInMilliseconds = mediaPlayer.CurrentPosition * TimeCode.BaseUnit;
                if (!mediaPlayer.IsPaused && videoPositionInMilliseconds > Configuration.Settings.General.SetStartEndHumanDelay)
                    videoPositionInMilliseconds -= Configuration.Settings.General.SetStartEndHumanDelay;

                var tc = new TimeCode(videoPositionInMilliseconds);
                MakeHistoryForUndo(_language.BeforeInsertSubtitleAtVideoPosition + "  " + tc);

                // find index where to insert
                int index = 0;
                foreach (var p in _subtitle.Paragraphs)
                {
                    if (p.StartTime.TotalMilliseconds > videoPositionInMilliseconds)
                        break;
                    index++;
                }

                // create and insert
                var newParagraph = new Paragraph(string.Empty, videoPositionInMilliseconds, videoPositionInMilliseconds + Configuration.Settings.General.NewEmptyDefaultMs);
                if (GetCurrentSubtitleFormat().IsFrameBased)
                {
                    newParagraph.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                    newParagraph.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                }

                if (_networkSession != null)
                {
                    _networkSession.TimerStop();
                    NetworkGetSendUpdates(new List<int>(), index, newParagraph);
                }
                else
                {
                    _subtitle.Paragraphs.Insert(index, newParagraph);

                    // check if original is available - and insert new paragraph in the original too
                    if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                    {
                        _subtitleAlternate.InsertParagraphInCorrectTimeOrder(new Paragraph(newParagraph));
                        _subtitleAlternate.Renumber();
                    }

                    _subtitleListViewIndex = -1;
                    _subtitle.Renumber();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                }
                SubtitleListview1.SelectIndexAndEnsureVisible(index);
                return newParagraph;
            }

            private void timerAutoDuration_Tick(object sender, EventArgs e)
            {
                labelAutoDuration.Visible = !labelAutoDuration.Visible;
                if (SubtitleListview1.SelectedItems.Count > 0)
                {
                    try
                    {
                        int firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;
                        var currentParagraph = _subtitle.Paragraphs[firstSelectedIndex];
                        var nextParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex + 1);
                        double duration = Utilities.GetOptimalDisplayMilliseconds(textBoxListViewText.Text);
                        if (currentParagraph.StartTime.TotalMilliseconds + duration + Configuration.Settings.General.MinimumMillisecondsBetweenLines > nextParagraph?.StartTime.TotalMilliseconds)
                        {
                            var newEndTime = nextParagraph.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                            if (newEndTime - currentParagraph.StartTime.TotalMilliseconds > 100)
                            {
                                duration = newEndTime - currentParagraph.StartTime.TotalMilliseconds;
                            }
                            else
                            {
                                return; // too close to next subtitle
                            }
                        }
                        SetDurationInSeconds(duration / TimeCode.BaseUnit);
                        currentParagraph.EndTime.TotalMilliseconds = currentParagraph.StartTime.TotalMilliseconds + duration;
                        SubtitleListview1.SetDuration(firstSelectedIndex, currentParagraph, _subtitle.GetParagraphOrDefault(firstSelectedIndex + 1));
                    }
                    catch
                    {
                        // ignore
                    }
                }
            }

            private void buttonBeforeText_Click(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedItems.Count > 0)
                {
                    int index = SubtitleListview1.SelectedItems[0].Index;

                    mediaPlayer.Pause();
                    double pos = _subtitle.Paragraphs[index].StartTime.TotalSeconds;
                    if (pos > 1)
                        mediaPlayer.CurrentPosition = (_subtitle.Paragraphs[index].StartTime.TotalSeconds) - 0.5;
                    else
                        mediaPlayer.CurrentPosition = _subtitle.Paragraphs[index].StartTime.TotalSeconds;
                    mediaPlayer.Play();
                }
            }

            private void GotoSubPositionAndPause()
            {
                GotoSubPositionAndPause(0);
            }

            private void GotoSubPositionAndPause(double adjustSeconds)
            {
                if (SubtitleListview1.SelectedItems.Count > 0)
                {
                    int index = SubtitleListview1.SelectedItems[0].Index;
                    if (index == -1 || index >= _subtitle.Paragraphs.Count)
                        return;

                    var p = _subtitle.Paragraphs[index];
                    mediaPlayer.Pause();
                    if (p.StartTime.IsMaxTime)
                        return;

                    double newPos = p.StartTime.TotalSeconds + adjustSeconds;
                    if (newPos < 0)
                        newPos = 0;
                    mediaPlayer.CurrentPosition = newPos;
                    ShowSubtitle();

                    double startPos = mediaPlayer.CurrentPosition - 1;
                    if (startPos < 0)
                        startPos = 0;

                    SetWaveformPosition(startPos, mediaPlayer.CurrentPosition, index);
                }
            }

            private void buttonGotoSub_Click(object sender, EventArgs e)
            {
                GotoSubPositionAndPause();
            }

            private void buttonOpenVideo_Click(object sender, EventArgs e)
            {
                if (string.IsNullOrEmpty(openFileDialog1.InitialDirectory) && !string.IsNullOrEmpty(_fileName))
                    openFileDialog1.InitialDirectory = Path.GetDirectoryName(_fileName);
                openFileDialog1.Title = _languageGeneral.OpenVideoFileTitle;
                openFileDialog1.FileName = string.Empty;
                openFileDialog1.Filter = Utilities.GetVideoFileFilter(true);

                openFileDialog1.FileName = string.Empty;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    if (audioVisualizer.WavePeaks != null)
                    {
                        audioVisualizer.WavePeaks = null;
                        audioVisualizer.Spectrogram = null;
                        audioVisualizer.SceneChanges = new List<double>();
                    }
                    openFileDialog1.InitialDirectory = Path.GetDirectoryName(openFileDialog1.FileName);
                    if (!panelVideoPlayer.Visible)
                        toolStripButtonToggleVideo_Click(null, null);
                    OpenVideo(openFileDialog1.FileName);
                }
            }

            private void toolStripButtonToggleVideo_Click(object sender, EventArgs e)
            {
                toolStripButtonToggleVideo.Checked = !toolStripButtonToggleVideo.Checked;
                panelVideoPlayer.Visible = toolStripButtonToggleVideo.Checked;
                mediaPlayer.BringToFront();
                if (!toolStripButtonToggleVideo.Checked && !toolStripButtonToggleWaveform.Checked)
                {
                    if (_isVideoControlsUndocked)
                        ShowHideUndockedVideoControls();
                    else
                        HideVideoPlayer();
                }
                else
                {
                    ShowVideoPlayer();
                }
                Configuration.Settings.General.ShowVideoPlayer = toolStripButtonToggleVideo.Checked;
                if (!_loading)
                    Refresh();
            }

            private void toolStripButtonToggleWaveform_Click(object sender, EventArgs e)
            {
                toolStripButtonToggleWaveform.Checked = !toolStripButtonToggleWaveform.Checked;
                audioVisualizer.Visible = toolStripButtonToggleWaveform.Checked;
                trackBarWaveformPosition.Visible = toolStripButtonToggleWaveform.Checked;
                panelWaveformControls.Visible = toolStripButtonToggleWaveform.Checked;
                if (!toolStripButtonToggleWaveform.Checked && !toolStripButtonToggleVideo.Checked)
                {
                    if (_isVideoControlsUndocked)
                        ShowHideUndockedVideoControls();
                    else
                        HideVideoPlayer();
                }
                else
                {
                    ShowVideoPlayer();
                }
                Configuration.Settings.General.ShowAudioVisualizer = toolStripButtonToggleWaveform.Checked;
                Refresh();
            }

            public void ShowEarlierOrLater(double adjustMilliseconds, SelectionChoice selection)
            {
                var tc = new TimeCode(adjustMilliseconds);
                MakeHistoryForUndo(_language.BeforeShowSelectedLinesEarlierLater + ": " + tc);
                if (adjustMilliseconds < 0)
                {
                    if (selection == SelectionChoice.AllLines)
                        ShowStatus(string.Format(_language.ShowAllLinesXSecondsLinesEarlier, adjustMilliseconds / -TimeCode.BaseUnit));
                    else if (selection == SelectionChoice.SelectionOnly)
                        ShowStatus(string.Format(_language.ShowSelectedLinesXSecondsLinesEarlier, adjustMilliseconds / -TimeCode.BaseUnit));
                    else if (selection == SelectionChoice.SelectionAndForward)
                        ShowStatus(string.Format(_language.ShowSelectionAndForwardXSecondsLinesEarlier, adjustMilliseconds / -TimeCode.BaseUnit));
                }
                else
                {
                    if (selection == SelectionChoice.AllLines)
                        ShowStatus(string.Format(_language.ShowAllLinesXSecondsLinesLater, adjustMilliseconds / TimeCode.BaseUnit));
                    else if (selection == SelectionChoice.SelectionOnly)
                        ShowStatus(string.Format(_language.ShowSelectedLinesXSecondsLinesLater, adjustMilliseconds / TimeCode.BaseUnit));
                    else if (selection == SelectionChoice.SelectionAndForward)
                        ShowStatus(string.Format(_language.ShowSelectionAndForwardXSecondsLinesLater, adjustMilliseconds / TimeCode.BaseUnit));
                }

                double frameRate = CurrentFrameRate;
                SubtitleListview1.BeginUpdate();

                int startFrom = 0;
                if (selection == SelectionChoice.SelectionAndForward)
                {
                    if (SubtitleListview1.SelectedItems.Count > 0)
                        startFrom = SubtitleListview1.SelectedItems[0].Index;
                    else
                        startFrom = _subtitle.Paragraphs.Count;
                }

                for (int i = startFrom; i < _subtitle.Paragraphs.Count; i++)
                {
                    switch (selection)
                    {
                        case SelectionChoice.SelectionOnly:
                            if (SubtitleListview1.Items[i].Selected)
                                ShowEarlierOrLaterParagraph(adjustMilliseconds, i);
                            break;
                        case SelectionChoice.AllLines:
                        case SelectionChoice.SelectionAndForward:
                            ShowEarlierOrLaterParagraph(adjustMilliseconds, i);
                            break;
                    }
                }

                SubtitleListview1.EndUpdate();
                if (_subtitle.WasLoadedWithFrameNumbers)
                    _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(frameRate);
                RefreshSelectedParagraph();
                UpdateSourceView();
                UpdateListSyntaxColoring();
            }

            private void ShowEarlierOrLaterParagraph(double adjustMilliseconds, int i)
            {
                var p = _subtitle.GetParagraphOrDefault(i);
                if (p != null && !p.StartTime.IsMaxTime)
                {
                    if (_subtitleAlternate != null)
                    {
                        var original = Utilities.GetOriginalParagraph(i, p, _subtitleAlternate.Paragraphs);
                        if (original != null)
                        {
                            original.StartTime.TotalMilliseconds += adjustMilliseconds;
                            original.EndTime.TotalMilliseconds += adjustMilliseconds;
                        }
                    }

                    p.StartTime.TotalMilliseconds += adjustMilliseconds;
                    p.EndTime.TotalMilliseconds += adjustMilliseconds;
                    SubtitleListview1.SetStartTimeAndDuration(i, p, _subtitle.GetParagraphOrDefault(i + 1), _subtitle.GetParagraphOrDefault(i - 1));
                }
            }

            private void UpdateSourceView()
            {
                if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                    ShowSource();
            }

            private void toolStripMenuItemAdjustAllTimes_Click(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedItems.Count > 1)
                {
                    ShowSelectedLinesEarlierlaterToolStripMenuItemClick(null, null);
                    return;
                }

                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                mediaPlayer.Pause();

                if (_showEarlierOrLater != null && !_showEarlierOrLater.IsDisposed)
                {
                    _showEarlierOrLater.WindowState = FormWindowState.Normal;
                    _showEarlierOrLater.Focus();
                    return;
                }

                _showEarlierOrLater = new ShowEarlierLater();
                if (!_showEarlierOrLater.IsPositionAndSizeSaved)
                {
                    _showEarlierOrLater.Top = Top + 100;
                    _showEarlierOrLater.Left = Left + Width / 2 - _showEarlierOrLater.Width / 3;
                }
                SaveSubtitleListviewIndices();
                _showEarlierOrLater.Initialize(ShowEarlierOrLater, false);
                _showEarlierOrLater.Show(this);
            }

            private void timer1_Tick(object sender, EventArgs e)
            {
                if (mediaPlayer.VideoPlayer != null)
                {
                    if (!mediaPlayer.IsPaused)
                    {
                        timeUpDownVideoPosition.Enabled = false;
                        timeUpDownVideoPositionAdjust.Enabled = false;

                        if (_endSeconds >= 0 && mediaPlayer.CurrentPosition > _endSeconds && !(AutoRepeatContinueOn || AutoRepeatOn))
                        {
                            mediaPlayer.Pause();
                            if (_endSecondsNewPosition >= 0 && _endSecondsNewPositionTicks > DateTime.UtcNow.Ticks - (10000 * 900)) // 900 ms
                            {
                                mediaPlayer.CurrentPosition = _endSecondsNewPosition;
                            }
                            else
                            {
                                mediaPlayer.CurrentPosition = _endSeconds + EndDelay;
                            }
                            _endSeconds = -1;
                            _endSecondsNewPosition = -1;
                            _endSecondsNewPositionTicks = 0;
                        }

                        if (AutoRepeatContinueOn || AutoRepeatOn)
                        {
                            if (_endSeconds >= 0 && mediaPlayer.CurrentPosition > _endSeconds && checkBoxAutoRepeatOn.Checked)
                            {
                                mediaPlayer.Pause();
                                _endSeconds = -1;

                                if (checkBoxAutoRepeatOn.Checked && _repeatCount > 0)
                                {
                                    if (_repeatCount == 1)
                                        labelStatus.Text = _language.VideoControls.RepeatingLastTime;
                                    else
                                        labelStatus.Text = string.Format(_language.VideoControls.RepeatingXTimesLeft, _repeatCount);

                                    _repeatCount--;
                                    if (_subtitleListViewIndex >= 0 && _subtitleListViewIndex < _subtitle.Paragraphs.Count)
                                        PlayPart(_subtitle.Paragraphs[_subtitleListViewIndex]);
                                }
                                else if (checkBoxAutoContinue.Checked)
                                {
                                    _autoContinueDelayCount = int.Parse(comboBoxAutoContinue.Text);
                                    if (_repeatCount == 1)
                                        labelStatus.Text = _language.VideoControls.AutoContinueInOneSecond;
                                    else
                                        labelStatus.Text = string.Format(_language.VideoControls.AutoContinueInXSeconds, _autoContinueDelayCount);
                                    timerAutoContinue.Start();
                                }
                            }
                        }
                    }
                    else
                    {
                        timeUpDownVideoPosition.Enabled = true;
                        timeUpDownVideoPositionAdjust.Enabled = true;
                    }
                    int index = ShowSubtitle();

                    double pos = mediaPlayer.CurrentPosition * TimeCode.BaseUnit;
                    if (!timeUpDownVideoPosition.MaskedTextBox.Focused && timeUpDownVideoPosition.TimeCode.TotalMilliseconds != pos)
                        timeUpDownVideoPosition.TimeCode = new TimeCode(pos);

                    if (!timeUpDownVideoPositionAdjust.MaskedTextBox.Focused && timeUpDownVideoPositionAdjust.TimeCode.TotalMilliseconds != pos)
                        timeUpDownVideoPositionAdjust.TimeCode = new TimeCode(pos);

                    mediaPlayer.RefreshProgressBar();

                    trackBarWaveformPosition.ValueChanged -= trackBarWaveformPosition_ValueChanged;
                    int value = (int)mediaPlayer.CurrentPosition;
                    if (value > trackBarWaveformPosition.Maximum)
                        value = trackBarWaveformPosition.Maximum;
                    if (value < trackBarWaveformPosition.Minimum)
                        value = trackBarWaveformPosition.Minimum;
                    trackBarWaveformPosition.Value = value;
                    trackBarWaveformPosition.ValueChanged += trackBarWaveformPosition_ValueChanged;

                    if (labelNextWord.Visible && _labelNextTicks + 100000000 < DateTime.UtcNow.Ticks)
                    {
                        labelNextWord.Visible = false;
                    }
                }
            }

            private void StopAutoDuration()
            {
                timerAutoDuration.Stop();
                labelAutoDuration.Visible = false;
            }

            private void textBoxListViewText_Leave(object sender, EventArgs e)
            {
                StopAutoDuration();
            }

            private void timerAutoContinue_Tick(object sender, EventArgs e)
            {
                _autoContinueDelayCount--;

                if (_autoContinueDelayCount == 0)
                {
                    timerAutoContinue.Stop();

                    if (timerStillTyping.Enabled)
                    {
                        labelStatus.Text = _language.VideoControls.StillTypingAutoContinueStopped;
                    }
                    else
                    {
                        labelStatus.Text = string.Empty;
                        PlayNext();
                    }
                }
                else
                {
                    if (_repeatCount == 1)
                        labelStatus.Text = _language.VideoControls.AutoContinueInOneSecond;
                    else
                        labelStatus.Text = string.Format(_language.VideoControls.AutoContinueInXSeconds, _autoContinueDelayCount);
                }
            }

            private void timerStillTyping_Tick(object sender, EventArgs e)
            {
                timerStillTyping.Stop();
            }

            private void textBoxListViewText_MouseMove(object sender, MouseEventArgs e)
            {
                if ((AutoRepeatContinueOn || AutoRepeatOn) && !textBoxSearchWord.Focused && textBoxListViewText.Focused)
                {
                    string selectedText = textBoxListViewText.SelectedText;
                    if (!string.IsNullOrEmpty(selectedText))
                    {
                        selectedText = selectedText.Trim();
                        selectedText = selectedText.TrimEnd('.', ',', '!', '?');
                        selectedText = selectedText.TrimEnd();
                        if (!string.IsNullOrEmpty(selectedText) && selectedText != textBoxSearchWord.Text)
                        {
                            textBoxSearchWord.Text = HtmlUtil.RemoveHtmlTags(selectedText);
                        }
                    }
                }
            }

            private void textBoxListViewText_KeyUp(object sender, KeyEventArgs e)
            {
                textBoxListViewText_MouseMove(sender, null);
                textBoxListViewText.ClearUndo();
                UpdatePositionAndTotalLength(labelTextLineTotal, textBoxListViewText);
            }

            private void buttonGoogleIt_Click(object sender, EventArgs e)
            {
                System.Diagnostics.Process.Start("https://www.google.com/search?q=" + Utilities.UrlEncode(textBoxSearchWord.Text));
            }

            private void buttonGoogleTranslateIt_Click(object sender, EventArgs e)
            {
                string languageId = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle);
                System.Diagnostics.Process.Start("https://translate.google.com/#auto|" + languageId + "|" + Utilities.UrlEncode(textBoxSearchWord.Text));
            }

            private void ButtonPlayCurrentClick(object sender, EventArgs e)
            {
                PlayCurrent();
            }

            private void buttonPlayNext_Click(object sender, EventArgs e)
            {
                PlayNext();
            }

            private void buttonPlayPrevious_Click(object sender, EventArgs e)
            {
                PlayPrevious();
            }

            private void buttonStop_Click(object sender, EventArgs e)
            {
                _endSeconds = -1;
                timerAutoContinue.Stop();
                mediaPlayer.Pause();
                labelStatus.Text = string.Empty;
            }

            private void fileToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
            {
                toolStripMenuItemOpenContainingFolder.Visible = !string.IsNullOrEmpty(_fileName) && File.Exists(_fileName);
                bool subtitleLoaded = IsSubtitleLoaded;
                toolStripMenuItemStatistics.Visible = subtitleLoaded;
                toolStripSeparator22.Visible = subtitleLoaded;
                toolStripMenuItemExport.Visible = subtitleLoaded;
                openOriginalToolStripMenuItem.Visible = subtitleLoaded;
                toolStripMenuItemOpenKeepVideo.Visible = _videoFileName != null;
                if (subtitleLoaded && Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    saveOriginalToolStripMenuItem.Visible = true;
                    saveOriginalAstoolStripMenuItem.Visible = true;
                    removeOriginalToolStripMenuItem.Visible = true;
                }
                else
                {
                    saveOriginalToolStripMenuItem.Visible = false;
                    saveOriginalAstoolStripMenuItem.Visible = false;
                    if (subtitleLoaded && SubtitleListview1.IsAlternateTextColumnVisible && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                        removeOriginalToolStripMenuItem.Visible = true;
                    else
                        removeOriginalToolStripMenuItem.Visible = false;
                }
                var format = GetCurrentSubtitleFormat();
                if (format.GetType() == typeof(AdvancedSubStationAlpha))
                {
                    toolStripMenuItemSubStationAlpha.Visible = true;
                    toolStripMenuItemSubStationAlpha.Text = _language.Menu.File.AdvancedSubStationAlphaProperties;
                }
                else if (format.GetType() == typeof(SubStationAlpha))
                {
                    toolStripMenuItemSubStationAlpha.Visible = true;
                    toolStripMenuItemSubStationAlpha.Text = _language.Menu.File.SubStationAlphaProperties;
                }
                else
                {
                    toolStripMenuItemSubStationAlpha.Visible = false;
                }

                if (format.GetType() == typeof(Ebu))
                {
                    toolStripMenuItemEbuProperties.Text = _language.Menu.File.EbuProperties;
                    toolStripMenuItemEbuProperties.Visible = !string.IsNullOrEmpty(_language.Menu.File.EbuProperties);
                }
                else
                {
                    toolStripMenuItemEbuProperties.Visible = false;
                }

                if (format.GetType() == typeof(DCSubtitle) || format.GetType() == typeof(DCinemaSmpte2010) || format.GetType() == typeof(DCinemaSmpte2007))
                {
                    toolStripMenuItemDCinemaProperties.Visible = true;
                }
                else
                {
                    toolStripMenuItemDCinemaProperties.Visible = false;
                }

                if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText))
                {
                    toolStripMenuItemTTProperties.Visible = true;
                }
                else
                {
                    toolStripMenuItemTTProperties.Visible = false;
                }

                toolStripMenuItemNuendoProperties.Visible = format.Name == "Nuendo";
                toolStripMenuItemFcpProperties.Visible = format.GetType() == typeof(FinalCutProXml);

                toolStripSeparator20.Visible = subtitleLoaded;
            }

            private void toolStripMenuItemOpenContainingFolder_Click(object sender, EventArgs e)
            {
                string folderName = Path.GetDirectoryName(_fileName);
                if (Utilities.IsRunningOnMono())
                {
                    System.Diagnostics.Process.Start(folderName);
                }
                else
                {
                    string argument = @"/select, " + _fileName;
                    System.Diagnostics.Process.Start("explorer.exe", argument);
                }
            }

            private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (tabControlButtons.SelectedIndex == 0)
                {
                    tabControlButtons.Width = groupBoxTranslateSearch.Left + groupBoxTranslateSearch.Width + 10;
                    Configuration.Settings.VideoControls.LastActiveTab = "Translate";
                }
                else if (tabControlButtons.SelectedIndex == 1)
                {
                    tabControlButtons.Width = buttonInsertNewText.Left + buttonInsertNewText.Width + 35;
                    Configuration.Settings.VideoControls.LastActiveTab = "Create";
                }
                else if (tabControlButtons.SelectedIndex == 2)
                {
                    tabControlButtons.Width = buttonInsertNewText.Left + buttonInsertNewText.Width + 35;
                    Configuration.Settings.VideoControls.LastActiveTab = "Adjust";
                }

                if (!_isVideoControlsUndocked)
                {
                    if (toolStripButtonToggleWaveform.Checked)
                        audioVisualizer.Left = tabControlButtons.Left + tabControlButtons.Width + 5;
                    if (!toolStripButtonToggleWaveform.Checked && toolStripButtonToggleVideo.Checked)
                    {
                        panelVideoPlayer.Left = tabControlButtons.Left + tabControlButtons.Width + 5;
                        panelVideoPlayer.Width = groupBoxVideo.Width - (panelVideoPlayer.Left + 10);
                    }

                    audioVisualizer.Width = groupBoxVideo.Width - (audioVisualizer.Left + 10);
                    panelWaveformControls.Left = audioVisualizer.Left;
                    trackBarWaveformPosition.Left = panelWaveformControls.Left + panelWaveformControls.Width + 5;
                    trackBarWaveformPosition.Width = groupBoxVideo.Width - (trackBarWaveformPosition.Left + 10);
                    Main_Resize(null, null);
                    checkBoxSyncListViewWithVideoWhilePlaying.Left = tabControlButtons.Left + tabControlButtons.Width + 5;
                    if (!_loading)
                        Refresh();
                }
                else if (_videoControlsUndocked != null && !_videoControlsUndocked.IsDisposed)
                {
                    _videoControlsUndocked.Width = tabControlButtons.Width + 20;
                    _videoControlsUndocked.Height = tabControlButtons.Height + 65;
                }
            }

            private void buttonSecBack1_Click(object sender, EventArgs e)
            {
                GoBackSeconds((double)numericUpDownSec1.Value);
            }

            private void buttonForward1_Click(object sender, EventArgs e)
            {
                GoBackSeconds(-(double)numericUpDownSec1.Value);
            }

            private void ButtonSetStartAndOffsetRestClick(object sender, EventArgs e)
            {
                SetStartAndOffsetTheRest(mediaPlayer.CurrentPosition);
            }

            private void SetStartAndOffsetTheRest(double videoPosition)
            {
                if (SubtitleListview1.SelectedItems.Count == 1)
                {
                    bool oldSync = checkBoxSyncListViewWithVideoWhilePlaying.Checked;
                    checkBoxSyncListViewWithVideoWhilePlaying.Checked = false;

                    timeUpDownStartTime.MaskedTextBox.TextChanged -= MaskedTextBoxTextChanged;
                    int index = SubtitleListview1.SelectedItems[0].Index;
                    var oldP = new Paragraph(_subtitle.Paragraphs[index]);
                    if (!mediaPlayer.IsPaused)
                        videoPosition -= Configuration.Settings.General.SetStartEndHumanDelay / TimeCode.BaseUnit;
                    var tc = TimeCode.FromSeconds(videoPosition);
                    timeUpDownStartTime.TimeCode = tc;

                    MakeHistoryForUndo(_language.BeforeSetStartTimeAndOffsetTheRest + @"  " + oldP.Number + @" - " + tc);

                    double offset = oldP.StartTime.TotalMilliseconds - tc.TotalMilliseconds;

                    if (oldP.StartTime.IsMaxTime)
                    {
                        _subtitle.Paragraphs[index].StartTime.TotalSeconds = videoPosition;
                        _subtitle.Paragraphs[index].EndTime.TotalMilliseconds = _subtitle.Paragraphs[index].StartTime.TotalMilliseconds + Utilities.GetOptimalDisplayMilliseconds(_subtitle.Paragraphs[index].Text);
                        SubtitleListview1.SetStartTimeAndDuration(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                        checkBoxSyncListViewWithVideoWhilePlaying.Checked = oldSync;
                        timeUpDownStartTime.MaskedTextBox.TextChanged += MaskedTextBoxTextChanged;
                        return;
                    }

                    _subtitle.Paragraphs[index].StartTime = new TimeCode(_subtitle.Paragraphs[index].StartTime.TotalMilliseconds - offset);
                    _subtitle.Paragraphs[index].EndTime = new TimeCode(_subtitle.Paragraphs[index].EndTime.TotalMilliseconds - offset);
                    SubtitleListview1.SetStartTimeAndDuration(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));

                    for (int i = index + 1; i < SubtitleListview1.Items.Count; i++)
                    {
                        if (!_subtitle.Paragraphs[i].StartTime.IsMaxTime)
                        {
                            _subtitle.Paragraphs[i].StartTime = new TimeCode(_subtitle.Paragraphs[i].StartTime.TotalMilliseconds - offset);
                            _subtitle.Paragraphs[i].EndTime = new TimeCode(_subtitle.Paragraphs[i].EndTime.TotalMilliseconds - offset);
                            SubtitleListview1.SetStartTimeAndDuration(i, _subtitle.Paragraphs[i], _subtitle.GetParagraphOrDefault(i + 1), _subtitle.GetParagraphOrDefault(index - 1));
                        }
                    }

                    if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                    {
                        var original = Utilities.GetOriginalParagraph(index, oldP, _subtitleAlternate.Paragraphs);
                        if (original != null)
                        {
                            index = _subtitleAlternate.GetIndex(original);
                            for (int i = index; i < _subtitleAlternate.Paragraphs.Count; i++)
                            {
                                if (!_subtitleAlternate.Paragraphs[i].StartTime.IsMaxTime)
                                {
                                    _subtitleAlternate.Paragraphs[i].StartTime = new TimeCode(_subtitleAlternate.Paragraphs[i].StartTime.TotalMilliseconds - offset);
                                    _subtitleAlternate.Paragraphs[i].EndTime = new TimeCode(_subtitleAlternate.Paragraphs[i].EndTime.TotalMilliseconds - offset);
                                }
                            }
                        }
                    }
                    if (IsFramesRelevant && CurrentFrameRate > 0)
                    {
                        _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                            ShowSource();
                    }

                    checkBoxSyncListViewWithVideoWhilePlaying.Checked = oldSync;
                    timeUpDownStartTime.MaskedTextBox.TextChanged += MaskedTextBoxTextChanged;
                }
            }

            private void ButtonSetEndAndGoToNextClick(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedItems.Count == 1)
                {
                    int index = SubtitleListview1.SelectedItems[0].Index;
                    double videoPosition = mediaPlayer.CurrentPosition;
                    if (!mediaPlayer.IsPaused)
                        videoPosition -= Configuration.Settings.General.SetStartEndHumanDelay / TimeCode.BaseUnit;

                    string oldDuration = _subtitle.Paragraphs[index].Duration.ToString();
                    var temp = new Paragraph(_subtitle.Paragraphs[index]);
                    temp.EndTime.TotalMilliseconds = TimeCode.FromSeconds(videoPosition).TotalMilliseconds;
                    MakeHistoryForUndo(string.Format(_language.DisplayTimeAdjustedX, "#" + _subtitle.Paragraphs[index].Number + ": " + oldDuration + " -> " + temp.Duration));
                    _makeHistoryPaused = true;

                    if (_subtitle.Paragraphs[index].StartTime.IsMaxTime)
                    {
                        timeUpDownStartTime.MaskedTextBox.TextChanged -= MaskedTextBoxTextChanged;
                        _subtitle.Paragraphs[index].EndTime.TotalSeconds = videoPosition;
                        _subtitle.Paragraphs[index].StartTime.TotalMilliseconds = _subtitle.Paragraphs[index].EndTime.TotalMilliseconds - Utilities.GetOptimalDisplayMilliseconds(_subtitle.Paragraphs[index].Text);
                        if (_subtitle.Paragraphs[index].StartTime.TotalMilliseconds < 0)
                            _subtitle.Paragraphs[index].StartTime.TotalMilliseconds = 0;
                        timeUpDownStartTime.TimeCode = _subtitle.Paragraphs[index].StartTime;
                        SubtitleListview1.SetStartTimeAndDuration(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                        timeUpDownStartTime.MaskedTextBox.TextChanged += MaskedTextBoxTextChanged;
                    }
                    else
                    {
                        _subtitle.Paragraphs[index].EndTime = TimeCode.FromSeconds(videoPosition);
                    }
                    SubtitleListview1.SetDuration(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1));
                    SetDurationInSeconds(_subtitle.Paragraphs[index].Duration.TotalSeconds);

                    if (index + 1 < _subtitle.Paragraphs.Count)
                    {
                        SubtitleListview1.Items[index].Selected = false;
                        SubtitleListview1.Items[index + 1].Selected = true;
                        if (!_subtitle.Paragraphs[index + 1].StartTime.IsMaxTime)
                            _subtitle.Paragraphs[index + 1].StartTime = TimeCode.FromSeconds(videoPosition + 0.001);

                        if (IsFramesRelevant && CurrentFrameRate > 0)
                        {
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                            if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                                ShowSource();
                        }
                        if (!_subtitle.Paragraphs[index + 1].StartTime.IsMaxTime)
                            SubtitleListview1.SetStartTimeAndDuration(index + 1, _subtitle.Paragraphs[index + 1], _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                        SubtitleListview1.SelectIndexAndEnsureVisible(index + 1, true);
                    }
                    _makeHistoryPaused = false;
                }
            }

            private void ButtonAdjustSecBackClick(object sender, EventArgs e)
            {
                GoBackSeconds((double)numericUpDownSecAdjust1.Value);
            }

            private void ButtonAdjustSecForwardClick(object sender, EventArgs e)
            {
                GoBackSeconds(-(double)numericUpDownSecAdjust1.Value);
            }

            private void Main_Shown(object sender, EventArgs e)
            {
                toolStripButtonToggleVideo.Checked = !Configuration.Settings.General.ShowVideoPlayer;
                toolStripButtonToggleVideo_Click(null, null);

                _timerAutoSave.Tick += TimerAutoSaveTick;
                if (Configuration.Settings.General.AutoBackupSeconds > 0)
                {
                    _timerAutoSave.Interval = 1000 * Configuration.Settings.General.AutoBackupSeconds; // take backup every x second if changes were made
                    _timerAutoSave.Start();
                }
                ToolStripMenuItemPlayRateNormalClick(null, null);

                SetPositionFromXYString(Configuration.Settings.General.UndockedVideoPosition, "VideoPlayerUndocked");
                SetPositionFromXYString(Configuration.Settings.General.UndockedWaveformPosition, "WaveformUndocked");
                SetPositionFromXYString(Configuration.Settings.General.UndockedVideoControlsPosition, "VideoControlsUndocked");
                if (Configuration.Settings.General.Undocked && Configuration.Settings.General.StartRememberPositionAndSize)
                {
                    Configuration.Settings.General.Undocked = false;
                    UndockVideoControlsToolStripMenuItemClick(null, null);
                }
                Main_Resize(null, null);

                toolStripButtonLockCenter.Checked = Configuration.Settings.General.WaveformCenter;
                audioVisualizer.Locked = toolStripButtonLockCenter.Checked;

                numericUpDownSec1.Value = (decimal)(Configuration.Settings.General.SmallDelayMilliseconds / TimeCode.BaseUnit);
                numericUpDownSec2.Value = (decimal)(Configuration.Settings.General.LargeDelayMilliseconds / TimeCode.BaseUnit);

                numericUpDownSecAdjust1.Value = (decimal)(Configuration.Settings.General.SmallDelayMilliseconds / TimeCode.BaseUnit);
                numericUpDownSecAdjust2.Value = (decimal)(Configuration.Settings.General.LargeDelayMilliseconds / TimeCode.BaseUnit);

                SetShortcuts();

                if (Configuration.Settings.General.StartInSourceView)
                {
                    textBoxSource.Focus();
                }
                else
                {
                    SubtitleListview1.Focus();
                    int index = FirstSelectedIndex;
                    if (index > 0 && SubtitleListview1.Items.Count > index)
                    {
                        SubtitleListview1.Focus();
                        SubtitleListview1.Items[index].Focused = true;
                    }
                }
                MainResize();
                _loading = false;
                OpenVideo(_videoFileName);
                lock (_syncUndo)
                {
                    timerTextUndo.Start();
                    timerAlternateTextUndo.Start();
                }
                if (Configuration.IsRunningOnLinux())
                {
                    numericUpDownDuration.Left = timeUpDownStartTime.Left + timeUpDownStartTime.Width + 10;
                    numericUpDownDuration.Width += 10;
                    numericUpDownSec1.Width += 10;
                    numericUpDownSec2.Width += 10;
                    numericUpDownSecAdjust1.Width += 10;
                    numericUpDownSecAdjust2.Width += 10;
                    labelDuration.Left = numericUpDownDuration.Left;
                }

                _timerDoSyntaxColoring.Interval = 100;
                _timerDoSyntaxColoring.Tick += _timerDoSyntaxColoring_Tick;

                var showBeta = Configuration.Settings.General.ShowBetaStuff;
                generateDatetimeInfoFromVideoToolStripMenuItem.Visible = showBeta;
                toolStripMenuItemExportCaptionInc.Visible = showBeta;
                toolStripMenuItemExportUltech130.Visible = showBeta;
                toolStripMenuItemInverseSelection.Visible = showBeta;
                toolStripMenuItemSpellCheckFromCurrentLine.Visible = showBeta;
                toolStripMenuItemImportOcrHardSub.Visible = showBeta;
                toolStripMenuItemMeasurementConverter.Visible = showBeta;
                toolStripMenuItemOpenDvd.Visible = showBeta;

                if (Configuration.Settings.General.StartRememberPositionAndSize &&
                    Configuration.Settings.General.SplitContainerMainSplitterDistance > 0 &&
                    Configuration.Settings.General.SplitContainer1SplitterDistance > 0 &&
                    Configuration.Settings.General.SplitContainerListViewAndTextSplitterDistance > 0)
                {
                    splitContainerMain.SplitterDistance = Configuration.Settings.General.SplitContainerMainSplitterDistance;
                    splitContainer1.SplitterDistance = Configuration.Settings.General.SplitContainer1SplitterDistance;
                    splitContainerListViewAndText.SplitterDistance = Configuration.Settings.General.SplitContainerListViewAndTextSplitterDistance;
                }
                mediaPlayer.InitializeVolume(Configuration.Settings.General.VideoPlayerDefaultVolume);
                tabControlSubtitle.Invalidate();

                if (string.IsNullOrEmpty(Configuration.Settings.Language.CheckForUpdates.CheckingForUpdates))
                {
                    checkForUpdatesToolStripMenuItem.Visible = false;
                    toolStripMenuItemSplitterCheckForUpdates.Visible = false;
                }
                else if (Configuration.Settings.General.CheckForUpdates && Configuration.Settings.General.LastCheckForUpdates < DateTime.Now.AddDays(-5))
                {
                    _checkForUpdatesHelper = new CheckForUpdatesHelper();
                    _checkForUpdatesHelper.CheckForUpdates();
                    _timerCheckForUpdates = new Timer();
                    _timerCheckForUpdates.Interval = 7000;
                    _timerCheckForUpdates.Tick += TimerCheckForUpdatesTick;
                    _timerCheckForUpdates.Start();
                    Configuration.Settings.General.LastCheckForUpdates = DateTime.Now;
                }
                _dragAndDropTimer.Interval = 50;
                _dragAndDropTimer.Tick += DoSubtitleListview1Drop;

                if (_exitWhenLoaded)
                    Application.Exit();

                // Fix some large font issue
                if (numericUpDownDuration.Left + numericUpDownDuration.Width > textBoxListViewText.Left)
                {
                    numericUpDownDuration.Left = timeUpDownStartTime.Left + timeUpDownStartTime.Width + 5;
                    numericUpDownDuration.Width = textBoxListViewText.Left - numericUpDownDuration.Left - 5;
                    labelDuration.Left = numericUpDownDuration.Left;
                }
                _changeSubtitleToString = _subtitle.GetFastHashCode(GetCurrentEncoding().BodyName);
                comboBoxSubtitleFormats.AutoCompleteSource = AutoCompleteSource.ListItems;
                comboBoxSubtitleFormats.AutoCompleteMode = AutoCompleteMode.Append;
                LoadPlugins();
            }

            private void TimerCheckForUpdatesTick(object sender, EventArgs e)
            {
                _timerCheckForUpdates.Stop();
                if (_checkForUpdatesHelper.IsUpdateAvailable())
                {
                    using (var form = new CheckForUpdates(this, _checkForUpdatesHelper))
                    {
                        form.ShowDialog(this);
                    }
                }
                _checkForUpdatesHelper = null;
                _timerCheckForUpdates = null;
            }

            private void _timerDoSyntaxColoring_Tick(object sender, EventArgs e)
            {
                UpdateListSyntaxColoring();
                _timerDoSyntaxColoring.Stop();
            }

            private static void SetPositionFromXYString(string positionAndSize, string name)
            {
                var parts = positionAndSize.Split(';');
                if (parts.Length == 4)
                {
                    int left, top, width, height;
                    if (int.TryParse(parts[0], out left)
                        && int.TryParse(parts[1], out top)
                        && int.TryParse(parts[2], out width)
                        && int.TryParse(parts[3], out height))
                    {
                        PositionAndSizeForm.SetPositionAndSize(name, new Rectangle(left, top, width, height));
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Could not set position and size for '{0}'.", name);
                    }
                }
            }

            private void SetShortcuts()
            {
                _mainGeneralGoToFirstSelectedLine = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralGoToFirstSelectedLine);
                _mainGeneralGoToFirstEmptyLine = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralGoToNextEmptyLine);
                _mainGeneralMergeSelectedLines = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralMergeSelectedLines);
                _mainGeneralMergeSelectedLinesOnlyFirstText = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralMergeSelectedLinesOnlyFirstText);
                _mainGeneralToggleTranslationMode = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralToggleTranslationMode);
                _mainGeneralSwitchTranslationAndOriginal = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralSwitchOriginalAndTranslation);
                _mainGeneralMergeTranslationAndOriginal = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralMergeOriginalAndTranslation);
                _mainGeneralMergeWithNext = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralMergeWithNext);
                _mainGeneralMergeWithPrevious = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralMergeWithPrevious);
                _mainGeneralGoToNextSubtitle = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralGoToNextSubtitle);
                _mainGeneralGoToPrevSubtitle = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralGoToPrevSubtitle);
                _mainGeneralGoToStartOfCurrentSubtitle = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralGoToStartOfCurrentSubtitle);
                _mainGeneralGoToEndOfCurrentSubtitle = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralGoToEndOfCurrentSubtitle);

                newToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileNew);
                openToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileOpen);
                toolStripMenuItemOpenKeepVideo.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileOpenKeepVideo);
                saveToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileSave);
                saveOriginalToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileSaveOriginal);
                saveOriginalAstoolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileSaveOriginalAs);
                saveAsToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileSaveAs);
                _mainGeneralFileSaveAll = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileSaveAll);
                removeOriginalToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileCloseOriginal);
                toolStripMenuItemImportText.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileImportPlainText);
                toolStripMenuItemImportTimeCodes.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileImportTimeCodes);
                eBUSTLToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileExportEbu);
                plainTextToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainFileExportPlainText);

                toolStripMenuItemUndo.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditUndo);
                toolStripMenuItemRedo.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditRedo);
                findToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditFind);
                findNextToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditFindNext);
                replaceToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditReplace);
                multipleReplaceToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditMultipleReplace);
                gotoLineNumberToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditGoToLineNumber);
                toolStripMenuItemRightToLeftMode.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditRightToLeft);
                toolStripMenuItemShowOriginalInPreview.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditToggleTranslationOriginalInPreviews);
                toolStripMenuItemInverseSelection.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditInverseSelection);
                toolStripMenuItemModifySelection.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditModifySelection);

                fixToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsFixCommonErrors);
                toolStripMenuItemAutoMergeShortLines.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsMergeShortLines);
                toolStripMenuItemMakeEmptyFromCurrent.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsMakeEmptyFromCurrent);
                toolStripMenuItemAutoSplitLongLines.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsSplitLongLines);
                startNumberingFromToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsRenumber);
                removeTextForHearImpairedToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsRemoveTextForHI);
                ChangeCasingToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsChangeCasing);
                toolStripMenuItemShowOriginalInPreview.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditToggleTranslationOriginalInPreviews);
                toolStripMenuItemBatchConvert.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsBatchConvert);

                openVideoToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideoOpen);
                closeVideoToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideoClose);
                showhideVideoToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideoShowHideVideo);
                _toggleVideoDockUndock = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideoToggleVideoControls);
                _videoPause = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideoPause);
                _videoPlayPauseToggle = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideoPlayPauseToggle);
                _video1FrameLeft = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo1FrameLeft);
                _video1FrameRight = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo1FrameRight);
                _video1FrameLeftWithPlay = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo1FrameLeftWithPlay);
                _video1FrameRightWithPlay = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo1FrameRightWithPlay);
                _video100MsLeft = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo100MsLeft);
                _video100MsRight = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo100MsRight);
                _video500MsLeft = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo500MsLeft);
                _video500MsRight = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo500MsRight);
                _video1000MsLeft = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo1000MsLeft);
                _video1000MsRight = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo1000MsRight);
                _video5000MsLeft = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo5000MsLeft);
                _video5000MsRight = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideo5000MsRight);
                _videoPlayFirstSelected = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralPlayFirstSelected);
                _mainGoToPreviousSubtitleAndFocusVideo = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralGoToPreviousSubtitleAndFocusVideo);
                _mainGoToNextSubtitleAndFocusVideo = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralGoToNextSubtitleAndFocusVideo);
                _mainAdjustExtendCurrentSubtitle = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralExtendCurrentSubtitle);
                _mainAutoCalcCurrentDuration = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralAutoCalcCurrentDuration);
                _mainUnbreakNoSpace = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralUnbrekNoSpace);
                _mainVideoFullscreen = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideoFullscreen);

                spellCheckToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainSpellCheck);
                findDoubleWordsToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainSpellCheckFindDoubleWords);
                addWordToNameListToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainSpellCheckAddWordToNames);

                toolStripMenuItemAdjustAllTimes.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainSynchronizationAdjustTimes);
                visualSyncToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainSynchronizationVisualSync);
                toolStripMenuItemPointSync.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainSynchronizationPointSync);
                pointSyncViaOtherSubtitleToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainSynchronizationPointSyncViaFile);
                toolStripMenuItemChangeFrameRate2.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainSynchronizationChangeFrameRate);
                italicToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewItalic);
                _mainToolsAutoDuration = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsAutoDuration);
                _mainToolsBeamer = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToolsBeamer);
                _mainListViewToggleDashes = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewToggleDashes);
                toolStripMenuItemAlignment.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewAlignment);
                _mainListViewAutoDuration = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewAutoDuration);
                _mainListViewFocusWaveform = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewFocusWaveform);
                _mainListViewGoToNextError = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewGoToNextError);
                _mainEditReverseStartAndEndingForRTL = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainEditReverseStartAndEndingForRTL);
                _mainListViewCopyText = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewCopyText);
                copyOriginalTextToCurrentToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewCopyTextFromOriginalToCurrent);
                toolStripMenuItemColumnDeleteText.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewColumnDeleteText);
                ShiftTextCellsDownToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewColumnInsertText);
                toolStripMenuItemPasteSpecial.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewColumnPaste);
                moveTextUpToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewColumnTextUp);
                moveTextDownToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainListViewColumnTextDown);
                toolStripMenuItemReverseRightToLeftStartEnd.ShortcutKeys = _mainEditReverseStartAndEndingForRTL;
                italicToolStripMenuItem1.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxItalic);
                _mainTextBoxSplitAtCursor = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxSplitAtCursor);
                _mainTextBoxSplitAtCursorAndVideoPos = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxSplitAtCursorAndVideoPos);
                _mainTextBoxMoveLastWordDown = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxMoveLastWordDown);
                _mainTextBoxMoveFirstWordFromNextUp = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxMoveFirstWordFromNextUp);
                _mainTextBoxMoveLastWordDownCurrent = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxMoveLastWordDownCurrent);
                _mainTextBoxMoveFirstWordUpCurrent = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxMoveFirstWordUpCurrent);
                _mainTextBoxSelectionToLower = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxSelectionToLower);
                _mainTextBoxSelectionToUpper = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxSelectionToUpper);
                _mainTextBoxToggleAutoDuration = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxToggleAutoDuration);
                _mainCreateInsertSubAtVideoPos = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainCreateInsertSubAtVideoPos);
                _mainCreatePlayFromJustBefore = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainCreatePlayFromJustBefore);
                _mainCreateSetStart = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainCreateSetStart);
                _mainCreateSetEnd = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainCreateSetEnd);
                _mainCreateStartDownEndUp = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainCreateStartDownEndUp);
                _mainCreateSetEndAddNewAndGoToNew = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainCreateSetEndAddNewAndGoToNew);
                _mainAdjustSetStartAndOffsetTheRest = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSetStartAndOffsetTheRest);
                _mainAdjustSetEndAndOffsetTheRest = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSetEndAndOffsetTheRest);
                _mainAdjustSetEndAndOffsetTheRestAndGoToNext = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSetEndAndOffsetTheRestAndGoToNext);
                _mainAdjustSetEndAndGotoNext = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSetEndAndGotoNext);
                _mainAdjustInsertViaEndAutoStartAndGoToNext = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustViaEndAutoStartAndGoToNext);
                _mainAdjustSetStartAutoDurationAndGoToNext = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSetStartAutoDurationAndGoToNext);
                _mainAdjustSetEndNextStartAndGoToNext = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSetEndNextStartAndGoToNext);
                _mainAdjustStartDownEndUpAndGoToNext = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustStartDownEndUpAndGoToNext);
                _mainAdjustSetStart = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSetStart);
                _mainAdjustSetStartKeepDuration = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSetStartKeepDuration);
                _mainAdjustSetEnd = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSetEnd);
                _mainAdjustSelected100MsForward = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSelected100MsForward);
                _mainAdjustSelected100MsBack = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustSelected100MsBack);
                _mainAdjustAdjustStartXMsBack = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustStartXMsBack);
                _mainAdjustAdjustStartXMsForward = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustStartXMsForward);
                _mainAdjustAdjustEndXMsBack = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustEndXMsBack);
                _mainAdjustAdjustEndXMsForward = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainAdjustEndXMsForward);
                _mainInsertAfter = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainInsertAfter);
                _mainInsertBefore = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainInsertBefore);
                _mainTextBoxInsertAfter = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxInsertAfter);
                _mainTextBoxAutoBreak = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxAutoBreak);
                _mainTextBoxUnbreak = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTextBoxUnbreak);
                _mainMergeDialog = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainMergeDialog);
                _mainToggleFocus = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainToggleFocus);
                _waveformVerticalZoom = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformVerticalZoom);
                _waveformVerticalZoomOut = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformVerticalZoomOut);
                _waveformZoomIn = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformZoomIn);
                _waveformZoomOut = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformZoomOut);
                _waveformPlaySelection = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformPlaySelection);
                _waveformPlaySelectionEnd = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformPlaySelectionEnd);
                _waveformSearchSilenceForward = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformSearchSilenceForward);
                _waveformSearchSilenceBack = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformSearchSilenceBack);
                _waveformAddTextAtHere = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformAddTextHere);
                _waveformAddTextAtHereFromClipboard = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformAddTextHereFromClipboard);
                _waveformFocusListView = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformFocusListView);
                _waveformGoToNextSubtitle = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformGoToNextSubtitle);
                _waveformGoToPreviousSceneChange = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformGoToPreviousSceneChange);
                _waveformGoToNextSceneChange = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformGoToNextSceneChange);
                _waveformToggleSceneChange = UiUtil.GetKeys(Configuration.Settings.Shortcuts.WaveformToggleSceneChange);

                _mainTranslateCustomSearch1 = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTranslateCustomSearch1);
                _mainTranslateCustomSearch2 = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTranslateCustomSearch2);
                _mainTranslateCustomSearch3 = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTranslateCustomSearch3);
                _mainTranslateCustomSearch4 = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTranslateCustomSearch4);
                _mainTranslateCustomSearch5 = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTranslateCustomSearch5);
                _mainTranslateCustomSearch6 = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainTranslateCustomSearch6);

                if (audioVisualizer != null)
                {
                    audioVisualizer.InsertAtVideoPositionShortcut = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainWaveformInsertAtCurrentPosition);
                }

                UiUtil.HelpKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.GeneralHelp);
                helpToolStripMenuItem1.ShortcutKeys = UiUtil.HelpKeys;
            }

            public static object GetPropertiesAndDoAction(string pluginFileName, out string name, out string text, out decimal version, out string description, out string actionType, out string shortcut, out System.Reflection.MethodInfo mi)
            {
                name = null;
                text = null;
                version = 0;
                description = null;
                actionType = null;
                shortcut = null;
                mi = null;
                System.Reflection.Assembly assembly;
                try
                {
                    assembly = System.Reflection.Assembly.Load(File.ReadAllBytes(pluginFileName));
                }
                catch
                {
                    return null;
                }
                string objectName = Path.GetFileNameWithoutExtension(pluginFileName);
                if (assembly != null)
                {
                    Type pluginType = assembly.GetType("Nikse.SubtitleEdit.PluginLogic." + objectName);
                    if (pluginType == null)
                        return null;
                    object pluginObject = Activator.CreateInstance(pluginType);

                    // IPlugin
                    var t = pluginType.GetInterface("IPlugin");
                    if (t == null)
                        return null;

                    System.Reflection.PropertyInfo pi = t.GetProperty("Name");
                    if (pi != null)
                        name = (string)pi.GetValue(pluginObject, null);

                    pi = t.GetProperty("Text");
                    if (pi != null)
                        text = (string)pi.GetValue(pluginObject, null);

                    pi = t.GetProperty("Description");
                    if (pi != null)
                        description = (string)pi.GetValue(pluginObject, null);

                    pi = t.GetProperty("Version");
                    if (pi != null)
                        version = Convert.ToDecimal(pi.GetValue(pluginObject, null));

                    pi = t.GetProperty("ActionType");
                    if (pi != null)
                        actionType = (string)pi.GetValue(pluginObject, null);

                    mi = t.GetMethod("DoAction");

                    pi = t.GetProperty("Shortcut");
                    if (pi != null)
                        shortcut = (string)pi.GetValue(pluginObject, null);

                    return pluginObject;
                }
                return null;
            }

            private void LoadPlugins()
            {
                var path = Configuration.PluginsDirectory;
                if (!Directory.Exists(path))
                    return;
                var pluginFiles = Directory.GetFiles(path, "*.DLL");

                int filePluginCount = 0;
                int toolsPluginCount = 0;
                int syncPluginCount = 0;
                int translatePluginCount = 0;
                int spellCheckPluginCount = 0;

                for (int k = fileToolStripMenuItem.DropDownItems.Count - 1; k > 0; k--)
                {
                    ToolStripItem x = fileToolStripMenuItem.DropDownItems[k];
                    if (x.Name.StartsWith("Plugin", StringComparison.OrdinalIgnoreCase))
                        fileToolStripMenuItem.DropDownItems.Remove(x);
                }
                for (int k = toolsToolStripMenuItem.DropDownItems.Count - 1; k > 0; k--)
                {
                    ToolStripItem x = toolsToolStripMenuItem.DropDownItems[k];
                    if (x.Name.StartsWith("Plugin", StringComparison.OrdinalIgnoreCase))
                        toolsToolStripMenuItem.DropDownItems.Remove(x);
                }
                for (int k = toolStripMenuItemSpellCheckMain.DropDownItems.Count - 1; k > 0; k--)
                {
                    ToolStripItem x = toolStripMenuItemSpellCheckMain.DropDownItems[k];
                    if (x.Name.StartsWith("Plugin", StringComparison.OrdinalIgnoreCase))
                        toolStripMenuItemSpellCheckMain.DropDownItems.Remove(x);
                }
                for (int k = toolStripMenuItemSynchronization.DropDownItems.Count - 1; k > 0; k--)
                {
                    ToolStripItem x = toolStripMenuItemSynchronization.DropDownItems[k];
                    if (x.Name.StartsWith("Plugin", StringComparison.OrdinalIgnoreCase))
                        toolStripMenuItemSynchronization.DropDownItems.Remove(x);
                }
                for (int k = toolStripMenuItemAutoTranslate.DropDownItems.Count - 1; k > 0; k--)
                {
                    ToolStripItem x = toolStripMenuItemAutoTranslate.DropDownItems[k];
                    if (x.Name.StartsWith("Plugin", StringComparison.OrdinalIgnoreCase))
                        toolStripMenuItemAutoTranslate.DropDownItems.Remove(x);
                }

                foreach (var pluginFileName in pluginFiles)
                {
                    try
                    {
                        string name, description, text, shortcut, actionType;
                        decimal version;
                        MethodInfo mi;
                        GetPropertiesAndDoAction(pluginFileName, out name, out text, out version, out description, out actionType, out shortcut, out mi);
                        if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(actionType) && mi != null)
                        {
                            var item = new ToolStripMenuItem();
                            item.Name = "Plugin" + toolsPluginCount;
                            item.Text = text;
                            item.Tag = pluginFileName;
                            UiUtil.FixFonts(item);

                            if (!string.IsNullOrEmpty(shortcut))
                                item.ShortcutKeys = UiUtil.GetKeys(shortcut);

                            if (actionType.Equals("File", StringComparison.OrdinalIgnoreCase))
                            {
                                AddSeparator(filePluginCount, fileToolStripMenuItem, 2);
                                item.Click += PluginToolClick;
                                fileToolStripMenuItem.DropDownItems.Insert(fileToolStripMenuItem.DropDownItems.Count - 2, item);
                                filePluginCount++;
                            }
                            else if (actionType.Equals("Tool", StringComparison.OrdinalIgnoreCase))
                            {
                                AddSeparator(toolsPluginCount, toolsToolStripMenuItem);
                                item.Click += PluginToolClick;
                                toolsToolStripMenuItem.DropDownItems.Add(item);
                                toolsPluginCount++;
                            }
                            else if (actionType.Equals("Sync", StringComparison.OrdinalIgnoreCase))
                            {
                                AddSeparator(syncPluginCount, toolStripMenuItemSynchronization);
                                item.Click += PluginToolClick;
                                toolStripMenuItemSynchronization.DropDownItems.Add(item);
                                syncPluginCount++;
                            }
                            else if (actionType.Equals("Translate", StringComparison.OrdinalIgnoreCase))
                            {
                                AddSeparator(translatePluginCount, toolStripMenuItemAutoTranslate);
                                item.Click += PluginClickTranslate;
                                toolStripMenuItemAutoTranslate.DropDownItems.Add(item);
                                translatePluginCount++;
                            }
                            else if (actionType.Equals("SpellCheck", StringComparison.OrdinalIgnoreCase))
                            {
                                AddSeparator(spellCheckPluginCount, toolStripMenuItemSpellCheckMain);
                                item.Click += PluginClickNoFormatChange;
                                toolStripMenuItemSpellCheckMain.DropDownItems.Add(item);
                                spellCheckPluginCount++;
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(string.Format(_language.ErrorLoadingPluginXErrorY, pluginFileName, exception.Message));
                    }
                }
            }

            private void AddSeparator(int pluginCount, ToolStripMenuItem parent, int? relativeOffset = null)
            {
                if (pluginCount == 0)
                {
                    var tss = new ToolStripSeparator();
                    if (relativeOffset == null)
                        parent.DropDownItems.Add(tss);
                    else
                        parent.DropDownItems.Insert(parent.DropDownItems.Count - relativeOffset.Value, tss);
                    UiUtil.FixFonts(tss);
                }
            }

            private void PluginToolClick(object sender, EventArgs e)
            {
                CallPlugin(sender, true, false);
            }

            private void PluginClickNoFormatChange(object sender, EventArgs e)
            {
                CallPlugin(sender, false, false);
            }

            private void PluginClickTranslate(object sender, EventArgs e)
            {
                CallPlugin(sender, false, true);
            }

            private void CallPlugin(object sender, bool allowChangeFormat, bool translate)
            {
                try
                {
                    var item = (ToolStripItem)sender;
                    string name, description, text, shortcut, actionType;
                    decimal version;
                    System.Reflection.MethodInfo mi;
                    var pluginObject = GetPropertiesAndDoAction(item.Tag.ToString(), out name, out text, out version, out description, out actionType, out shortcut, out mi);
                    if (mi == null)
                    {
                        return;
                    }

                    string rawText = null;
                    SubtitleFormat format = GetCurrentSubtitleFormat();
                    if (format != null)
                    {
                        if (format.IsFrameBased)
                            _subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                        else
                            _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        rawText = _subtitle.ToText(format);
                    }

                    string pluginResult = (string)mi.Invoke(pluginObject,
                        new object[]
                        {
                            this,
                            _subtitle.ToText(new SubRip()),
                            Configuration.Settings.General.CurrentFrameRate,
                            Configuration.Settings.General.ListViewLineSeparatorString,
                            _fileName,
                            _videoFileName,
                            rawText
                        });

                    if (!string.IsNullOrEmpty(pluginResult) && pluginResult.Length > 10 && text != pluginResult)
                    {
                        var lines = new List<string>(pluginResult.SplitToLines());

                        MakeHistoryForUndo(string.Format(_language.BeforeRunningPluginXVersionY, name, version));

                        var s = new Subtitle();
                        SubtitleFormat newFormat = null;
                        foreach (var subtitleFormat in SubtitleFormat.AllSubtitleFormats)
                        {
                            if (subtitleFormat.IsMine(lines, null))
                            {
                                subtitleFormat.LoadSubtitle(s, lines, null);
                                newFormat = subtitleFormat;
                                break;
                            }
                        }

                        if (translate)
                        {
                            _subtitleAlternate = new Subtitle(_subtitle);
                            _subtitleAlternateFileName = _fileName;
                            _fileName = null;
                            _subtitle.Paragraphs.Clear();
                            foreach (var p in s.Paragraphs)
                                _subtitle.Paragraphs.Add(new Paragraph(p));
                            ShowStatus(_language.SubtitleTranslated);
                            ShowSource();
                            SubtitleListview1.ShowAlternateTextColumn(_languageGeneral.OriginalText);
                            SubtitleListview1.AutoSizeAllColumns(this);
                            SetupAlternateEdit();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            ResetHistory();
                            RestoreSubtitleListviewIndices();
                            _converted = true;
                            SetTitle();
                            return;
                        }

                        if (newFormat != null)
                        {
                            if (!allowChangeFormat && IsOnlyTextChanged(_subtitle, s))
                            {
                                for (int k = 0; k < s.Paragraphs.Count; k++)
                                {
                                    _subtitle.Paragraphs[k].Text = s.Paragraphs[k].Text;
                                }
                            }
                            else
                            {
                                _subtitle.Paragraphs.Clear();
                                _subtitle.Header = s.Header;
                                _subtitle.Footer = s.Footer;
                                foreach (var p in s.Paragraphs)
                                    _subtitle.Paragraphs.Add(p);
                            }

                            if (allowChangeFormat)
                                SetCurrentFormat(newFormat);

                            SaveSubtitleListviewIndices();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            RestoreSubtitleListviewIndices();
                            ShowSource();

                            ShowStatus(string.Format(_language.PluginXExecuted, name));
                        }
                        else
                        {
                            MessageBox.Show(_language.UnableToReadPluginResult);
                        }
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message + Environment.NewLine + exception.StackTrace);
                    if (exception.InnerException != null)
                    {
                        MessageBox.Show(exception.InnerException.Message + Environment.NewLine + exception.InnerException.StackTrace);
                    }
                }
            }

            private bool IsOnlyTextChanged(Subtitle s1, Subtitle s2)
            {
                if (s1.Paragraphs.Count != s2.Paragraphs.Count)
                    return false;

                for (int i = 0; i < s1.Paragraphs.Count; i++)
                {
                    var p1 = s1.Paragraphs[i];
                    var p2 = s2.Paragraphs[i];
                    if (Math.Abs(p1.StartTime.TotalMilliseconds - p2.StartTime.TotalMilliseconds) > 0.01)
                        return false;
                    if (Math.Abs(p1.EndTime.TotalMilliseconds - p2.EndTime.TotalMilliseconds) > 0.01)
                        return false;
                }

                return true;
            }

            private void TimerAutoSaveTick(object sender, EventArgs e)
            {
                string currentText = string.Empty;
                if (_subtitle != null && _subtitle.Paragraphs.Count > 0)
                {
                    var saveFormat = GetCurrentSubtitleFormat();
                    if (!saveFormat.IsTextBased)
                        saveFormat = new SubRip();
                    currentText = _subtitle.ToText(saveFormat);
                    if (_textAutoSave == null)
                        _textAutoSave = _changeSubtitleToString;
                    if (!string.IsNullOrEmpty(_textAutoSave) && currentText.Trim() != _textAutoSave.Trim() && !string.IsNullOrWhiteSpace(currentText))
                    {
                        if (!Directory.Exists(Configuration.AutoBackupDirectory))
                        {
                            try
                            {
                                Directory.CreateDirectory(Configuration.AutoBackupDirectory);
                            }
                            catch (Exception exception)
                            {
                                MessageBox.Show(string.Format(_language.UnableToCreateBackupDirectory, Configuration.AutoBackupDirectory, exception.Message));
                                return;
                            }
                        }
                        string title = string.Empty;
                        if (!string.IsNullOrEmpty(_fileName))
                            title = "_" + Path.GetFileNameWithoutExtension(_fileName);
                        string fileName = string.Format("{0}{1:0000}-{2:00}-{3:00}_{4:00}-{5:00}-{6:00}{7}{8}", Configuration.AutoBackupDirectory, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, title, saveFormat.Extension);
                        File.WriteAllText(fileName, currentText);

                        RestoreAutoBackup.CleanAutoBackupFolder(Configuration.AutoBackupDirectory, Configuration.Settings.General.AutoBackupDeleteAfterMonths);
                    }
                }
                _textAutoSave = currentText;

                if (_subtitleAlternateFileName != null && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    var saveFormat = GetCurrentSubtitleFormat();
                    if (!saveFormat.IsTextBased)
                        saveFormat = new SubRip();
                    string currentTextAlternate = _subtitleAlternate.ToText(saveFormat);
                    if (_subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                    {
                        if (_textAutoSaveOriginal == null)
                            _textAutoSaveOriginal = _changeAlternateSubtitleToString;
                        if (!string.IsNullOrEmpty(_textAutoSaveOriginal) && currentTextAlternate.Trim() != _textAutoSaveOriginal.Trim() && !string.IsNullOrWhiteSpace(currentTextAlternate))
                        {
                            if (!Directory.Exists(Configuration.AutoBackupDirectory))
                            {
                                try
                                {
                                    Directory.CreateDirectory(Configuration.AutoBackupDirectory);
                                }
                                catch (Exception exception)
                                {
                                    MessageBox.Show(string.Format(_language.UnableToCreateBackupDirectory, Configuration.AutoBackupDirectory, exception.Message));
                                    return;
                                }
                            }
                            string title = string.Empty;
                            if (!string.IsNullOrEmpty(_subtitleAlternateFileName))
                                title = "_" + Path.GetFileNameWithoutExtension(_subtitleAlternateFileName);
                            string fileName = string.Format("{0}{1:0000}-{2:00}-{3:00}_{4:00}-{5:00}-{6:00}{7}{8}", Configuration.AutoBackupDirectory, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, "_Original" + title, saveFormat.Extension);
                            File.WriteAllText(fileName, currentTextAlternate);
                        }
                    }
                    _textAutoSaveOriginal = currentTextAlternate;
                }
            }

            private void mediaPlayer_DragDrop(object sender, DragEventArgs e)
            {
                var files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files.Length == 1)
                {
                    string fileName = files[0];
                    string ext = Path.GetExtension(fileName).ToLowerInvariant();
                    if (Utilities.GetVideoFileFilter(true).Contains(ext))
                    {
                        if (string.IsNullOrEmpty(_fileName))
                        {
                            var dirName = Path.GetDirectoryName(fileName);
                            saveFileDialog1.InitialDirectory = dirName;
                            openFileDialog1.InitialDirectory = dirName;
                        }
                        OpenVideo(fileName);
                    }
                    else
                    {
                        try
                        {
                            var fi = new FileInfo(fileName);
                            if (fi.Length < Subtitle.MaxFileSize)
                            {
                                var lines = new List<string>(File.ReadAllLines(fileName));
                                foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
                                {
                                    if (format.IsMine(lines, fileName))
                                    {
                                        OpenSubtitle(fileName, null);
                                        return;
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }

                        MessageBox.Show(string.Format(_language.DropFileXNotAccepted, fileName));
                    }
                }
                else
                {
                    MessageBox.Show(_language.DropOnlyOneFile);
                }
            }

            private void mediaPlayer_DragEnter(object sender, DragEventArgs e)
            {
                // make sure they're actually dropping files (not text or anything else)
                if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
                    e.Effect = DragDropEffects.All;
            }

            private void buttonSecBack2_Click(object sender, EventArgs e)
            {
                GoBackSeconds((double)numericUpDownSec2.Value);
            }

            private void buttonForward2_Click(object sender, EventArgs e)
            {
                GoBackSeconds(-(double)numericUpDownSec2.Value);
            }

            private void buttonAdjustSecBack2_Click(object sender, EventArgs e)
            {
                GoBackSeconds((double)numericUpDownSecAdjust2.Value);
            }

            private void buttonAdjustSecForward2_Click(object sender, EventArgs e)
            {
                GoBackSeconds(-(double)numericUpDownSecAdjust2.Value);
            }

            private void translatepoweredByMicrosoftToolStripMenuItem_Click(object sender, EventArgs e)
            {
                TranslateViaGoogle(false, false);
            }

            private void AudioWaveform_Click(object sender, EventArgs e)
            {
                if (audioVisualizer.WavePeaks == null)
                {
                    if (_videoFileName != null && (_videoFileName.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
                                                  _videoFileName.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
                    {
                        return;
                    }

                    if (string.IsNullOrEmpty(_videoFileName))
                    {
                        buttonOpenVideo_Click(sender, e);
                        if (string.IsNullOrEmpty(_videoFileName))
                            return;
                    }
                    mediaPlayer.Pause();
                    using (var addWaveform = new AddWaveform())
                    {
                        var peakWaveFileName = WavePeakGenerator.GetPeakWaveFileName(_videoFileName);
                        var spectrogramFolder = Nikse.SubtitleEdit.Core.WavePeakGenerator.SpectrogramDrawer.GetSpectrogramFolder(_videoFileName);

                        if (WavePeakGenerator.IsFileValidForVisualizer(_videoFileName))
                        {
                            addWaveform.InitializeViaWaveFile(_videoFileName, peakWaveFileName, spectrogramFolder);
                        }
                        else
                        {
                            addWaveform.Initialize(_videoFileName, peakWaveFileName, spectrogramFolder, _videoAudioTrackNumber);
                        }
                        if (addWaveform.ShowDialog() == DialogResult.OK)
                        {
                            audioVisualizer.WavePeaks = addWaveform.Peaks;
                            audioVisualizer.Spectrogram = addWaveform.Spectrogram;
                            timerWaveform.Start();
                        }
                    }
                }
            }

            private void timerWaveform_Tick(object sender, EventArgs e)
            {
                if (audioVisualizer.Visible && mediaPlayer.VideoPlayer != null && audioVisualizer.WavePeaks != null)
                {
                    int index = -1;
                    if (SubtitleListview1.SelectedItems.Count > 0)
                        index = SubtitleListview1.SelectedItems[0].Index;

                    if (audioVisualizer.Locked)
                    {
                        double startPos = mediaPlayer.CurrentPosition - ((audioVisualizer.EndPositionSeconds - audioVisualizer.StartPositionSeconds) / 2.0);
                        if (startPos < 0)
                            startPos = 0;
                        SetWaveformPosition(startPos, mediaPlayer.CurrentPosition, index);
                    }
                    else if (mediaPlayer.CurrentPosition > audioVisualizer.EndPositionSeconds || mediaPlayer.CurrentPosition < audioVisualizer.StartPositionSeconds)
                    {
                        double startPos = mediaPlayer.CurrentPosition - 0.01;
                        if (startPos < 0)
                            startPos = 0;
                        audioVisualizer.ClearSelection();
                        SetWaveformPosition(startPos, mediaPlayer.CurrentPosition, index);
                    }
                    else
                    {
                        SetWaveformPosition(audioVisualizer.StartPositionSeconds, mediaPlayer.CurrentPosition, index);
                    }

                    bool paused = mediaPlayer.IsPaused;
                    toolStripButtonWaveformPause.Visible = !paused;
                    toolStripButtonWaveformPlay.Visible = paused;
                }
                else
                {
                    toolStripButtonWaveformPlay.Visible = true;
                    toolStripButtonWaveformPause.Visible = false;
                }
            }

            private void addParagraphHereToolStripMenuItem_Click(object sender, EventArgs e)
            {
                audioVisualizer.ClearSelection();
                var newParagraph = new Paragraph(audioVisualizer.NewSelectionParagraph);
                var format = GetCurrentSubtitleFormat();
                bool useExtraForStyle = format.HasStyleSupport;
                var styles = new List<string>();
                if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha))
                    styles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header);
                else if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText))
                    styles = TimedText10.GetStylesFromHeader(_subtitle.Header);
                else if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern))
                    styles = Sami.GetStylesFromHeader(_subtitle.Header);
                string style = "Default";
                if (styles.Count > 0)
                    style = styles[0];
                if (useExtraForStyle)
                    newParagraph.Extra = style;

                mediaPlayer.Pause();

                // find index where to insert
                int index = 0;
                for (int i = 0; i < _subtitle.Paragraphs.Count; i++)
                {
                    var p = _subtitle.Paragraphs[i];
                    if (p.StartTime.TotalMilliseconds > newParagraph.StartTime.TotalMilliseconds &&
                        (!p.StartTime.IsMaxTime || !HasSmallerStartTimes(_subtitle, i + 1, newParagraph.StartTime.TotalMilliseconds)))
                    {
                        break;
                    }
                    index++;
                }

                if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText))
                {
                    var c = _subtitle.GetParagraphOrDefault(index);
                    if (c == null)
                        c = _subtitle.GetParagraphOrDefault(index - 1);
                    if (c != null)
                    {
                        newParagraph.Style = c.Style;
                        newParagraph.Region = c.Region;
                        newParagraph.Language = c.Language;
                        newParagraph.Extra = TimedText10.SetExtra(newParagraph);
                    }
                }

                MakeHistoryForUndo(_language.BeforeInsertLine);

                // create and insert
                if (format.IsFrameBased)
                {
                    newParagraph.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                    newParagraph.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                }

                if (_networkSession != null)
                {
                    _networkSession.TimerStop();
                    NetworkGetSendUpdates(new List<int>(), index, newParagraph);
                }
                else
                {
                    _subtitle.Paragraphs.Insert(index, newParagraph);

                    if (_subtitleAlternate != null && SubtitleListview1.IsAlternateTextColumnVisible && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                    {
                        _subtitleAlternate.InsertParagraphInCorrectTimeOrder(new Paragraph(newParagraph));
                        _subtitleAlternate.Renumber();
                    }

                    _subtitleListViewIndex = -1;
                    _subtitle.Renumber();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                }
                SubtitleListview1.SelectIndexAndEnsureVisible(index);

                textBoxListViewText.Focus();
                audioVisualizer.NewSelectionParagraph = null;

                ShowStatus(string.Format(_language.VideoControls.NewTextInsertAtX, newParagraph.StartTime.ToShortString()));
                audioVisualizer.Invalidate();
            }

            private static bool HasSmallerStartTimes(Subtitle subtitle, int startIndex, double startMs)
            {
                for (int i = startIndex; i < subtitle.Paragraphs.Count; i++)
                {
                    var p = subtitle.Paragraphs[i];
                    if (startMs > p.StartTime.TotalMilliseconds && !p.StartTime.IsMaxTime)
                        return true;
                }
                return false;
            }

            private void addParagraphAndPasteToolStripMenuItem_Click(object sender, EventArgs e)
            {
                addParagraphHereToolStripMenuItem_Click(sender, e);
                textBoxListViewText.Text = Clipboard.GetText();
            }

            private void mergeWithPreviousToolStripMenuItem_Click(object sender, EventArgs e)
            {
                int index = _subtitle.GetIndex(audioVisualizer.RightClickedParagraph);
                if (index >= 0)
                {
                    SubtitleListview1.SelectIndexAndEnsureVisible(index);
                    MergeBeforeToolStripMenuItemClick(null, null);
                }
                audioVisualizer.Invalidate();
            }

            private void deleteParagraphToolStripMenuItem_Click(object sender, EventArgs e)
            {
                int index = _subtitle.GetIndex(audioVisualizer.RightClickedParagraph);
                if (index >= 0)
                {
                    SubtitleListview1.SelectIndexAndEnsureVisible(index);
                    ToolStripMenuItemDeleteClick(null, null);
                }
                audioVisualizer.Invalidate();
            }

            private void splitToolStripMenuItem1_Click(object sender, EventArgs e)
            {
                for (int i = 0; i < _subtitle.Paragraphs.Count; i++)
                {
                    if (audioVisualizer.RightClickedParagraph.StartTime.TotalMilliseconds == _subtitle.Paragraphs[i].StartTime.TotalMilliseconds &&
                        audioVisualizer.RightClickedParagraph.EndTime.TotalMilliseconds == _subtitle.Paragraphs[i].EndTime.TotalMilliseconds)
                    {
                        SubtitleListview1.SelectIndexAndEnsureVisible(i);
                        SplitSelectedParagraph(_audioWaveformRightClickSeconds, null);
                        break;
                    }
                }
                audioVisualizer.Invalidate();
            }

            private void mergeWithNextToolStripMenuItem_Click(object sender, EventArgs e)
            {
                int index = _subtitle.GetIndex(audioVisualizer.RightClickedParagraph);
                if (index >= 0)
                {
                    SubtitleListview1.SelectIndexAndEnsureVisible(index);
                    MergeAfterToolStripMenuItemClick(null, null);
                }
                audioVisualizer.Invalidate();
            }

            private void buttonWaveformZoomIn_Click(object sender, EventArgs e)
            {
                if (audioVisualizer.WavePeaks != null && audioVisualizer.Visible)
                {
                    audioVisualizer.ZoomFactor += 0.1;
                }
            }

            private void buttonWaveformZoomOut_Click(object sender, EventArgs e)
            {
                if (audioVisualizer.WavePeaks != null && audioVisualizer.Visible)
                {
                    audioVisualizer.ZoomFactor -= 0.1;
                }
            }

            private void buttonWaveformZoomReset_Click(object sender, EventArgs e)
            {
                if (audioVisualizer.WavePeaks != null && audioVisualizer.Visible)
                {
                    audioVisualizer.ZoomFactor = 1.0;
                }
            }

            private void toolStripMenuItemWaveformPlaySelection_Click(object sender, EventArgs e)
            {
                WaveformPlaySelection();
            }

            private void WaveformPlaySelection(bool nearEnd = false)
            {
                if (mediaPlayer.VideoPlayer != null)
                {
                    var p =
                        audioVisualizer.NewSelectionParagraph ??
                        audioVisualizer.SelectedParagraph;

                    if (p != null)
                    {
                        double startSeconds = p.StartTime.TotalSeconds;
                        _endSeconds = p.EndTime.TotalSeconds;
                        if (nearEnd)
                        {
                            startSeconds = Math.Max(startSeconds, _endSeconds - 1.0);
                        }
                        mediaPlayer.CurrentPosition = startSeconds;
                        UiUtil.ShowSubtitle(_subtitle, mediaPlayer);
                        mediaPlayer.Play();
                    }
                }
            }

            private void toolStripButtonWaveformZoomIn_Click(object sender, EventArgs e)
            {
                if (audioVisualizer.WavePeaks != null && audioVisualizer.Visible)
                {
                    audioVisualizer.ZoomFactor += 0.1;
                    SelectZoomTextInComboBox();
                }
            }

            private void toolStripButtonWaveformZoomOut_Click(object sender, EventArgs e)
            {
                if (audioVisualizer.WavePeaks != null && audioVisualizer.Visible)
                {
                    audioVisualizer.ZoomFactor -= 0.1;
                    SelectZoomTextInComboBox();
                }
            }

            private void toolStripComboBoxWaveform_SelectedIndexChanged(object sender, EventArgs e)
            {
                try
                {
                    ComboBoxZoomItem item = toolStripComboBoxWaveform.SelectedItem as ComboBoxZoomItem;
                    if (item != null)
                        audioVisualizer.ZoomFactor = item.ZoomFactor;
                }
                catch
                {
                }
            }

            private void SelectZoomTextInComboBox()
            {
                int i = 0;
                foreach (ComboBoxZoomItem item in toolStripComboBoxWaveform.Items)
                {
                    if (Math.Abs(audioVisualizer.ZoomFactor - item.ZoomFactor) < 0.001)
                    {
                        toolStripComboBoxWaveform.SelectedIndex = i;
                        return;
                    }
                    i++;
                }
            }

            private void toolStripButtonWaveformPause_Click(object sender, EventArgs e)
            {
                mediaPlayer.Pause();
            }

            private void toolStripButtonWaveformPlay_Click(object sender, EventArgs e)
            {
                mediaPlayer.Play();
            }

            private void toolStripButtonLockCenter_Click(object sender, EventArgs e)
            {
                toolStripButtonLockCenter.Checked = !toolStripButtonLockCenter.Checked;
                audioVisualizer.Locked = toolStripButtonLockCenter.Checked;
                Configuration.Settings.General.WaveformCenter = audioVisualizer.Locked;
            }

            private void trackBarWaveformPosition_ValueChanged(object sender, EventArgs e)
            {
                mediaPlayer.CurrentPosition = trackBarWaveformPosition.Value;
            }

            private void buttonCustomUrl_Click(object sender, EventArgs e)
            {
                RunCustomSearch(Configuration.Settings.VideoControls.CustomSearchUrl1);
            }

            private void buttonCustomUrl2_Click(object sender, EventArgs e)
            {
                RunCustomSearch(Configuration.Settings.VideoControls.CustomSearchUrl2);
            }

            private void ShowhideWaveformToolStripMenuItemClick(object sender, EventArgs e)
            {
                toolStripButtonToggleWaveform_Click(null, null);
            }

            private void AudioWaveformDragEnter(object sender, DragEventArgs e)
            {
                // make sure they're actually dropping files (not text or anything else)
                if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
                    e.Effect = DragDropEffects.All;
            }

            private void AudioWaveformDragDrop(object sender, DragEventArgs e)
            {
                var files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files.Length != 1)
                {
                    MessageBox.Show(_language.DropOnlyOneFile);
                    return;
                }

                string fileName = files[0];
                string ext = Path.GetExtension(fileName).ToLowerInvariant();
                if (ext != ".wav" || !WavePeakGenerator.IsFileValidForVisualizer(fileName))
                {
                    if (audioVisualizer.WavePeaks == null && (Utilities.VideoFileExtensions.Contains(ext) || ext == ".wav" || ext == ".mp3" || ext == ".mka" || ext == ".m4a" || ext == ".wma"))
                    {
                        _videoFileName = fileName;
                        AudioWaveform_Click(null, null);
                        OpenVideo(_videoFileName);
                        return;
                    }
                    try
                    {
                        var fi = new FileInfo(fileName);
                        if (fi.Length < 1024 * 500)
                        {
                            var lines = new List<string>(File.ReadAllLines(fileName));
                            foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
                            {
                                if (format.IsMine(lines, fileName))
                                {
                                    OpenSubtitle(fileName, null);
                                    return;
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }

                if (ext != ".wav")
                {
                    MessageBox.Show(".wav only!");
                    return;
                }

                if (_videoFileName == null)
                {
                    OpenVideo(fileName);
                    return;
                }

                using (var addWaveform = new AddWaveform())
                {
                    string peakWaveFileName = WavePeakGenerator.GetPeakWaveFileName(_videoFileName);
                    string spectrogramFolder = Nikse.SubtitleEdit.Core.WavePeakGenerator.SpectrogramDrawer.GetSpectrogramFolder(_videoFileName);
                    addWaveform.InitializeViaWaveFile(fileName, peakWaveFileName, spectrogramFolder);
                    if (addWaveform.ShowDialog() == DialogResult.OK)
                    {
                        audioVisualizer.WavePeaks = addWaveform.Peaks;
                        audioVisualizer.Spectrogram = addWaveform.Spectrogram;
                        timerWaveform.Start();
                    }
                }
            }

            private void toolStripMenuItemImportBluRaySup_Click(object sender, EventArgs e)
            {
                if (ContinueNewOrExit())
                {
                    openFileDialog1.Title = _language.OpenBluRaySupFile;
                    openFileDialog1.FileName = string.Empty;
                    openFileDialog1.Filter = _language.BluRaySupFiles + "|*.sup";
                    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                    {
                        ImportAndOcrBluRaySup(openFileDialog1.FileName, false);
                    }
                }
            }

            private void ImportAndOcrBluRaySup(string fileName, bool showInTaskbar)
            {
                var log = new StringBuilder();
                var subtitles = BluRaySupParser.ParseBluRaySup(fileName, log);
                if (subtitles.Count == 0)
                {
                    string msg = _language.BlurayNotSubtitlesFound + Environment.NewLine + Environment.NewLine + log.ToString();
                    if (msg.Length > 800)
                        msg = msg.Substring(0, 800);
                    MessageBox.Show(msg.Trim() + "...");
                    return;
                }

                using (var vobSubOcr = new VobSubOcr())
                {
                    if (showInTaskbar)
                    {
                        vobSubOcr.Icon = (Icon)Icon.Clone();
                        vobSubOcr.ShowInTaskbar = true;
                        vobSubOcr.ShowIcon = true;
                    }
                    vobSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName);
                    vobSubOcr.FileName = Path.GetFileName(fileName);
                    if (vobSubOcr.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeImportingBluRaySupFile);
                        FileNew();
                        _subtitle.Paragraphs.Clear();
                        SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        _subtitle.WasLoadedWithFrameNumbers = false;
                        _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                        foreach (var p in vobSubOcr.SubtitleFromOcr.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }

                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        _subtitleListViewIndex = -1;
                        SubtitleListview1.FirstVisibleIndex = -1;
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        _fileName = Path.ChangeExtension(vobSubOcr.FileName, new SubRip().Extension);
                        SetTitle();
                        _converted = true;

                        Configuration.Settings.Save();
                    }
                    else
                    {
                        _exitWhenLoaded = _loading;
                    }
                }
            }

            private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
            {
                GetFocusedTextBox().SelectAll();
            }

            private void cutToolStripMenuItem_Click(object sender, EventArgs e)
            {
                GetFocusedTextBox().Cut();
            }

            private void copyToolStripMenuItem_Click(object sender, EventArgs e)
            {
                GetFocusedTextBox().Copy();
            }

            private void PasteToolStripMenuItemClick(object sender, EventArgs e)
            {
                GetFocusedTextBox().Paste();
            }

            private void DeleteToolStripMenuItemClick(object sender, EventArgs e)
            {
                GetFocusedTextBox().SelectedText = string.Empty;
            }

            private void NormalToolStripMenuItem1Click(object sender, EventArgs e)
            {
                var tb = GetFocusedTextBox();

                string text = tb.SelectedText;
                int selectionStart = tb.SelectionStart;
                text = HtmlUtil.RemoveHtmlTags(text);
                tb.SelectedText = text;
                tb.SelectionStart = selectionStart;
                tb.SelectionLength = text.Length;
            }

            private TextBox GetFocusedTextBox()
            {
                if (!textBoxListViewTextAlternate.Visible)
                    return textBoxListViewText;
                return textBoxListViewTextAlternate.Focused ? textBoxListViewTextAlternate : textBoxListViewText;
            }

            private void TextBoxListViewToggleTag(string tag)
            {
                var tb = GetFocusedTextBox();

                string text;
                int selectionStart = tb.SelectionStart;

                // No text selected.
                if (tb.SelectedText.Length == 0)
                {
                    text = tb.Text;

                    // Split lines (split a subtitle into its lines).
                    var lines = text.SplitToLines();

                    // Get current line index (the line where the cursor is current located).
                    int selectedLineIdx = tb.GetLineFromCharIndex(tb.SelectionStart);

                    // Get line from index.
                    string selectedLine = lines[selectedLineIdx];

                    // Test if line at where cursor is current at is a dialog.
                    bool isDialog = selectedLine.StartsWith('-') ||
                        selectedLine.StartsWith("<" + tag + ">-", StringComparison.OrdinalIgnoreCase);

                    // Will be used keep cursor in its previous location after toggle/untoggle.
                    int textLen = text.Length;

                    // 1st set the cursor position to zero.
                    tb.SelectionStart = 0;

                    // If is dialog, only toggle/Untoggle line where caret/cursor is current at.
                    if (isDialog)
                    {
                        lines[selectedLineIdx] = HtmlUtil.ToggleTag(selectedLine, tag);
                        text = string.Join(Environment.NewLine, lines);
                    }
                    else
                    {
                        text = HtmlUtil.ToggleTag(text, tag);
                    }
                    tb.Text = text;
                    // Note: Math.Max will prevent blowing if caret is at the begining and tag was untoggled.
                    tb.SelectionStart = textLen > text.Length ? Math.Max(selectionStart - 3, 0) : selectionStart + 3;
                }
                else
                {
                    string post = string.Empty;
                    string pre = string.Empty;
                    // There is text selected
                    text = tb.SelectedText;
                    while (text.EndsWith(' ') || text.EndsWith(Environment.NewLine, StringComparison.Ordinal) || text.StartsWith(' ') || text.StartsWith(Environment.NewLine, StringComparison.Ordinal))
                    {
                        if (text.EndsWith(' '))
                        {
                            post += " ";
                            text = text.Remove(text.Length - 1);
                        }
                        if (text.EndsWith(Environment.NewLine, StringComparison.Ordinal))
                        {
                            post += Environment.NewLine;
                            text = text.Remove(text.Length - 2);
                        }
                        if (text.StartsWith(' '))
                        {
                            pre += " ";
                            text = text.Remove(0, 1);
                        }
                        if (text.StartsWith(Environment.NewLine, StringComparison.Ordinal))
                        {
                            pre += Environment.NewLine;
                            text = text.Remove(0, 2);
                        }
                    }
                    text = HtmlUtil.ToggleTag(text, tag);
                    // Update text and maintain selection.
                    if (pre.Length > 0)
                    {
                        text = pre + text;
                        selectionStart += pre.Length;
                    }
                    if (post.Length > 0)
                    {
                        text = text + post;
                    }
                    tb.SelectedText = text;
                    tb.SelectionStart = selectionStart;
                    tb.SelectionLength = text.Length;
                }
            }

            private void BoldToolStripMenuItem1Click(object sender, EventArgs e)
            {
                TextBoxListViewToggleTag(HtmlUtil.TagBold);
            }

            private void ItalicToolStripMenuItem1Click(object sender, EventArgs e)
            {
                TextBoxListViewToggleTag(HtmlUtil.TagItalic);
            }

            private void UnderlineToolStripMenuItem1Click(object sender, EventArgs e)
            {
                TextBoxListViewToggleTag(HtmlUtil.TagUnderline);
            }

            private void ColorToolStripMenuItem1Click(object sender, EventArgs e)
            {
                var tb = GetFocusedTextBox();
                string text = tb.SelectedText;
                int selectionStart = tb.SelectionStart;

                string color;
                if (GetCurrentSubtitleFormat().GetType() == typeof(Ebu))
                {
                    using (var form = new EbuColorPicker())
                    {
                        if (form.ShowDialog(this) != DialogResult.OK)
                            return;
                        color = form.Color;
                    }
                }
                else
                {
                    if (colorDialog1.ShowDialog(this) != DialogResult.OK)
                        return;
                    color = Utilities.ColorToHex(colorDialog1.Color);
                }

                bool done = false;
                string s = text;
                if (s.StartsWith("<font ", StringComparison.Ordinal))
                {
                    int end = s.IndexOf('>');
                    if (end > 0)
                    {
                        string f = s.Substring(0, end);
                        if (f.Contains(" face=") && !f.Contains(" color="))
                        {
                            var start = s.IndexOf(" face=", StringComparison.Ordinal);
                            s = s.Insert(start, string.Format(" color=\"{0}\"", color));
                            text = s;
                            done = true;
                        }
                        else if (f.Contains(" color="))
                        {
                            int colorStart = f.IndexOf(" color=", StringComparison.Ordinal);
                            if (s.IndexOf('"', colorStart + " color=".Length + 1) > 0)
                                end = s.IndexOf('"', colorStart + " color=".Length + 1);
                            s = s.Substring(0, colorStart) + string.Format(" color=\"{0}", color) + s.Substring(end);
                            text = s;
                            done = true;
                        }
                    }
                }

                if (!done)
                    text = string.Format("<font color=\"{0}\">{1}</font>", color, text);

                tb.SelectedText = text;
                tb.SelectionStart = selectionStart;
                tb.SelectionLength = text.Length;
            }

            private void FontNameToolStripMenuItemClick(object sender, EventArgs e)
            {
                var tb = GetFocusedTextBox();

                // font name
                string text = tb.SelectedText;
                int selectionStart = tb.SelectionStart;

                if (fontDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    bool done = false;

                    if (text.StartsWith("<font ", StringComparison.Ordinal))
                    {
                        int end = text.IndexOf('>');
                        if (end > 0)
                        {
                            string f = text.Substring(0, end);
                            if (f.Contains(" color=") && !f.Contains(" face="))
                            {
                                var start = text.IndexOf(" color=", StringComparison.Ordinal);
                                text = text.Insert(start, string.Format(" face=\"{0}\"", fontDialog1.Font.Name));
                                done = true;
                            }
                            else if (f.Contains(" face="))
                            {
                                int faceStart = f.IndexOf(" face=", StringComparison.Ordinal);
                                if (text.IndexOf('"', faceStart + " face=".Length + 1) > 0)
                                    end = text.IndexOf('"', faceStart + " face=".Length + 1);
                                text = text.Substring(0, faceStart) + string.Format(" face=\"{0}", fontDialog1.Font.Name) + text.Substring(end);
                                done = true;
                            }
                        }
                    }
                    if (!done)
                        text = string.Format("<font face=\"{0}\">{1}</font>", fontDialog1.Font.Name, text);

                    tb.SelectedText = text;
                    tb.SelectionStart = selectionStart;
                    tb.SelectionLength = text.Length;
                }
            }

            public void SetSubtitle(Subtitle subtitle, string message)
            {
                _subtitle = subtitle;
                SubtitleListview1.Fill(subtitle, _subtitleAlternate);
                ShowStatus(message);
            }

            #region Networking

            private void startServerToolStripMenuItem_Click(object sender, EventArgs e)
            {
                using (var networkNew = new NetworkStart())
                {
                    _networkSession = new NikseWebServiceSession(_subtitle, _subtitleAlternate, TimerWebServiceTick, OnUpdateUserLogEntries);
                    networkNew.Initialize(_networkSession, _fileName);
                    if (networkNew.ShowDialog(this) == DialogResult.OK)
                    {
                        _networkSession.AppendToLog(string.Format(_language.XStartedSessionYAtZ, _networkSession.CurrentUser.UserName, _networkSession.SessionId, DateTime.Now.ToLongTimeString()));
                        toolStripStatusNetworking.Visible = true;
                        toolStripStatusNetworking.Text = _language.NetworkMode;
                        EnableDisableControlsNotWorkingInNetworkMode(false);
                        SubtitleListview1.ShowNetworkColumn(_language.UserAndAction);
                        SubtitleListview1.AutoSizeAllColumns(this);
                        TimerWebServiceTick(null, null);
                    }
                    else
                    {
                        _networkSession = null;
                    }
                }
            }

            private void joinSessionToolStripMenuItem_Click(object sender, EventArgs e)
            {
                _networkSession = new NikseWebServiceSession(_subtitle, _subtitleAlternate, TimerWebServiceTick, OnUpdateUserLogEntries);
                using (var networkJoin = new NetworkJoin())
                {
                    networkJoin.Initialize(_networkSession);

                    if (networkJoin.ShowDialog(this) == DialogResult.OK)
                    {
                        _subtitle = _networkSession.Subtitle;
                        _subtitleAlternate = _networkSession.OriginalSubtitle;
                        if (_subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                            SubtitleListview1.ShowAlternateTextColumn(_languageGeneral.OriginalText);
                        _fileName = networkJoin.FileName;
                        SetTitle();
                        Text = Title;
                        toolStripStatusNetworking.Visible = true;
                        toolStripStatusNetworking.Text = _language.NetworkMode;
                        EnableDisableControlsNotWorkingInNetworkMode(false);
                        _networkSession.AppendToLog(string.Format(_language.XStartedSessionYAtZ, _networkSession.CurrentUser.UserName, _networkSession.SessionId, DateTime.Now.ToLongTimeString()));
                        SubtitleListview1.ShowNetworkColumn(_language.UserAndAction);
                        SubtitleListview1.AutoSizeAllColumns(this);
                        _subtitleListViewIndex = -1;
                        _oldSelectedParagraph = null;

                        if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                        {
                            buttonUnBreak.Visible = false;
                            buttonAutoBreak.Visible = false;
                            buttonSplitLine.Visible = false;

                            textBoxListViewText.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
                            textBoxListViewText.Width = (groupBoxEdit.Width - (textBoxListViewText.Left + 10)) / 2;
                            textBoxListViewTextAlternate.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
                            textBoxListViewTextAlternate.Left = textBoxListViewText.Left + textBoxListViewText.Width + 3;
                            textBoxListViewTextAlternate.Width = textBoxListViewText.Width;
                            textBoxListViewTextAlternate.Visible = true;
                            labelAlternateText.Text = _languageGeneral.OriginalText;
                            labelAlternateText.Visible = true;
                            labelAlternateCharactersPerSecond.Visible = true;
                            labelTextAlternateLineLengths.Visible = true;
                            labelAlternateSingleLine.Visible = true;
                            labelTextAlternateLineTotal.Visible = true;

                            labelCharactersPerSecond.Left = textBoxListViewText.Left + (textBoxListViewText.Width - labelCharactersPerSecond.Width);
                            labelTextLineTotal.Left = textBoxListViewText.Left + (textBoxListViewText.Width - labelTextLineTotal.Width);
                            AddAlternate();
                            Main_Resize(null, null);
                            _changeAlternateSubtitleToString = _subtitleAlternate.ToText(new SubRip()).Trim();
                        }
                        else
                        {
                            RemoveAlternate(false);
                        }
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);
                        TimerWebServiceTick(null, null);
                    }
                    else
                    {
                        _networkSession = null;
                    }
                }
            }

            private void EnableDisableControlsNotWorkingInNetworkMode(bool enabled)
            {
                //Top menu
                newToolStripMenuItem.Enabled = enabled;
                openToolStripMenuItem.Enabled = enabled;
                reopenToolStripMenuItem.Enabled = enabled;
                toolStripMenuItemOpenContainingFolder.Enabled = enabled;
                toolStripMenuItemCompare.Enabled = enabled;
                toolStripMenuItemImportDvdSubtitles.Enabled = enabled;
                toolStripMenuItemSubIdx.Enabled = enabled;
                toolStripMenuItemImportBluRaySup.Enabled = enabled;
                matroskaImportStripMenuItem.Enabled = enabled;
                toolStripMenuItemManualAnsi.Enabled = enabled;
                toolStripMenuItemImportText.Enabled = enabled;
                toolStripMenuItemImportTimeCodes.Enabled = enabled;

                showHistoryforUndoToolStripMenuItem.Enabled = enabled;
                multipleReplaceToolStripMenuItem.Enabled = enabled;

                toolsToolStripMenuItem.Enabled = enabled;

                toolStripMenuItemSynchronization.Enabled = enabled;

                toolStripMenuItemAutoTranslate.Enabled = enabled;

                //Toolbar
                toolStripButtonFileNew.Enabled = enabled;
                toolStripButtonFileOpen.Enabled = enabled;
                toolStripMenuItemOpenKeepVideo.Enabled = enabled;
                toolStripMenuItemRestoreAutoBackup.Enabled = enabled;
                toolStripButtonVisualSync.Enabled = enabled;

                // textbox source
                textBoxSource.ReadOnly = !enabled;
            }

            internal void TimerWebServiceTick(object sender, EventArgs e)
            {
                if (_networkSession == null)
                    return;

                List<int> deleteIndices = new List<int>();
                NetworkGetSendUpdates(deleteIndices, 0, null);
            }

            private void NetworkGetSendUpdates(List<int> deleteIndices, int insertIndex, Paragraph insertParagraph)
            {
                _networkSession.TimerStop();

                bool doReFill = false;
                bool updateListViewStatus = false;
                SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                string message = string.Empty;

                int numberOfLines = 0;
                List<SeNetworkService.SeUpdate> updates = null;
                int numberOfRetries = 10;
                while (numberOfRetries > 0)
                {
                    numberOfRetries--;
                    try
                    {
                        updates = _networkSession.GetUpdates(out message, out numberOfLines);
                        numberOfRetries = 0;
                    }
                    catch (Exception exception)
                    {
                        if (numberOfRetries <= 0)
                        {
                            if (exception.InnerException != null)
                                MessageBox.Show(string.Format(_language.NetworkUnableToConnectToServer, exception.InnerException.Message + Environment.NewLine + exception.InnerException.StackTrace));
                            else
                                MessageBox.Show(string.Format(_language.NetworkUnableToConnectToServer, exception.Message + Environment.NewLine + exception.StackTrace));
                            _networkSession.TimerStop();
                            if (_networkChat != null && !_networkChat.IsDisposed)
                            {
                                _networkChat.Close();
                                _networkChat = null;
                            }
                            _networkSession = null;
                            EnableDisableControlsNotWorkingInNetworkMode(true);
                            toolStripStatusNetworking.Visible = false;
                            SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Network);
                            _networkChat = null;
                            return;
                        }

                        Application.DoEvents();
                        System.Threading.Thread.Sleep(250);
                    }
                }
                int currentSelectedIndex = -1;
                if (SubtitleListview1.SelectedItems.Count > 0)
                    currentSelectedIndex = SubtitleListview1.SelectedItems[0].Index;
                int oldCurrentSelectedIndex = currentSelectedIndex;
                if (message == "OK")
                {
                    foreach (var update in updates)
                    {
                        if (!string.IsNullOrEmpty(update.Text))
                        {
                            if (!update.Text.Contains(Environment.NewLine))
                                update.Text = update.Text.Replace("\n", Environment.NewLine);
                            update.Text = WebUtility.HtmlDecode(update.Text).Replace("<br />", Environment.NewLine);
                        }
                        if (update.User.Ip != _networkSession.CurrentUser.Ip || update.User.UserName != _networkSession.CurrentUser.UserName)
                        {
                            if (update.Action == "USR")
                            {
                                _networkSession.Users.Add(update.User);
                                if (_networkChat != null && !_networkChat.IsDisposed)
                                {
                                    _networkChat.AddUser(update.User);
                                }
                                _networkSession.AppendToLog(string.Format(_language.NetworkNewUser, update.User.UserName, update.User.Ip));
                            }
                            else if (update.Action == "MSG")
                            {
                                _networkSession.ChatLog.Add(new NikseWebServiceSession.ChatEntry { User = update.User, Message = update.Text });
                                if (_networkChat == null || _networkChat.IsDisposed)
                                {
                                    _networkChat = new NetworkChat();
                                    _networkChat.Initialize(_networkSession);
                                    _networkChat.Show(this);
                                }
                                else
                                {
                                    _networkChat.AddChatMessage(update.User, update.Text);
                                }
                                if (!string.IsNullOrEmpty(Configuration.Settings.NetworkSettings.NewMessageSound) && File.Exists(Configuration.Settings.NetworkSettings.NewMessageSound))
                                {
                                    try
                                    {
                                        using (var soundPlayer = new System.Media.SoundPlayer(Configuration.Settings.NetworkSettings.NewMessageSound))
                                        {
                                            soundPlayer.Play();
                                        }
                                    }
                                    catch
                                    {
                                    }
                                }
                                _networkSession.AppendToLog(string.Format(_language.NetworkMessage, update.User.UserName, update.User.Ip, update.Text));
                            }
                            else if (update.Action == "DEL")
                            {
                                doReFill = true;
                                _subtitle.Paragraphs.RemoveAt(update.Index);
                                if (_networkSession.LastSubtitle != null)
                                    _networkSession.LastSubtitle.Paragraphs.RemoveAt(update.Index);
                                _networkSession.AppendToLog(string.Format(_language.NetworkDelete, update.User.UserName, update.User.Ip, update.Index));
                                _networkSession.AdjustUpdateLogToDelete(update.Index);

                                if (deleteIndices.Count > 0)
                                {
                                    for (int i = deleteIndices.Count - 1; i >= 0; i--)
                                    {
                                        int index = deleteIndices[i];
                                        if (index == update.Index)
                                            deleteIndices.RemoveAt(i);
                                        else if (index > update.Index)
                                            deleteIndices[i] = index - 1;
                                    }
                                }

                                if (insertIndex > update.Index)
                                    insertIndex--;
                                if (currentSelectedIndex >= 0 && currentSelectedIndex > update.Index)
                                    currentSelectedIndex--;
                            }
                            else if (update.Action == "INS")
                            {
                                doReFill = true;
                                var p = new Paragraph(update.Text, update.StartMilliseconds, update.EndMilliseconds);
                                _subtitle.Paragraphs.Insert(update.Index, p);
                                if (_networkSession.LastSubtitle != null)
                                    _networkSession.LastSubtitle.Paragraphs.Insert(update.Index, new Paragraph(p));
                                _networkSession.AppendToLog(string.Format(_language.NetworkInsert, update.User.UserName, update.User.Ip, update.Index, UiUtil.GetListViewTextFromString(update.Text)));
                                _networkSession.AddToWsUserLog(update.User, update.Index, update.Action, false);
                                updateListViewStatus = true;
                                _networkSession.AdjustUpdateLogToInsert(update.Index);

                                if (deleteIndices.Count > 0)
                                {
                                    for (int i = deleteIndices.Count - 1; i >= 0; i--)
                                    {
                                        int index = deleteIndices[i];
                                        if (index > update.Index)
                                            deleteIndices[i] = index + 1;
                                    }
                                }
                                if (insertIndex > update.Index)
                                    insertIndex++;
                                if (currentSelectedIndex >= 0 && currentSelectedIndex > update.Index)
                                    currentSelectedIndex++;
                            }
                            else if (update.Action == "UPD")
                            {
                                updateListViewStatus = true;
                                var p = _subtitle.GetParagraphOrDefault(update.Index);
                                if (p != null)
                                {
                                    p.StartTime.TotalMilliseconds = update.StartMilliseconds;
                                    p.EndTime.TotalMilliseconds = update.EndMilliseconds;
                                    p.Text = update.Text;
                                    SubtitleListview1.SetTimeAndText(update.Index, p, _subtitle.GetParagraphOrDefault(update.Index + 1));
                                    _networkSession.AppendToLog(string.Format(_language.NetworkUpdate, update.User.UserName, update.User.Ip, update.Index, UiUtil.GetListViewTextFromString(update.Text)));
                                    _networkSession.AddToWsUserLog(update.User, update.Index, update.Action, true);
                                    updateListViewStatus = true;
                                }
                                if (_networkSession.LastSubtitle != null)
                                {
                                    p = _networkSession.LastSubtitle.GetParagraphOrDefault(update.Index);
                                    if (p != null)
                                    {
                                        p.StartTime.TotalMilliseconds = update.StartMilliseconds;
                                        p.EndTime.TotalMilliseconds = update.EndMilliseconds;
                                        p.Text = update.Text;
                                    }
                                }
                            }
                            else if (update.Action == "BYE")
                            {
                                if (_networkChat != null && !_networkChat.IsDisposed)
                                    _networkChat.RemoveUser(update.User);

                                SeNetworkService.SeUser removeUser = null;
                                foreach (var user in _networkSession.Users)
                                {
                                    if (user.UserName == update.User.UserName)
                                    {
                                        removeUser = user;
                                        break;
                                    }
                                }
                                if (removeUser != null)
                                    _networkSession.Users.Remove(removeUser);

                                _networkSession.AppendToLog(string.Format(_language.NetworkByeUser, update.User.UserName, update.User.Ip));
                            }
                            else
                            {
                                _networkSession.AppendToLog("UNKNOWN ACTION: " + update.Action + " by " + update.User.UserName + " (" + update.User.Ip + ")");
                            }
                        }
                    }
                    if (numberOfLines != _subtitle.Paragraphs.Count)
                    {
                        _subtitle = _networkSession.ReloadSubtitle();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        UpdateListviewWithUserLogEntries();
                        _networkSession.LastSubtitle = new Subtitle(_subtitle);
                        _oldSelectedParagraph = null;
                        SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                        _networkSession.TimerStart();
                        RefreshSelectedParagraph();
                        return;
                    }
                    if (deleteIndices.Count > 0)
                    {
                        deleteIndices.Sort();
                        deleteIndices.Reverse();
                        foreach (int i in deleteIndices)
                        {
                            _subtitle.Paragraphs.RemoveAt(i);
                            if (_networkSession.LastSubtitle != null && i < _networkSession.LastSubtitle.Paragraphs.Count)
                                _networkSession.LastSubtitle.Paragraphs.RemoveAt(i);
                        }

                        _networkSession.DeleteLines(deleteIndices);
                        doReFill = true;
                    }
                    if (insertIndex >= 0 && insertParagraph != null)
                    {
                        _subtitle.Paragraphs.Insert(insertIndex, insertParagraph);
                        if (_networkSession.LastSubtitle != null && insertIndex < _networkSession.LastSubtitle.Paragraphs.Count)
                            _networkSession.LastSubtitle.Paragraphs.Insert(insertIndex, insertParagraph);
                        _networkSession.InsertLine(insertIndex, insertParagraph);
                        doReFill = true;
                    }
                    _networkSession.CheckForAndSubmitUpdates(); // updates only (no inserts/deletes)
                }
                else
                {
                    if (message == "Session not found!")
                    {
                        message = _networkSession.Restart();
                        if (message == "Reload")
                        {
                            _subtitle = _networkSession.ReloadSubtitle();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            UpdateListviewWithUserLogEntries();
                            _networkSession.LastSubtitle = new Subtitle(_subtitle);
                            _oldSelectedParagraph = null;
                            SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                            _networkSession.TimerStart();
                            RefreshSelectedParagraph();
                            return;
                        }
                        if (message == "OK")
                        {
                            _networkSession.TimerStart();
                            RefreshSelectedParagraph();
                            return;
                        }
                    }
                    else if (message == "User not found!")
                    {
                        message = _networkSession.ReJoin();
                        if (message == "Reload")
                        {
                            _subtitle = _networkSession.ReloadSubtitle();
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            UpdateListviewWithUserLogEntries();
                            _networkSession.LastSubtitle = new Subtitle(_subtitle);
                            _oldSelectedParagraph = null;
                            SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                            _networkSession.TimerStart();
                            RefreshSelectedParagraph();
                            return;
                        }
                    }

                    MessageBox.Show(message);
                    LeaveSessionToolStripMenuItemClick(null, null);
                    SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                    return;
                }
                if (doReFill)
                {
                    _subtitle.Renumber();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    UpdateListviewWithUserLogEntries();

                    if (oldCurrentSelectedIndex != currentSelectedIndex)
                    {
                        _oldSelectedParagraph = null;
                        _subtitleListViewIndex = currentSelectedIndex;
                        SubtitleListview1.SelectIndexAndEnsureVisible(_subtitleListViewIndex);
                    }
                    else if (_oldSelectedParagraph != null)
                    {
                        var p = _subtitle.GetFirstAlike(_oldSelectedParagraph);
                        if (p == null)
                        {
                            var tmp = new Paragraph(_oldSelectedParagraph);
                            tmp.Text = textBoxListViewText.Text;
                            p = _subtitle.GetFirstAlike(tmp);
                        }

                        if (p == null)
                        {
                            int idx = oldCurrentSelectedIndex;
                            if (idx >= _subtitle.Paragraphs.Count)
                                idx = _subtitle.Paragraphs.Count - 1;

                            if (idx >= 0 && idx < _subtitle.Paragraphs.Count)
                            {
                                SubtitleListview1.SelectIndexAndEnsureVisible(idx);
                                _listViewTextUndoIndex = -1;
                                SubtitleListView1SelectedIndexChange();
                                textBoxListViewText.Text = _subtitle.Paragraphs[idx].Text;
                            }
                        }
                        else
                        {
                            _subtitleListViewIndex = _subtitle.GetIndex(p);
                            SubtitleListview1.SelectIndexAndEnsureVisible(_subtitleListViewIndex);
                            _listViewTextUndoIndex = -1;
                            SubtitleListView1SelectedIndexChange();
                        }
                    }
                }
                else if (updateListViewStatus)
                {
                    UpdateListviewWithUserLogEntries();
                }
                _networkSession.LastSubtitle = new Subtitle(_subtitle);
                SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                _networkSession.TimerStart();
            }

            private void UpdateListviewWithUserLogEntries()
            {
                SubtitleListview1.BeginUpdate();
                foreach (UpdateLogEntry entry in _networkSession.UpdateLog)
                    SubtitleListview1.SetNetworkText(entry.Index, entry.ToString(), Utilities.GetColorFromUserName(entry.UserName));
                SubtitleListview1.EndUpdate();
            }

            private void LeaveSessionToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (_networkSession != null)
                {
                    _networkSession.TimerStop();
                    _networkSession.Leave();
                }
                if (_networkChat != null && !_networkChat.IsDisposed)
                {
                    _networkChat.Close();
                    _networkChat = null;
                }
                _networkSession = null;
                EnableDisableControlsNotWorkingInNetworkMode(true);
                toolStripStatusNetworking.Visible = false;
                SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.Network);
                _networkChat = null;
            }

            private void toolStripMenuItemNetworking_DropDownOpening(object sender, EventArgs e)
            {
                startServerToolStripMenuItem.Visible = _networkSession == null;
                joinSessionToolStripMenuItem.Visible = _networkSession == null;
                showSessionKeyLogToolStripMenuItem.Visible = _networkSession != null;
                leaveSessionToolStripMenuItem.Visible = _networkSession != null;
                chatToolStripMenuItem.Visible = _networkSession != null;
            }

            internal void OnUpdateUserLogEntries(object sender, EventArgs e)
            {
                UpdateListviewWithUserLogEntries();
            }

            private void toolStripStatusNetworking_Click(object sender, EventArgs e)
            {
                showSessionKeyLogToolStripMenuItem_Click(null, null);
            }

            private void showSessionKeyLogToolStripMenuItem_Click(object sender, EventArgs e)
            {
                using (var networkLog = new NetworkLogAndInfo())
                {
                    networkLog.Initialize(_networkSession);
                    networkLog.ShowDialog(this);
                }
            }

            private void chatToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (_networkSession != null)
                {
                    if (_networkChat == null || _networkChat.IsDisposed)
                    {
                        _networkChat = new NetworkChat();
                        _networkChat.Initialize(_networkSession);
                        _networkChat.Show(this);
                    }
                    else
                    {
                        _networkChat.WindowState = FormWindowState.Normal;
                    }
                }
            }

            #endregion Networking

            private void UnDockVideoPlayer()
            {
                bool firstUndock = _videoPlayerUndocked != null && !_videoPlayerUndocked.IsDisposed;

                _videoPlayerUndocked = new VideoPlayerUndocked(this, mediaPlayer);

                if (firstUndock)
                {
                    Configuration.Settings.General.UndockedVideoPosition = _videoPlayerUndocked.Left + @";" + _videoPlayerUndocked.Top + @";" + _videoPlayerUndocked.Width + @";" + _videoPlayerUndocked.Height;
                }

                Control control = null;
                if (splitContainer1.Panel2.Controls.Count == 0)
                {
                    control = panelVideoPlayer;
                    groupBoxVideo.Controls.Remove(control);
                }
                else if (splitContainer1.Panel2.Controls.Count > 0)
                {
                    control = panelVideoPlayer;
                    splitContainer1.Panel2.Controls.Clear();
                }
                if (control != null)
                {
                    control.Top = 0;
                    control.Left = 0;
                    control.Width = _videoPlayerUndocked.PanelContainer.Width;
                    control.Height = _videoPlayerUndocked.PanelContainer.Height;
                    _videoPlayerUndocked.PanelContainer.Controls.Add(control);
                }
            }

            public void ReDockVideoPlayer(Control control)
            {
                groupBoxVideo.Controls.Add(control);
                mediaPlayer.FontSizeFactor = 1.0F;
                mediaPlayer.SetSubtitleFont();
                mediaPlayer.SubtitleText = string.Empty;
            }

            private void UnDockWaveform()
            {
                _waveformUndocked = new WaveformUndocked(this);

                var control = audioVisualizer;
                groupBoxVideo.Controls.Remove(control);
                control.Top = 0;
                control.Left = 0;
                control.Width = _waveformUndocked.PanelContainer.Width;
                control.Height = _waveformUndocked.PanelContainer.Height - panelWaveformControls.Height;
                _waveformUndocked.PanelContainer.Controls.Add(control);

                var control2 = (Control)panelWaveformControls;
                groupBoxVideo.Controls.Remove(control2);
                control2.Top = control.Height;
                control2.Left = 0;
                _waveformUndocked.PanelContainer.Controls.Add(control2);

                var control3 = (Control)trackBarWaveformPosition;
                groupBoxVideo.Controls.Remove(control3);
                control3.Top = control.Height;
                control3.Left = control2.Width + 2;
                control3.Width = _waveformUndocked.PanelContainer.Width - control3.Left;
                _waveformUndocked.PanelContainer.Controls.Add(control3);
            }

            public void ReDockWaveform(Control waveform, Control buttons, Control trackBar)
            {
                groupBoxVideo.Controls.Add(waveform);
                waveform.Top = 30;
                waveform.Height = groupBoxVideo.Height - (waveform.Top + buttons.Height + 10);

                groupBoxVideo.Controls.Add(buttons);
                buttons.Top = waveform.Top + waveform.Height + 5;

                groupBoxVideo.Controls.Add(trackBar);
                trackBar.Top = buttons.Top;
            }

            private void UnDockVideoButtons()
            {
                _videoControlsUndocked = new VideoControlsUndocked(this);
                var control = tabControlButtons;
                groupBoxVideo.Controls.Remove(control);
                control.Top = 25;
                control.Left = 0;
                _videoControlsUndocked.PanelContainer.Controls.Add(control);

                groupBoxVideo.Controls.Remove(checkBoxSyncListViewWithVideoWhilePlaying);
                _videoControlsUndocked.PanelContainer.Controls.Add(checkBoxSyncListViewWithVideoWhilePlaying);
                checkBoxSyncListViewWithVideoWhilePlaying.Top = 5;
                checkBoxSyncListViewWithVideoWhilePlaying.Left = 5;

                splitContainerMain.Panel2Collapsed = true;
                splitContainer1.Panel2Collapsed = true;
            }

            public void ReDockVideoButtons(Control videoButtons, Control checkBoxSyncSubWithVideo)
            {
                groupBoxVideo.Controls.Add(videoButtons);
                videoButtons.Top = 12;
                videoButtons.Left = 5;

                groupBoxVideo.Controls.Add(checkBoxSyncSubWithVideo);
                checkBoxSyncSubWithVideo.Top = 11;
                checkBoxSyncSubWithVideo.Left = videoButtons.Left + videoButtons.Width + 5;
            }

            private void UndockVideoControlsToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (Configuration.Settings.General.Undocked)
                    return;

                Configuration.Settings.General.Undocked = true;

                var top = Math.Max(Top, 0);
                var left = Math.Max(Left, 0);
                UnDockVideoPlayer();
                splitContainerListViewAndText.SplitterDistance = splitContainerListViewAndText.Height - 109;
                if (toolStripButtonToggleVideo.Checked)
                {
                    _videoPlayerUndocked.Show(this);
                    if (_videoPlayerUndocked.Top < 0 || _videoPlayerUndocked.Left < 0)
                    {
                        _videoPlayerUndocked.WindowState = FormWindowState.Normal;
                        _videoPlayerUndocked.Top = top + 40;
                        _videoPlayerUndocked.Left = Math.Abs(left - 20);
                        _videoPlayerUndocked.Width = 600;
                        _videoPlayerUndocked.Height = 400;
                    }
                }

                UnDockWaveform();
                if (toolStripButtonToggleWaveform.Checked)
                {
                    _waveformUndocked.Show(this);
                    if (_waveformUndocked.Top < 0 || _waveformUndocked.Left < 0)
                    {
                        _waveformUndocked.WindowState = FormWindowState.Normal;
                        _waveformUndocked.Top = top + 60;
                        _waveformUndocked.Left = Math.Abs(left - 15);
                        _waveformUndocked.Width = 600;
                        _waveformUndocked.Height = 200;
                    }
                }

                UnDockVideoButtons();
                _videoControlsUndocked.Show(this);
                if (_videoControlsUndocked.Top < 0 || _videoControlsUndocked.Left < 0)
                {
                    _videoControlsUndocked.WindowState = FormWindowState.Normal;
                    _videoControlsUndocked.Top = top + 40;
                    _videoControlsUndocked.Left = Math.Abs(left - 10);
                    _videoControlsUndocked.Width = tabControlButtons.Width + 20;
                    _videoControlsUndocked.Height = tabControlButtons.Height + 65;
                }

                _isVideoControlsUndocked = true;
                SetUndockedWindowsTitle();

                undockVideoControlsToolStripMenuItem.Visible = false;
                redockVideoControlsToolStripMenuItem.Visible = true;

                tabControl1_SelectedIndexChanged(null, null);
                _videoControlsUndocked.Refresh();
            }

            public void RedockVideoControlsToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!Configuration.Settings.General.Undocked)
                    return;

                mediaPlayer.ShowNonFullScreenControls();

                SaveUndockedPositions();

                Configuration.Settings.General.Undocked = false;

                if (_videoControlsUndocked != null && !_videoControlsUndocked.IsDisposed)
                {
                    var control = _videoControlsUndocked.PanelContainer.Controls[0];
                    var controlCheckBox = _videoControlsUndocked.PanelContainer.Controls[1];
                    _videoControlsUndocked.PanelContainer.Controls.Clear();
                    ReDockVideoButtons(control, controlCheckBox);
                    _videoControlsUndocked.Close();
                    _videoControlsUndocked = null;
                }

                if (_waveformUndocked != null && !_waveformUndocked.IsDisposed)
                {
                    var controlWaveform = _waveformUndocked.PanelContainer.Controls[0];
                    var controlButtons = _waveformUndocked.PanelContainer.Controls[1];
                    var controlTrackBar = _waveformUndocked.PanelContainer.Controls[2];
                    _waveformUndocked.PanelContainer.Controls.Clear();
                    ReDockWaveform(controlWaveform, controlButtons, controlTrackBar);
                    _waveformUndocked.Close();
                    _waveformUndocked = null;
                }

                if (_videoPlayerUndocked != null && !_videoPlayerUndocked.IsDisposed)
                {
                    var control = _videoPlayerUndocked.PanelContainer.Controls[0];
                    _videoPlayerUndocked.PanelContainer.Controls.Remove(control);
                    ReDockVideoPlayer(control);
                    _videoPlayerUndocked.Close();
                    _videoPlayerUndocked = null;
                    mediaPlayer.ShowFullscreenButton = Configuration.Settings.General.VideoPlayerShowFullscreenButton;
                }

                _isVideoControlsUndocked = false;
                _videoPlayerUndocked = null;
                _waveformUndocked = null;
                _videoControlsUndocked = null;
                ShowVideoPlayer();

                audioVisualizer.Visible = toolStripButtonToggleWaveform.Checked;
                trackBarWaveformPosition.Visible = toolStripButtonToggleWaveform.Checked;
                panelWaveformControls.Visible = toolStripButtonToggleWaveform.Checked;
                if (!toolStripButtonToggleVideo.Checked)
                    HideVideoPlayer();

                mediaPlayer.Invalidate();
                Refresh();

                undockVideoControlsToolStripMenuItem.Visible = true;
                redockVideoControlsToolStripMenuItem.Visible = false;
            }

            internal void SetWaveformToggleOff()
            {
                toolStripButtonToggleWaveform.Checked = false;
            }

            internal void SetVideoPlayerToggleOff()
            {
                toolStripButtonToggleVideo.Checked = false;
            }

            private void ToolStripMenuItemInsertSubtitleClick(object sender, EventArgs e)
            {
                openFileDialog1.Title = _languageGeneral.OpenSubtitle;
                openFileDialog1.FileName = string.Empty;
                openFileDialog1.Filter = UiUtil.SubtitleExtensionFilter.Value;
                if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    if (!File.Exists(openFileDialog1.FileName))
                        return;

                    var fi = new FileInfo(openFileDialog1.FileName);
                    if (fi.Length > 1024 * 1024 * 10) // max 10 mb
                    {
                        var text = string.Format(_language.FileXIsLargerThan10MB + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, openFileDialog1.FileName);
                        if (MessageBox.Show(this, text, Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                            return;
                    }

                    MakeHistoryForUndo(string.Format(_language.BeforeInsertLine, openFileDialog1.FileName));

                    Encoding encoding;
                    var subtitle = new Subtitle();
                    SubtitleFormat format = subtitle.LoadSubtitle(openFileDialog1.FileName, out encoding, null);

                    if (format != null)
                    {
                        SaveSubtitleListviewIndices();
                        if (format.IsFrameBased)
                            subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                        else
                            subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                        if (Configuration.Settings.General.RemoveBlankLinesWhenOpening)
                            subtitle.RemoveEmptyLines();

                        int index = FirstSelectedIndex + 1;
                        if (index < 0)
                            index = 0;
                        foreach (var p in subtitle.Paragraphs)
                        {
                            _subtitle.Paragraphs.Insert(index, new Paragraph(p));
                            index++;
                        }

                        if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                        {
                            index = FirstSelectedIndex;
                            if (index < 0)
                                index = 0;
                            var current = _subtitle.GetParagraphOrDefault(index);
                            if (current != null)
                            {
                                var original = Utilities.GetOriginalParagraph(index, current, _subtitleAlternate.Paragraphs);
                                if (original != null)
                                {
                                    index = _subtitleAlternate.GetIndex(original);
                                    foreach (var p in subtitle.Paragraphs)
                                    {
                                        _subtitleAlternate.Paragraphs.Insert(index, new Paragraph(p));
                                        index++;
                                    }
                                    if (subtitle.Paragraphs.Count > 0)
                                        _subtitleAlternate.Renumber();
                                }
                            }
                        }
                        _subtitle.Renumber();
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void InsertLineToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (_subtitle == null || _subtitle.Paragraphs.Count == 0)
                {
                    InsertBefore();
                }
                else
                {
                    SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.Paragraphs.Count - 1);
                    InsertAfter();
                    SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.Paragraphs.Count - 1);
                }
            }

            private void CloseVideoToolStripMenuItemClick(object sender, EventArgs e)
            {
                timer1.Stop();
                if (mediaPlayer.VideoPlayer != null)
                {
                    mediaPlayer.PauseAndDisposePlayer();
                }
                mediaPlayer.SetPlayerName(string.Empty);
                mediaPlayer.ResetTimeLabel();
                mediaPlayer.VideoPlayer = null;
                _videoFileName = null;
                _videoInfo = null;
                _videoAudioTrackNumber = -1;
                labelVideoInfo.Text = _languageGeneral.NoVideoLoaded;
                audioVisualizer.WavePeaks = null;
                audioVisualizer.Spectrogram = null;
                audioVisualizer.SceneChanges = new List<double>();
                mediaPlayer.CurrentPosition = 0;
            }

            private void ToolStripMenuItemVideoDropDownOpening(object sender, EventArgs e)
            {
                if (_isVideoControlsUndocked)
                {
                    redockVideoControlsToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideoToggleVideoControls);
                    undockVideoControlsToolStripMenuItem.ShortcutKeys = Keys.None;
                }
                else
                {
                    undockVideoControlsToolStripMenuItem.ShortcutKeys = UiUtil.GetKeys(Configuration.Settings.Shortcuts.MainVideoToggleVideoControls);
                    redockVideoControlsToolStripMenuItem.ShortcutKeys = Keys.None;
                }

                closeVideoToolStripMenuItem.Visible = !string.IsNullOrEmpty(_videoFileName);
                setVideoOffsetToolStripMenuItem.Visible = !string.IsNullOrEmpty(_videoFileName);
                smpteTimeModedropFrameToolStripMenuItem.Visible = !string.IsNullOrEmpty(_videoFileName);
                if (!string.IsNullOrEmpty(_videoFileName))
                {
                    if (Configuration.Settings.General.CurrentVideoOffsetInMs > 0)
                    {
                        setVideoOffsetToolStripMenuItem.Text = string.Format("{0} [{1}]", _language.Menu.Video.SetVideoOffset, new TimeCode(Configuration.Settings.General.CurrentVideoOffsetInMs).ToShortDisplayString());
                    }
                    else
                    {
                        setVideoOffsetToolStripMenuItem.Text = _language.Menu.Video.SetVideoOffset;
                    }
                    smpteTimeModedropFrameToolStripMenuItem.Checked = mediaPlayer.SmpteMode;
                }

                toolStripMenuItemOpenVideoFromUrl.Visible = Configuration.Settings.General.VideoPlayer.Trim().Equals("MPV", StringComparison.OrdinalIgnoreCase) &&
                                                            LibMpvDynamic.IsInstalled &&
                                                            File.Exists(Path.Combine(Configuration.BaseDirectory, "youtube-dl.exe"));

                toolStripMenuItemSetAudioTrack.Visible = false;
                var libVlc = mediaPlayer.VideoPlayer as LibVlcDynamic;
                var libMpv = mediaPlayer.VideoPlayer as LibMpvDynamic;
                if (libVlc != null)
                {
                    var audioTracks = libVlc.GetAudioTracks();
                    _videoAudioTrackNumber = libVlc.AudioTrackNumber;
                    if (audioTracks.Count > 1)
                    {
                        toolStripMenuItemSetAudioTrack.DropDownItems.Clear();
                        for (int i = 0; i < audioTracks.Count; i++)
                        {
                            var at = audioTracks[i];
                            toolStripMenuItemSetAudioTrack.DropDownItems.Add(string.IsNullOrWhiteSpace(at.Value) ? at.Key.ToString(CultureInfo.InvariantCulture) : at.Value, null, ChooseAudioTrack);
                            toolStripMenuItemSetAudioTrack.DropDownItems[toolStripMenuItemSetAudioTrack.DropDownItems.Count - 1].Tag = at.Key.ToString(CultureInfo.InvariantCulture);
                            if (at.Key == _videoAudioTrackNumber)
                                toolStripMenuItemSetAudioTrack.DropDownItems[toolStripMenuItemSetAudioTrack.DropDownItems.Count - 1].Select();
                        }
                        toolStripMenuItemSetAudioTrack.Visible = true;
                    }
                }
                else if (libMpv != null)
                {
                    int numberOfTracks = libMpv.AudioTrackCount;
                    _videoAudioTrackNumber = libMpv.AudioTrackNumber;
                    if (numberOfTracks > 1)
                    {
                        toolStripMenuItemSetAudioTrack.DropDownItems.Clear();
                        for (int i = 0; i < numberOfTracks; i++)
                        {
                            toolStripMenuItemSetAudioTrack.DropDownItems.Add((i + 1).ToString(CultureInfo.InvariantCulture), null, ChooseAudioTrack);
                            if (i == _videoAudioTrackNumber)
                                toolStripMenuItemSetAudioTrack.DropDownItems[toolStripMenuItemSetAudioTrack.DropDownItems.Count - 1].Select();
                        }
                        toolStripMenuItemSetAudioTrack.Visible = true;
                    }
                }

                if (mediaPlayer.VideoPlayer != null && audioVisualizer != null && audioVisualizer.WavePeaks != null && audioVisualizer.WavePeaks.Peaks.Count > 0)
                {
                    toolStripMenuItemImportSceneChanges.Visible = true;
                    toolStripMenuItemRemoveSceneChanges.Visible = audioVisualizer.SceneChanges.Count > 0;
                }
                else
                {
                    toolStripMenuItemImportSceneChanges.Visible = false;
                    toolStripMenuItemRemoveSceneChanges.Visible = false;
                }

                generateTextFromCurrentVideoToolStripMenuItem.Visible = Configuration.Settings.General.ShowBetaStuff;
            }

            private void ChooseAudioTrack(object sender, EventArgs e)
            {
                var libVlc = mediaPlayer.VideoPlayer as LibVlcDynamic;
                var libMpv = mediaPlayer.VideoPlayer as LibMpvDynamic;
                if (libVlc != null)
                {
                    var item = sender as ToolStripItem;
                    int number = int.Parse(item.Tag.ToString());
                    libVlc.AudioTrackNumber = number;
                    _videoAudioTrackNumber = number;
                }
                else if (libMpv != null)
                {
                    var item = sender as ToolStripItem;
                    int number = int.Parse(item.Text);
                    number--;
                    libMpv.AudioTrackNumber = number;
                    _videoAudioTrackNumber = number;
                }
            }

            private void textBoxListViewTextAlternate_TextChanged(object sender, EventArgs e)
            {
                if (_subtitleAlternate == null || _subtitleAlternate.Paragraphs.Count < 1)
                    return;

                if (_subtitleListViewIndex >= 0)
                {
                    var original = Utilities.GetOriginalParagraph(_subtitleListViewIndex, _subtitle.Paragraphs[_subtitleListViewIndex], _subtitleAlternate.Paragraphs);
                    if (original != null)
                    {
                        string text = textBoxListViewTextAlternate.Text.TrimEnd();

                        // update _subtitle + listview
                        original.Text = text;
                        UpdateListViewTextInfo(labelTextAlternateLineLengths, labelAlternateSingleLine, labelTextAlternateLineTotal, labelAlternateCharactersPerSecond, original, textBoxListViewTextAlternate);
                        SubtitleListview1.SetAlternateText(_subtitleListViewIndex, text);
                    }
                }
            }

            private void TextBoxListViewTextAlternateKeyDown(object sender, KeyEventArgs e)
            {
                _listViewAlternateTextTicks = DateTime.UtcNow.Ticks;
                if (_subtitleAlternate == null || _subtitleAlternate.Paragraphs.Count < 1)
                    return;

                if (e.Modifiers == Keys.Shift && e.KeyCode == Keys.ShiftKey)
                    return;
                if (e.Modifiers == Keys.Control && e.KeyCode == (Keys.LButton | Keys.ShiftKey))
                { // surround ctrl+v action with history (for undo)
                    _listViewAlternateTextTicks = 0;
                    TimerAlternateTextUndoTick(sender, e);
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(50);
                    Application.DoEvents();
                    _listViewAlternateTextTicks = 0;
                    TimerAlternateTextUndoTick(sender, e);
                    return;
                }

                int numberOfLines = Utilities.GetNumberOfLines(textBoxListViewTextAlternate.Text);

                //Utilities.CheckAutoWrap(textBoxListViewTextAlternate, e, numberOfNewLines);

                if (e.Modifiers == Keys.None && e.KeyCode == Keys.Enter && numberOfLines > Configuration.Settings.Tools.ListViewSyntaxMoreThanXLinesX)
                {
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _mainTextBoxAutoBreak)
                {
                    if (textBoxListViewTextAlternate.Text.Length > 0)
                        textBoxListViewTextAlternate.Text = Utilities.AutoBreakLine(textBoxListViewTextAlternate.Text);
                    e.SuppressKeyPress = true;
                }
                else if (e.KeyData == _mainTextBoxUnbreak)
                {
                    textBoxListViewTextAlternate.Text = Utilities.UnbreakLine(textBoxListViewTextAlternate.Text);
                    e.SuppressKeyPress = true;
                }
                else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.I)
                {
                    if (textBoxListViewTextAlternate.SelectionLength == 0)
                    {
                        if (textBoxListViewTextAlternate.Text.Contains("<i>"))
                        {
                            textBoxListViewTextAlternate.Text = HtmlUtil.RemoveOpenCloseTags(textBoxListViewTextAlternate.Text, HtmlUtil.TagItalic);
                        }
                        else
                        {
                            textBoxListViewTextAlternate.Text = string.Format("<i>{0}</i>", textBoxListViewTextAlternate.Text);
                        }
                    }
                    else
                    {
                        TextBoxListViewToggleTag(HtmlUtil.TagItalic);
                    }
                }
                if (e.Modifiers == Keys.Control && e.KeyCode == Keys.D)
                {
                    textBoxListViewTextAlternate.SelectionLength = 0;
                    e.SuppressKeyPress = true;
                }
                else if (_mainTextBoxSelectionToLower == e.KeyData) // selection to lowercase
                {
                    if (textBoxListViewTextAlternate.SelectionLength > 0)
                    {
                        int start = textBoxListViewTextAlternate.SelectionStart;
                        int length = textBoxListViewTextAlternate.SelectionLength;
                        textBoxListViewTextAlternate.SelectedText = textBoxListViewTextAlternate.SelectedText.ToLower();
                        textBoxListViewTextAlternate.SelectionStart = start;
                        textBoxListViewTextAlternate.SelectionLength = length;
                        e.SuppressKeyPress = true;
                    }
                }
                else if (_mainTextBoxSelectionToUpper == e.KeyData) // selection to uppercase
                {
                    if (textBoxListViewTextAlternate.SelectionLength > 0)
                    {
                        int start = textBoxListViewTextAlternate.SelectionStart;
                        int length = textBoxListViewTextAlternate.SelectionLength;
                        textBoxListViewTextAlternate.SelectedText = textBoxListViewTextAlternate.SelectedText.ToUpper();
                        textBoxListViewTextAlternate.SelectionStart = start;
                        textBoxListViewTextAlternate.SelectionLength = length;
                        e.SuppressKeyPress = true;
                    }
                }

                // last key down in text
                _lastTextKeyDownTicks = DateTime.UtcNow.Ticks;

                UpdatePositionAndTotalLength(labelTextAlternateLineTotal, textBoxListViewTextAlternate);
            }

            private void OpenOriginalToolStripMenuItemClick(object sender, EventArgs e)
            {
                OpenAlternateSubtitle();
            }

            private void SaveOriginalAstoolStripMenuItemClick(object sender, EventArgs e)
            {
                if (_subtitleAlternate == null || _subtitleAlternate.Paragraphs.Count == 0)
                    return;

                SubtitleFormat currentFormat = GetCurrentSubtitleFormat();
                UiUtil.SetSaveDialogFilter(saveFileDialog1, currentFormat);

                saveFileDialog1.Title = _language.SaveOriginalSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + currentFormat.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_subtitleAlternateFileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    _subtitleAlternateFileName = saveFileDialog1.FileName;
                    SaveOriginalSubtitle(GetCurrentSubtitleFormat());
                    SetTitle();
                    if (_fileName != null)
                    {
                        Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                    }
                }
            }

            private void SaveOriginalToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (string.IsNullOrEmpty(_subtitleAlternateFileName))
                {
                    SaveOriginalAstoolStripMenuItemClick(null, null);
                    return;
                }

                try
                {
                    SaveOriginalSubtitle(GetCurrentSubtitleFormat());
                }
                catch
                {
                    MessageBox.Show(string.Format(_language.UnableToSaveSubtitleX, _subtitleAlternateFileName));
                }
            }

            private void RemoveOriginalToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (ContinueNewOrExitAlternate())
                {
                    RemoveAlternate(true);
                }
            }

            private void RemoveAlternate(bool removeFromListView)
            {
                if (removeFromListView)
                {
                    SubtitleListview1.HideColumn(SubtitleListView.SubtitleColumn.TextAlternate);
                    SubtitleListview1.AutoSizeAllColumns(this);
                    _subtitleAlternate = new Subtitle();
                    _subtitleAlternateFileName = null;

                    if (_fileName != null)
                    {
                        Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName, Configuration.Settings.General.CurrentVideoOffsetInMs);
                        Configuration.Settings.Save();
                        UpdateRecentFilesUI();
                    }
                }

                buttonUnBreak.Visible = true;
                buttonAutoBreak.Visible = true;
                textBoxListViewTextAlternate.Visible = false;
                labelAlternateText.Visible = false;
                labelAlternateCharactersPerSecond.Visible = false;
                labelTextAlternateLineLengths.Visible = false;
                labelAlternateSingleLine.Visible = false;
                labelTextAlternateLineTotal.Visible = false;
                textBoxListViewText.Width = (groupBoxEdit.Width - (textBoxListViewText.Left + 8 + buttonUnBreak.Width));
                textBoxListViewText.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;

                MainResize();
                SetTitle();
            }

            private void ToolStripMenuItemSpellCheckMainDropDownOpening(object sender, EventArgs e)
            {
                addWordToNameListToolStripMenuItem.Visible = true;
            }

            private void ToolStripMenuItemPlayRateSlowClick(object sender, EventArgs e)
            {
                if (mediaPlayer.VideoPlayer != null)
                {
                    toolStripMenuItemPlayRateSlow.Checked = true;
                    toolStripMenuItemPlayRateNormal.Checked = false;
                    toolStripMenuItemPlayRateFast.Checked = false;
                    toolStripMenuItemPlayRateVeryFast.Checked = false;
                    mediaPlayer.VideoPlayer.PlayRate = 0.8;
                    toolStripSplitButtonPlayRate.Image = imageListPlayRate.Images[1];
                }
            }

            private void ToolStripMenuItemPlayRateNormalClick(object sender, EventArgs e)
            {
                if (mediaPlayer.VideoPlayer != null)
                {
                    toolStripMenuItemPlayRateSlow.Checked = false;
                    toolStripMenuItemPlayRateNormal.Checked = true;
                    toolStripMenuItemPlayRateFast.Checked = false;
                    toolStripMenuItemPlayRateVeryFast.Checked = false;
                    mediaPlayer.VideoPlayer.PlayRate = 1.0;
                    toolStripSplitButtonPlayRate.Image = imageListPlayRate.Images[0];
                }
            }

            private void ToolStripMenuItemPlayRateFastClick(object sender, EventArgs e)
            {
                if (mediaPlayer.VideoPlayer != null)
                {
                    toolStripMenuItemPlayRateSlow.Checked = false;
                    toolStripMenuItemPlayRateNormal.Checked = false;
                    toolStripMenuItemPlayRateFast.Checked = true;
                    toolStripMenuItemPlayRateVeryFast.Checked = false;
                    mediaPlayer.VideoPlayer.PlayRate = 1.2;
                    toolStripSplitButtonPlayRate.Image = imageListPlayRate.Images[1];
                }
            }

            private void VeryFastToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (mediaPlayer.VideoPlayer != null)
                {
                    toolStripMenuItemPlayRateSlow.Checked = false;
                    toolStripMenuItemPlayRateNormal.Checked = false;
                    toolStripMenuItemPlayRateFast.Checked = false;
                    toolStripMenuItemPlayRateVeryFast.Checked = true;
                    mediaPlayer.VideoPlayer.PlayRate = 1.6;
                    toolStripSplitButtonPlayRate.Image = imageListPlayRate.Images[1];
                }
            }

            private void SplitContainer1SplitterMoved(object sender, SplitterEventArgs e)
            {
                Main_Resize(null, null);
            }

            private void ButtonSplitLineClick(object sender, EventArgs e)
            {
                SplitSelectedParagraph(null, null);
            }

            private void ToolStripMenuItemCopySourceTextClick(object sender, EventArgs e)
            {
                var selectedLines = new Subtitle(_subtitle);
                selectedLines.Paragraphs.Clear();
                foreach (int index in SubtitleListview1.SelectedIndices)
                    selectedLines.Paragraphs.Add(_subtitle.Paragraphs[index]);
                Clipboard.SetText(selectedLines.ToText(GetCurrentSubtitleFormat()).TrimEnd());
            }

            public void PlayPause()
            {
                mediaPlayer.TogglePlayPause();
            }

            public void SetCurrentViaEndPositionAndGotoNext(int index)
            {
                var p = _subtitle.GetParagraphOrDefault(index);
                if (p == null)
                    return;

                if (mediaPlayer.VideoPlayer == null || string.IsNullOrEmpty(_videoFileName))
                {
                    MessageBox.Show(_languageGeneral.NoVideoLoaded);
                    return;
                }

                //if (autoDuration)
                //{
                //    // TODO: auto duration
                //    // TODO: Search for start via wave file (must only be minor adjustment)
                //}

                // current movie Position
                double durationTotalMilliseconds = p.Duration.TotalMilliseconds;
                double totalMillisecondsEnd = mediaPlayer.CurrentPosition * TimeCode.BaseUnit;

                var tc = new TimeCode(totalMillisecondsEnd - durationTotalMilliseconds);
                MakeHistoryForUndo(_language.BeforeSetEndAndVideoPosition + "  " + tc);
                _makeHistoryPaused = true;

                if (p.StartTime.IsMaxTime)
                {
                    p.EndTime.TotalSeconds = mediaPlayer.CurrentPosition;
                    p.StartTime.TotalMilliseconds = p.EndTime.TotalMilliseconds - Utilities.GetOptimalDisplayMilliseconds(p.Text);
                }
                else
                {
                    p.StartTime.TotalMilliseconds = totalMillisecondsEnd - durationTotalMilliseconds;
                    p.EndTime.TotalMilliseconds = totalMillisecondsEnd;
                }

                timeUpDownStartTime.TimeCode = p.StartTime;
                var durationInSeconds = (decimal)(p.Duration.TotalSeconds);
                if (durationInSeconds >= numericUpDownDuration.Minimum && durationInSeconds <= numericUpDownDuration.Maximum)
                    SetDurationInSeconds((double)durationInSeconds);

                SubtitleListview1.SelectIndexAndEnsureVisible(index + 1);
                ShowStatus(string.Format(_language.VideoControls.AdjustedViaEndTime, p.StartTime.ToShortString()));
                audioVisualizer.Invalidate();
                _makeHistoryPaused = false;
            }

            public void SetCurrentStartAutoDurationAndGotoNext(int index)
            {
                var prev = _subtitle.GetParagraphOrDefault(index - 1);
                var p = _subtitle.GetParagraphOrDefault(index);
                if (p == null)
                    return;

                double videoPosition = mediaPlayer.CurrentPosition;
                if (prev != null && Math.Abs(prev.StartTime.TotalSeconds - videoPosition) < 0.3)
                {
                    ShowStatus("Subtitle already here");
                    return;
                }

                ShowNextSubtitleLabel();

                if (mediaPlayer.VideoPlayer == null || string.IsNullOrEmpty(_videoFileName))
                {
                    MessageBox.Show(_languageGeneral.NoVideoLoaded);
                    return;
                }

                MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.VideoControls.BeforeChangingTimeInWaveformX, "#" + p.Number + " " + p.Text));

                timeUpDownStartTime.MaskedTextBox.TextChanged -= MaskedTextBoxTextChanged;
                var oldParagraph = new Paragraph(_subtitle.Paragraphs[index]);
                if (!mediaPlayer.IsPaused)
                    videoPosition -= Configuration.Settings.General.SetStartEndHumanDelay / TimeCode.BaseUnit;

                timeUpDownStartTime.TimeCode = TimeCode.FromSeconds(videoPosition);

                double duration = Utilities.GetOptimalDisplayMilliseconds(textBoxListViewText.Text);

                _subtitle.Paragraphs[index].StartTime.TotalMilliseconds = TimeSpan.FromSeconds(videoPosition).TotalMilliseconds;
                if (prev != null && prev.EndTime.TotalMilliseconds > _subtitle.Paragraphs[index].StartTime.TotalMilliseconds)
                {
                    int minDiff = Configuration.Settings.General.MinimumMillisecondsBetweenLines + 1;
                    if (minDiff < 1)
                        minDiff = 1;
                    prev.EndTime.TotalMilliseconds = _subtitle.Paragraphs[index].StartTime.TotalMilliseconds - minDiff;
                }
                _subtitle.Paragraphs[index].EndTime.TotalMilliseconds = _subtitle.Paragraphs[index].StartTime.TotalMilliseconds + duration;
                SubtitleListview1.SetStartTimeAndDuration(index, _subtitle.Paragraphs[index], _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                timeUpDownStartTime.TimeCode = _subtitle.Paragraphs[index].StartTime;
                timeUpDownStartTime.MaskedTextBox.TextChanged += MaskedTextBoxTextChanged;
                UpdateOriginalTimeCodes(oldParagraph);
                _subtitleListViewIndex = -1;
                SubtitleListview1.SelectIndexAndEnsureVisible(index + 1);
                audioVisualizer.Invalidate();
            }

            public void SetCurrentEndNextStartAndGoToNext(int index)
            {
                var p = _subtitle.GetParagraphOrDefault(index);
                var next = _subtitle.GetParagraphOrDefault(index + 1);
                if (p == null)
                    return;

                if (mediaPlayer.VideoPlayer == null || string.IsNullOrEmpty(_videoFileName))
                {
                    MessageBox.Show(_languageGeneral.NoVideoLoaded);
                    return;
                }

                MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.VideoControls.BeforeChangingTimeInWaveformX, "#" + p.Number + " " + p.Text));

                double videoPosition = mediaPlayer.CurrentPosition;
                if (!mediaPlayer.IsPaused)
                    videoPosition -= Configuration.Settings.General.SetStartEndHumanDelay / TimeCode.BaseUnit;

                p.EndTime = TimeCode.FromSeconds(videoPosition);
                if (p.StartTime.IsMaxTime)
                {
                    timeUpDownStartTime.MaskedTextBox.TextChanged -= MaskedTextBoxTextChanged;
                    p.StartTime.TotalMilliseconds = p.EndTime.TotalMilliseconds - Utilities.GetOptimalDisplayMilliseconds(p.Text);
                    if (p.StartTime.TotalMilliseconds < 0)
                        p.StartTime.TotalMilliseconds = 0;
                    timeUpDownStartTime.TimeCode = p.StartTime;
                    SubtitleListview1.SetStartTimeAndDuration(index, p, _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));
                    timeUpDownStartTime.MaskedTextBox.TextChanged += MaskedTextBoxTextChanged;
                }
                if (p.Duration.TotalSeconds < 0 || p.Duration.TotalSeconds > 10)
                    p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + Utilities.GetOptimalDisplayMilliseconds(p.Text);

                SubtitleListview1.SetStartTimeAndDuration(index, p, _subtitle.GetParagraphOrDefault(index + 1), _subtitle.GetParagraphOrDefault(index - 1));

                SetDurationInSeconds(_subtitle.Paragraphs[index].Duration.TotalSeconds + 0.001);
                if (next != null)
                {
                    int addMilliseconds = Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                    if (addMilliseconds < 1 || addMilliseconds > 500)
                        addMilliseconds = 1;

                    var oldDuration = next.Duration.TotalMilliseconds;
                    if (next.StartTime.IsMaxTime || next.EndTime.IsMaxTime)
                        oldDuration = Utilities.GetOptimalDisplayMilliseconds(p.Text);
                    next.StartTime.TotalMilliseconds = p.EndTime.TotalMilliseconds + addMilliseconds;
                    next.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds + oldDuration;
                    SubtitleListview1.SetStartTimeAndDuration(index + 1, next, _subtitle.GetParagraphOrDefault(index + 2), _subtitle.GetParagraphOrDefault(index));
                    SubtitleListview1.SelectIndexAndEnsureVisible(index + 1);
                }
                audioVisualizer.Invalidate();
            }

            private void EditSelectAllToolStripMenuItemClick(object sender, EventArgs e)
            {
                for (int i = 0; i < SubtitleListview1.Items.Count; i++)
                    SubtitleListview1.Items[i].Selected = true;
            }

            private void ToolStripMenuItemSplitTextAtCursorClick(object sender, EventArgs e)
            {
                var tb = GetFocusedTextBox();

                int? pos = null;
                if (tb.SelectionStart > 1 && tb.SelectionStart < tb.Text.Length - 1)
                    pos = tb.SelectionStart;
                SplitSelectedParagraph(null, pos);
                tb.Focus();
                tb.SelectionStart = tb.Text.Length;
            }

            private void toolStripMenuItemSplitViaWaveform_Click(object sender, EventArgs e)
            {
                var tb = GetFocusedTextBox();
                if (tb.SelectionStart > 1 && tb.SelectionStart < tb.Text.Length - 1)
                {
                    int? pos = tb.SelectionStart;
                    SplitSelectedParagraph(mediaPlayer.CurrentPosition, pos);
                    tb.Focus();
                    tb.SelectionStart = tb.Text.Length;
                }
            }

            private void ContextMenuStripTextBoxListViewOpening(object sender, System.ComponentModel.CancelEventArgs e)
            {
                var tb = GetFocusedTextBox();
                toolStripMenuItemSplitTextAtCursor.Visible = tb.Text.Length > 1;

                if (IsUnicode)
                {
                    if (toolStripMenuItemInsertUnicodeSymbol.DropDownItems.Count == 0)
                    {
                        foreach (var s in Configuration.Settings.Tools.UnicodeSymbolsToInsert.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            toolStripMenuItemInsertUnicodeSymbol.DropDownItems.Add(s, null, InsertUnicodeGlyph);
                            if (Environment.OSVersion.Version.Major < 6 && Configuration.Settings.General.SubtitleFontName == Utilities.WinXP2KUnicodeFontName) // 6 == Vista/Win2008Server/Win7
                                toolStripMenuItemInsertUnicodeSymbol.DropDownItems[toolStripMenuItemInsertUnicodeSymbol.DropDownItems.Count - 1].Font = new Font(Utilities.WinXP2KUnicodeFontName, toolStripMenuItemInsertUnicodeSymbol.Font.Size);
                        }
                    }
                    toolStripMenuItemInsertUnicodeSymbol.Visible = toolStripMenuItemInsertUnicodeSymbol.DropDownItems.Count > 0;
                    toolStripSeparator26.Visible = toolStripMenuItemInsertUnicodeSymbol.DropDownItems.Count > 0;

                    superscriptToolStripMenuItem.Visible = tb.SelectionLength > 0;
                    subscriptToolStripMenuItem.Visible = tb.SelectionLength > 0;
                    toolStripMenuItemInsertUnicodeControlCharacters.Visible = true;
                }
                else
                {
                    toolStripMenuItemInsertUnicodeSymbol.Visible = false;
                    toolStripSeparator26.Visible = false;
                    superscriptToolStripMenuItem.Visible = false;
                    subscriptToolStripMenuItem.Visible = false;
                    toolStripMenuItemInsertUnicodeControlCharacters.Visible = false;
                }

                var formatType = GetCurrentSubtitleFormat().GetType();
                if ((formatType == typeof(WebVTT) && tb.SelectionLength > 0))
                {
                    toolStripSeparatorWebVTT.Visible = true;
                    toolStripMenuItemWebVttVoice.Visible = true;
                    var voices = WebVTT.GetVoices(_subtitle);
                    toolStripMenuItemWebVttVoice.DropDownItems.Clear();
                    foreach (var style in voices)
                    {
                        toolStripMenuItemWebVttVoice.DropDownItems.Add(style, null, WebVTTSetVoiceTextBox);
                    }
                    toolStripMenuItemWebVttVoice.DropDownItems.Add(_language.Menu.ContextMenu.WebVTTSetNewVoice, null, WebVTTSetNewVoiceTextBox);
                }
                else
                {
                    toolStripSeparatorWebVTT.Visible = false;
                    toolStripMenuItemWebVttVoice.Visible = false;
                }

                if (tb.SelectionStart > 1 && tb.SelectionStart < tb.Text.Length - 1 && !string.IsNullOrEmpty(_videoFileName) && mediaPlayer != null &&
                    _subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    int firstSelectedIndex = SubtitleListview1.SelectedItems[0].Index;
                    var currentParagraph = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                    var splitSeconds = mediaPlayer.CurrentPosition;
                    if (splitSeconds > (currentParagraph.StartTime.TotalSeconds + 0.2) && splitSeconds < (currentParagraph.EndTime.TotalSeconds - 0.2))
                        toolStripMenuItemSplitViaWaveform.Visible = true;
                    else
                        toolStripMenuItemSplitViaWaveform.Visible = false;
                }
                else
                {
                    toolStripMenuItemSplitViaWaveform.Visible = false;
                }
            }

            private void ToolStripMenuItemExportPngXmlClick(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), "BDNXML", _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void TabControlSubtitleSelecting(object sender, TabControlCancelEventArgs e)
            {
                if (tabControlSubtitle.SelectedIndex != TabControlSourceView && textBoxSource.Text.Trim().Length > 1)
                {
                    var currentFormat = GetCurrentSubtitleFormat();
                    if (currentFormat != null && !currentFormat.IsTextBased)
                        return;

                    SubtitleFormat format = new Subtitle().ReloadLoadSubtitle(textBoxSource.Lines.ToList(), _fileName, currentFormat);
                    if (format == null)
                        e.Cancel = true;
                }
            }

            private void ToolStripComboBoxFrameRateTextChanged(object sender, EventArgs e)
            {
                Configuration.Settings.General.CurrentFrameRate = CurrentFrameRate;
                if (_loading)
                    return;

                SubtitleListview1.UpdateFrames(_subtitle);
            }

            private void ToolStripMenuItemGoogleMicrosoftTranslateSelLineClick(object sender, EventArgs e)
            {
                int firstSelectedIndex = FirstSelectedIndex;
                if (firstSelectedIndex >= 0)
                {
                    var p = _subtitle.GetParagraphOrDefault(firstSelectedIndex);
                    if (p != null)
                    {
                        string defaultFromLanguage = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle);
                        string defaultToLanguage = defaultFromLanguage;
                        if (_subtitleAlternate != null)
                        {
                            var o = Utilities.GetOriginalParagraph(firstSelectedIndex, p, _subtitleAlternate.Paragraphs);
                            if (o != null)
                            {
                                p = o;
                                defaultFromLanguage = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitleAlternate);
                            }
                        }
                        Cursor = Cursors.WaitCursor;
                        if (_googleOrMicrosoftTranslate == null || _googleOrMicrosoftTranslate.IsDisposed)
                        {
                            _googleOrMicrosoftTranslate = new GoogleOrMicrosoftTranslate();
                            _googleOrMicrosoftTranslate.InitializeFromLanguage(defaultFromLanguage, defaultToLanguage);
                        }
                        _googleOrMicrosoftTranslate.Initialize(p);
                        Cursor = Cursors.Default;
                        if (_googleOrMicrosoftTranslate.ShowDialog() == DialogResult.OK)
                        {
                            textBoxListViewText.Text = _googleOrMicrosoftTranslate.TranslatedText;
                        }
                    }
                }
            }

            private void NumericUpDownSec1ValueChanged(object sender, EventArgs e)
            {
                Configuration.Settings.General.SmallDelayMilliseconds = (int)(numericUpDownSec1.Value * 1000);
            }

            private void NumericUpDownSec2ValueChanged(object sender, EventArgs e)
            {
                Configuration.Settings.General.LargeDelayMilliseconds = (int)(numericUpDownSec2.Value * 1000);
            }

            private void NumericUpDownSecAdjust1ValueChanged(object sender, EventArgs e)
            {
                Configuration.Settings.General.SmallDelayMilliseconds = (int)(numericUpDownSecAdjust1.Value * 1000);
            }

            private void NumericUpDownSecAdjust2ValueChanged(object sender, EventArgs e)
            {
                Configuration.Settings.General.LargeDelayMilliseconds = (int)(numericUpDownSecAdjust2.Value * 1000);
            }

            private void ToolStripMenuItemMakeEmptyFromCurrentClick(object sender, EventArgs e)
            {
                if (ContinueNewOrExit())
                {
                    bool isAlternateVisible = SubtitleListview1.IsAlternateTextColumnVisible;
                    _subtitleAlternate = new Subtitle(_subtitle);
                    _subtitleAlternateFileName = null;
                    int oldIndex = FirstSelectedIndex;
                    if (oldIndex < 0)
                        oldIndex = 0;

                    foreach (var p in _subtitle.Paragraphs)
                    {
                        if (Configuration.Settings.General.RemoveBlankLinesWhenOpening && string.IsNullOrEmpty(Configuration.Settings.Tools.NewEmptyTranslationText))
                            p.Text = "-";
                        else if (Configuration.Settings.Tools.NewEmptyTranslationText != null)
                            p.Text = Configuration.Settings.Tools.NewEmptyTranslationText;
                        else
                            p.Text = string.Empty;
                    }
                    SubtitleListview1.ShowAlternateTextColumn(_languageGeneral.OriginalText);
                    _subtitleListViewIndex = -1;
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    SubtitleListview1.SelectIndexAndEnsureVisible(oldIndex);
                    textBoxListViewText.Focus();
                    Configuration.Settings.General.ShowOriginalAsPreviewIfAvailable = true;

                    _subtitleAlternateFileName = _fileName;
                    _fileName = null;
                    SetupAlternateEdit();
                    ResetHistory();

                    if (!isAlternateVisible || toolStripMenuItemShowOriginalInPreview.Checked)
                    {
                        toolStripMenuItemShowOriginalInPreview.Checked = false;
                        Configuration.Settings.General.ShowOriginalAsPreviewIfAvailable = false;
                        audioVisualizer.Invalidate();
                    }
                }
            }

            private void ToolStripMenuItemShowOriginalInPreviewClick(object sender, EventArgs e)
            {
                toolStripMenuItemShowOriginalInPreview.Checked = !toolStripMenuItemShowOriginalInPreview.Checked;
                Configuration.Settings.General.ShowOriginalAsPreviewIfAvailable = toolStripMenuItemShowOriginalInPreview.Checked;
            }

            private void ToolStripMenuItemVideoDropDownClosed(object sender, EventArgs e)
            {
                redockVideoControlsToolStripMenuItem.ShortcutKeys = Keys.None;
                undockVideoControlsToolStripMenuItem.ShortcutKeys = Keys.None;
            }

            private void ToolsToolStripMenuItemDropDownOpening(object sender, EventArgs e)
            {
                if (_subtitle?.Paragraphs.Count > 0 && _networkSession == null)
                {
                    toolStripSeparator23.Visible = true;
                    toolStripMenuItemMakeEmptyFromCurrent.Visible = !SubtitleListview1.IsAlternateTextColumnVisible;
                    toolStripMenuItemShowOriginalInPreview.Checked = Configuration.Settings.General.ShowOriginalAsPreviewIfAvailable;
                }
                else
                {
                    toolStripSeparator23.Visible = false;
                    toolStripMenuItemMakeEmptyFromCurrent.Visible = false;
                    toolStripMenuItemShowOriginalInPreview.Checked = false;
                }
                var f = GetCurrentSubtitleFormat();
                styleToolStripMenuItem.Visible = f.HasStyleSupport;
                var formatType = f.GetType();
                actorToolStripMenuItem.Visible = formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha);
            }

            private void ContextMenuStripWaveformOpening(object sender, System.ComponentModel.CancelEventArgs e)
            {
                if (audioVisualizer.IsSpectrogramAvailable)
                {
                    if (audioVisualizer.ShowSpectrogram && audioVisualizer.ShowWaveform)
                    {
                        showWaveformAndSpectrogramToolStripMenuItem.Visible = false;
                        showOnlyWaveformToolStripMenuItem.Visible = true;
                        showOnlySpectrogramToolStripMenuItem.Visible = true;
                        toolStripSeparatorGuessTimeCodes.Visible = true;
                    }
                    else if (audioVisualizer.ShowSpectrogram)
                    {
                        showWaveformAndSpectrogramToolStripMenuItem.Visible = true;
                        showOnlyWaveformToolStripMenuItem.Visible = true;
                        showOnlySpectrogramToolStripMenuItem.Visible = false;
                        toolStripSeparatorGuessTimeCodes.Visible = true;
                    }
                    else
                    {
                        showWaveformAndSpectrogramToolStripMenuItem.Visible = true;
                        showOnlyWaveformToolStripMenuItem.Visible = false;
                        showOnlySpectrogramToolStripMenuItem.Visible = true;
                        toolStripSeparatorGuessTimeCodes.Visible = true;
                    }
                }
                else
                {
                    toolStripSeparator24.Visible = false;
                    showWaveformAndSpectrogramToolStripMenuItem.Visible = false;
                    showOnlyWaveformToolStripMenuItem.Visible = false;
                    showOnlySpectrogramToolStripMenuItem.Visible = false;
                    toolStripSeparatorGuessTimeCodes.Visible = false;
                }
                insertSubtitleHereToolStripMenuItem.Visible = !_subtitle.Paragraphs.Any(p => p.StartTime.TotalSeconds <= mediaPlayer.CurrentPosition + 1.0 &&
                                                                                             p.EndTime.TotalSeconds <= mediaPlayer.CurrentPosition + 1.0 &&
                                                                                             p.EndTime.TotalSeconds >= mediaPlayer.CurrentPosition);
            }

            private void ShowWaveformAndSpectrogramToolStripMenuItemClick(object sender, EventArgs e)
            {
                audioVisualizer.ShowSpectrogram = true;
                audioVisualizer.ShowWaveform = true;
            }

            private void ShowOnlyWaveformToolStripMenuItemClick(object sender, EventArgs e)
            {
                audioVisualizer.ShowSpectrogram = false;
                audioVisualizer.ShowWaveform = true;
            }

            private void ShowOnlySpectrogramToolStripMenuItemClick(object sender, EventArgs e)
            {
                audioVisualizer.ShowSpectrogram = true;
                audioVisualizer.ShowWaveform = false;
            }

            private void SplitContainerMainSplitterMoved(object sender, SplitterEventArgs e)
            {
                mediaPlayer.Refresh();
            }

            private void FindDoubleLinesToolStripMenuItemClick(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }
                for (int i = FirstSelectedIndex + 1; i < _subtitle.Paragraphs.Count; i++)
                {
                    var current = _subtitle.GetParagraphOrDefault(i);
                    var next = _subtitle.GetParagraphOrDefault(i + 1);
                    if (current != null && next != null)
                    {
                        if (current.Text.Trim().Equals(next.Text.Trim(), StringComparison.OrdinalIgnoreCase))
                        {
                            SubtitleListview1.SelectIndexAndEnsureVisible(i);
                            SubtitleListview1.Items[i + 1].Selected = true;
                            break;
                        }
                    }
                }
            }

            private void TextBoxListViewTextAlternateMouseMove(object sender, MouseEventArgs e)
            {
                if (Control.ModifierKeys == Keys.Control && MouseButtons == MouseButtons.Left)
                {
                    if (!string.IsNullOrEmpty(textBoxListViewTextAlternate.SelectedText))
                        textBoxListViewTextAlternate.DoDragDrop(textBoxListViewTextAlternate.SelectedText, DragDropEffects.Copy);
                    else
                        textBoxListViewTextAlternate.DoDragDrop(textBoxListViewTextAlternate.Text, DragDropEffects.Copy);
                }
                else if ((AutoRepeatContinueOn || AutoRepeatOn) && !textBoxSearchWord.Focused && textBoxListViewTextAlternate.Focused)
                {
                    string selectedText = textBoxListViewTextAlternate.SelectedText;
                    if (!string.IsNullOrEmpty(selectedText))
                    {
                        selectedText = selectedText.Trim();
                        selectedText = selectedText.TrimEnd('.', ',', '!', '?').TrimEnd();
                        if (!string.IsNullOrEmpty(selectedText) && selectedText != textBoxSearchWord.Text)
                        {
                            textBoxSearchWord.Text = HtmlUtil.RemoveHtmlTags(selectedText);
                        }
                    }
                }
            }

            private void EBustlToolStripMenuItemClick(object sender, EventArgs e)
            {
                var ebu = new Ebu();
                saveFileDialog1.Filter = ebu.Name + "|*" + ebu.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + ebu.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(ebu.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += ebu.Extension;
                    }
                    new Ebu().Save(fileName, GetSaveSubtitle(_subtitle));
                }
            }

            private void ToolStripMenuItemCavena890Click(object sender, EventArgs e)
            {
                var cavena890 = new Cavena890();
                saveFileDialog1.Filter = cavena890.Name + "|*" + cavena890.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + cavena890.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(cavena890.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += cavena890.Extension;
                    }
                    using (var form = new Cavena890SaveOptions(_subtitle, _fileName))
                    {
                        if (form.ShowDialog(this) == DialogResult.OK)
                        {
                            cavena890.Save(fileName, GetSaveSubtitle(_subtitle));
                        }
                    }
                }
            }

            private void PacScreenElectronicsToolStripMenuItemClick(object sender, EventArgs e)
            {
                var pac = new Pac();
                saveFileDialog1.Filter = pac.Name + "|*" + pac.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + pac.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(pac.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += pac.Extension;
                    }
                    pac.Save(fileName, GetSaveSubtitle(_subtitle));
                }
            }

            private void uniPacExportToolStripMenuItem_Click(object sender, EventArgs e)
            {
                var uniPac = new PacUnicode();
                saveFileDialog1.Filter = uniPac.Name + "|*" + uniPac.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + uniPac.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(uniPac.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += uniPac.Extension;
                    }
                    uniPac.Save(fileName, GetSaveSubtitle(_subtitle));
                }
            }

            private void toolStripMenuItemExportAyato_Click(object sender, EventArgs e)
            {
                var ayato = new Ayato();
                saveFileDialog1.Filter = ayato.Name + "|*" + ayato.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + ayato.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(ayato.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += ayato.Extension;
                    }
                    ayato.Save(fileName, _videoFileName, GetSaveSubtitle(_subtitle));
                }
            }

            private void TextBoxListViewTextEnter(object sender, EventArgs e)
            {
                if (_findHelper != null)
                    _findHelper.MatchInOriginal = false;
            }

            private void TextBoxListViewTextAlternateEnter(object sender, EventArgs e)
            {
                if (_findHelper != null)
                    _findHelper.MatchInOriginal = true;
            }

            private void PlainTextToolStripMenuItemClick(object sender, EventArgs e)
            {
                using (var exportText = new ExportText())
                {
                    exportText.Initialize(GetSaveSubtitle(_subtitle), _fileName);
                    if (exportText.ShowDialog() == DialogResult.OK)
                    {
                        ShowStatus(_language.SubtitleExported);
                    }
                }
            }

            private void BluraySupToolStripMenuItemClick(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.BluraySup, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void VobSubsubidxToolStripMenuItemClick(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.VobSub, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void TextBoxListViewTextAlternateKeyUp(object sender, KeyEventArgs e)
            {
                textBoxListViewTextAlternate.ClearUndo();
                UpdatePositionAndTotalLength(labelTextAlternateLineTotal, textBoxListViewTextAlternate);
            }

            private void TimerTextUndoTick(object sender, EventArgs e)
            {
                // progress check
                ShowTranslationProgress();

                // text undo
                int index = _listViewTextUndoIndex;
                if (_listViewTextTicks == -1 || !CanFocus || _subtitle == null || _subtitle.Paragraphs.Count == 0 || index < 0 || index >= _subtitle.Paragraphs.Count)
                    return;

                if ((DateTime.UtcNow.Ticks - _listViewTextTicks) > 10000 * 700) // only if last typed char was entered > 700 milliseconds
                {
                    if (index < 0 || index >= _subtitle.Paragraphs.Count)
                        return;
                    string newText = _subtitle.Paragraphs[index].Text.TrimEnd();
                    string oldText = _listViewTextUndoLast;
                    if (oldText == null)
                        return;

                    if (_listViewTextUndoLast != newText)
                    {
                        MakeHistoryForUndo(_languageGeneral.Text + ": " + _listViewTextUndoLast.TrimEnd() + " -> " + newText, false);
                        int hidx = _subtitle.HistoryItems.Count - 1;
                        if (hidx >= 0 && hidx < _subtitle.HistoryItems.Count)
                            _subtitle.HistoryItems[hidx].Subtitle.Paragraphs[index].Text = _listViewTextUndoLast;

                        _listViewTextUndoLast = newText;
                        _listViewTextUndoIndex = -1;
                    }
                }
            }

            private void ShowTranslationProgress()
            {
                if (Configuration.Settings.General.ShowProgress)
                {
                    if (_subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                    {
                        int numberOfNonBlankLines = 0;
                        foreach (var paragraph in _subtitle.Paragraphs)
                        {
                            if (!string.IsNullOrWhiteSpace(paragraph.Text))
                                numberOfNonBlankLines++;
                        }
                        int percent = (int)Math.Round(numberOfNonBlankLines * 100.0 / _subtitle.Paragraphs.Count);
                        toolStripStatusLabelProgress.Text = string.Format("{0}% completed", percent);
                        if (!toolStripStatusLabelProgress.Visible)
                            toolStripStatusLabelProgress.Visible = true;
                    }
                    else if (_subtitle.Paragraphs.Count > 0 && !string.IsNullOrWhiteSpace(_videoFileName) && mediaPlayer != null && mediaPlayer.VideoPlayer != null && mediaPlayer.VideoPlayer.Duration > 0)
                    {
                        var last = _subtitle.Paragraphs.LastOrDefault();
                        if (last != null)
                        {
                            var subtitleEndSeconds = last.EndTime.TotalSeconds;
                            var videoEndSeconds = mediaPlayer.VideoPlayer.Duration;
                            int percent = (int)Math.Round(subtitleEndSeconds * 100.0 / videoEndSeconds);
                            toolStripStatusLabelProgress.Text = string.Format("{0}% completed", percent);
                            if (!toolStripStatusLabelProgress.Visible)
                                toolStripStatusLabelProgress.Visible = true;
                        }
                    }
                    else
                    {
                        toolStripStatusLabelProgress.Visible = false;
                    }
                }
            }

            private void TimerAlternateTextUndoTick(object sender, EventArgs e)
            {
                if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                {
                    int index = _listViewTextUndoIndex;
                    if (_listViewAlternateTextTicks == -1 || !CanFocus || _subtitleAlternate == null || _subtitleAlternate.Paragraphs.Count == 0 || index < 0 || index >= _subtitleAlternate.Paragraphs.Count)
                        return;

                    if ((DateTime.UtcNow.Ticks - _listViewAlternateTextTicks) > 10000 * 700) // only if last typed char was entered > 700 milliseconds
                    {
                        var original = Utilities.GetOriginalParagraph(index, _subtitle.Paragraphs[index], _subtitleAlternate.Paragraphs);
                        if (original != null)
                            index = _subtitleAlternate.Paragraphs.IndexOf(original);
                        else
                            return;

                        string newText = _subtitleAlternate.Paragraphs[index].Text.TrimEnd();
                        string oldText = _listViewAlternateTextUndoLast;
                        if (oldText == null)
                            return;

                        if (_listViewAlternateTextUndoLast != newText)
                        {
                            MakeHistoryForUndo(_languageGeneral.Text + ": " + _listViewAlternateTextUndoLast.TrimEnd() + " -> " + newText, false);
                            _subtitle.HistoryItems[_subtitle.HistoryItems.Count - 1].OriginalSubtitle.Paragraphs[index].Text = _listViewAlternateTextUndoLast;

                            _listViewAlternateTextUndoLast = newText;
                            _listViewTextUndoIndex = -1;
                        }
                    }
                }
            }

            private void UpdatePositionAndTotalLength(Label lineTotal, TextBox textBox)
            {
                if (string.IsNullOrEmpty(textBox.Text))
                {
                    lineTotal.Text = string.Empty;
                    return;
                }

                int extraNewLineLength = Environment.NewLine.Length - 1;
                int lineBreakPos = textBox.Text.IndexOf(Environment.NewLine, StringComparison.Ordinal);
                int pos = textBox.SelectionStart;
                var s = HtmlUtil.RemoveHtmlTags(textBox.Text, true).Replace(Environment.NewLine, string.Empty); // we don't count new line in total length... correct?
                int totalLength = s.Length;
                string totalL = "     " + string.Format(_languageGeneral.TotalLengthX, totalLength);
                if (lineBreakPos < 0 || pos <= lineBreakPos)
                {
                    lineTotal.Text = "1," + (pos + 1) + totalL;
                    lineTotal.Left = textBox.Left + (textBox.Width - lineTotal.Width);
                    return;
                }
                int secondLineBreakPos = textBox.Text.IndexOf(Environment.NewLine, lineBreakPos + 1, StringComparison.Ordinal);
                if (secondLineBreakPos < 0 || pos <= secondLineBreakPos + extraNewLineLength)
                {
                    lineTotal.Text = "2," + (pos - (lineBreakPos + extraNewLineLength)) + totalL;
                    lineTotal.Left = textBox.Left + (textBox.Width - lineTotal.Width);
                    return;
                }
                int thirdLineBreakPos = textBox.Text.IndexOf(Environment.NewLine, secondLineBreakPos + 1, StringComparison.Ordinal);
                if (thirdLineBreakPos < 0 || pos < thirdLineBreakPos + (extraNewLineLength * 2))
                {
                    lineTotal.Text = "3," + (pos - (secondLineBreakPos + extraNewLineLength)) + totalL;
                    lineTotal.Left = textBox.Left + (textBox.Width - lineTotal.Width);
                    return;
                }
                int forthLineBreakPos = textBox.Text.IndexOf(Environment.NewLine, thirdLineBreakPos + 1, StringComparison.Ordinal);
                if (forthLineBreakPos < 0 || pos < forthLineBreakPos + (extraNewLineLength * 3))
                {
                    lineTotal.Text = "4," + (pos - (thirdLineBreakPos + extraNewLineLength)) + totalL;
                    lineTotal.Left = textBox.Left + (textBox.Width - lineTotal.Width);
                    return;
                }
                lineTotal.Text = string.Empty;
            }

            private void TextBoxListViewTextMouseClick(object sender, MouseEventArgs e)
            {
                UpdatePositionAndTotalLength(labelTextLineTotal, textBoxListViewText);
            }

            private void TextBoxListViewTextAlternateMouseClick(object sender, MouseEventArgs e)
            {
                UpdatePositionAndTotalLength(labelTextAlternateLineTotal, textBoxListViewTextAlternate);
            }

            private void TabControlButtonsDrawItem(object sender, DrawItemEventArgs e)
            {
                var tc = (TabControl)sender;
                var textBrush = new SolidBrush(ForeColor);
                var tabFont = new Font(tc.Font, FontStyle.Regular);
                if (e.State == DrawItemState.Selected)
                {
                    tabFont = new Font(tc.Font, FontStyle.Bold);
                    e.Graphics.FillRectangle(new SolidBrush(SystemColors.Window), e.Bounds);
                }
                Rectangle tabBounds = tc.GetTabRect(e.Index);
                var stringFlags = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
                e.Graphics.DrawString(tc.TabPages[e.Index].Text.Trim(), tabFont, textBrush, tabBounds, new StringFormat(stringFlags));
            }

            public void GotoNextSubPosFromVideoPos()
            {
                if (mediaPlayer.VideoPlayer != null && _subtitle != null)
                {
                    double ms = mediaPlayer.VideoPlayer.CurrentPosition * TimeCode.BaseUnit;
                    foreach (var p in _subtitle.Paragraphs)
                    {
                        if (p.EndTime.TotalMilliseconds > ms && p.StartTime.TotalMilliseconds < ms)
                        {
                            // current sub
                        }
                        else if (p.Duration.TotalSeconds < 10 && p.StartTime.TotalMilliseconds > ms)
                        {
                            mediaPlayer.VideoPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                            SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.GetIndex(p));
                            return;
                        }
                    }
                }
            }

            public void GotoPrevSubPosFromvideoPos()
            {
                if (mediaPlayer.VideoPlayer != null && _subtitle != null)
                {
                    double ms = mediaPlayer.VideoPlayer.CurrentPosition * TimeCode.BaseUnit;
                    int i = _subtitle.Paragraphs.Count - 1;
                    while (i > 0)
                    {
                        var p = _subtitle.Paragraphs[i];
                        if (p.EndTime.TotalMilliseconds > ms && p.StartTime.TotalMilliseconds < ms)
                        {
                            // current sub
                        }
                        else if (p.Duration.TotalSeconds < 10 && p.StartTime.TotalMilliseconds < ms)
                        {
                            mediaPlayer.VideoPlayer.CurrentPosition = p.StartTime.TotalSeconds;
                            SubtitleListview1.SelectIndexAndEnsureVisible(_subtitle.GetIndex(p));
                            return;
                        }
                        i--;
                    }
                }
            }

            private void AdobeEncoreFabImageScriptToolStripMenuItemClick(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.Fab, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void ToolStripMenuItemMergeDialogClick(object sender, EventArgs e)
            {
                MergeDialogs();
            }

            private void MainKeyUp(object sender, KeyEventArgs e)
            {
                if (_mainCreateStartDownEndUpParagraph != null)
                {
                    var p = _subtitle.Paragraphs[_subtitleListViewIndex];
                    if (p.ToString() == _mainCreateStartDownEndUpParagraph.ToString())
                        ButtonSetEndClick(null, null);
                    _mainCreateStartDownEndUpParagraph = null;
                }
                else if (_mainAdjustStartDownEndUpAndGoToNextParagraph != null)
                {
                    var p = _subtitle.Paragraphs[_subtitleListViewIndex];
                    if (p.ToString() == _mainAdjustStartDownEndUpAndGoToNextParagraph.ToString())
                    {
                        double videoPositionInSeconds = mediaPlayer.CurrentPosition;
                        if (p.StartTime.TotalSeconds + 0.1 < videoPositionInSeconds)
                            ButtonSetEndClick(null, null);
                        SubtitleListview1.SelectIndexAndEnsureVisible(_subtitleListViewIndex + 1);
                    }
                    _mainAdjustStartDownEndUpAndGoToNextParagraph = null;
                }
            }

            private void ToolStripMenuItemSurroundWithMusicSymbolsClick(object sender, EventArgs e)
            {
                const string tag = "♪";
                if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                {
                    SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                    MakeHistoryForUndo(string.Format(_language.BeforeAddingTagX, tag));

                    var indices = new List<int>();
                    foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                        indices.Add(item.Index);

                    SubtitleListview1.BeginUpdate();
                    foreach (int i in indices)
                    {
                        if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                        {
                            var original = Utilities.GetOriginalParagraph(i, _subtitle.Paragraphs[i], _subtitleAlternate.Paragraphs);
                            if (original != null)
                            {
                                if (original.Text.Contains(tag))
                                {
                                    original.Text = original.Text.Replace(tag, string.Empty);
                                    original.Text = original.Text.Replace(Environment.NewLine + " ", Environment.NewLine).Replace(" " + Environment.NewLine, Environment.NewLine).Trim();
                                }
                                else
                                {
                                    if (Configuration.Settings.Tools.MusicSymbolStyle.Equals("single", StringComparison.OrdinalIgnoreCase))
                                        original.Text = string.Format("{0} {1}", tag, original.Text.Replace(Environment.NewLine, Environment.NewLine + tag + " "));
                                    else
                                        original.Text = string.Format("{0} {1} {0}", tag, original.Text.Replace(Environment.NewLine, " " + tag + Environment.NewLine + tag + " "));
                                }
                                SubtitleListview1.SetAlternateText(i, original.Text);
                            }
                        }

                        if (_subtitle.Paragraphs[i].Text.Contains(tag))
                        {
                            _subtitle.Paragraphs[i].Text = _subtitle.Paragraphs[i].Text.Replace("♪", string.Empty).Replace(Environment.NewLine + " ", Environment.NewLine).Replace(" " + Environment.NewLine, Environment.NewLine).Trim();
                        }
                        else
                        {
                            if (Configuration.Settings.Tools.MusicSymbolStyle.Equals("single", StringComparison.OrdinalIgnoreCase))
                                _subtitle.Paragraphs[i].Text = string.Format("{0} {1}", tag, _subtitle.Paragraphs[i].Text.Replace(Environment.NewLine, Environment.NewLine + tag + " "));
                            else
                                _subtitle.Paragraphs[i].Text = string.Format("{0} {1} {0}", tag, _subtitle.Paragraphs[i].Text.Replace(Environment.NewLine, " " + tag + Environment.NewLine + tag + " "));
                        }
                        SubtitleListview1.SetText(i, _subtitle.Paragraphs[i].Text);
                    }
                    SubtitleListview1.EndUpdate();

                    ShowStatus(string.Format(_language.TagXAdded, tag));
                    ShowSource();
                    RefreshSelectedParagraph();
                    SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                }
            }

            private void SuperscriptToolStripMenuItemClick(object sender, EventArgs e)
            {
                var tb = GetFocusedTextBox();

                string text = tb.SelectedText;
                int selectionStart = tb.SelectionStart;
                text = Utilities.ToSuperscript(text);
                tb.SelectedText = text;
                tb.SelectionStart = selectionStart;
                tb.SelectionLength = text.Length;
            }

            private void SubscriptToolStripMenuItemClick(object sender, EventArgs e)
            {
                var tb = GetFocusedTextBox();

                string text = tb.SelectedText;
                int selectionStart = tb.SelectionStart;
                text = Utilities.ToSubscript(text);
                tb.SelectedText = text;
                tb.SelectionStart = selectionStart;
                tb.SelectionLength = text.Length;
            }

            private void ToolStripMenuItemImagePerFrameClick(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.ImageFrame, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void toolStripMenuItemApplyDisplayTimeLimits_Click(object sender, EventArgs e)
            {
                ApplyDisplayTimeLimits(false);
            }

            private void ApplyDisplayTimeLimits(bool onlySelectedLines)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var applyDurationLimits = new ApplyDurationLimits())
                {
                    if (onlySelectedLines)
                    {
                        var selectedLines = new Subtitle { WasLoadedWithFrameNumbers = _subtitle.WasLoadedWithFrameNumbers };
                        foreach (int index in SubtitleListview1.SelectedIndices)
                            selectedLines.Paragraphs.Add(_subtitle.Paragraphs[index]);
                        applyDurationLimits.Initialize(selectedLines);
                    }
                    else
                    {
                        applyDurationLimits.Initialize(_subtitle);
                    }

                    applyDurationLimits.Initialize(_subtitle);
                    if (applyDurationLimits.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeDisplayTimeAdjustment);

                        if (onlySelectedLines)
                        { // we only update selected lines
                            int i = 0;
                            foreach (int index in SubtitleListview1.SelectedIndices)
                            {
                                _subtitle.Paragraphs[index] = applyDurationLimits.FixedSubtitle.Paragraphs[i];
                                i++;
                            }
                            ShowStatus(_language.VisualSyncPerformedOnSelectedLines);
                            SubtitleListview1.SyntaxColorAllLines(_subtitle);
                        }
                        else
                        {
                            SaveSubtitleListviewIndices();
                            _subtitle.Paragraphs.Clear();
                            foreach (var p in applyDurationLimits.FixedSubtitle.Paragraphs)
                                _subtitle.Paragraphs.Add(new Paragraph(p));
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            RestoreSubtitleListviewIndices();
                        }

                        if (IsFramesRelevant && CurrentFrameRate > 0)
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        ShowSource();
                    }
                }
            }

            private void generateDatetimeInfoFromVideoToolStripMenuItem_Click(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                using (var extractDateTimeInfo = new ExtractDateTimeInfo())
                {
                    if (extractDateTimeInfo.ShowDialog(this) == DialogResult.OK)
                    {
                        if (ContinueNewOrExit())
                        {
                            MakeHistoryForUndo(_language.BeforeDisplayTimeAdjustment);

                            ResetSubtitle();
                            _subtitle.Paragraphs.Clear();
                            foreach (var p in extractDateTimeInfo.DateTimeSubtitle.Paragraphs)
                                _subtitle.Paragraphs.Add(new Paragraph(p));
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            SubtitleListview1.SelectIndexAndEnsureVisible(0);

                            if (IsFramesRelevant && CurrentFrameRate > 0)
                                _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                            ShowSource();

                            OpenVideo(extractDateTimeInfo.VideoFileName);
                        }
                    }
                }
            }

            private void ToolStripMenuItemRightToLeftModeClick(object sender, EventArgs e)
            {
                var focusedItem = SubtitleListview1.FocusedItem;
                toolStripMenuItemRightToLeftMode.Checked = !toolStripMenuItemRightToLeftMode.Checked;
                if (!toolStripMenuItemRightToLeftMode.Checked)
                {
                    RightToLeft = RightToLeft.No;
                    textBoxListViewText.RightToLeft = RightToLeft.No;
                    textBoxListViewTextAlternate.RightToLeft = RightToLeft.No;
                    SubtitleListview1.RightToLeft = RightToLeft.No;
                    SubtitleListview1.RightToLeftLayout = false;
                    textBoxSource.RightToLeft = RightToLeft.No;
                    mediaPlayer.TextRightToLeft = RightToLeft.No;
                    textBoxSearchWord.RightToLeft = RightToLeft.No;
                    Configuration.Settings.General.RightToLeftMode = false;
                }
                else
                {
                    //RightToLeft = RightToLeft.Yes; - is this better? TimeUpDown custom control needs to support RTL before enabling this
                    textBoxListViewText.RightToLeft = RightToLeft.Yes;
                    textBoxListViewTextAlternate.RightToLeft = RightToLeft.Yes;
                    SubtitleListview1.RightToLeft = RightToLeft.Yes;
                    SubtitleListview1.RightToLeftLayout = true;
                    textBoxSource.RightToLeft = RightToLeft.Yes;
                    mediaPlayer.TextRightToLeft = RightToLeft.Yes;
                    textBoxSearchWord.RightToLeft = RightToLeft.Yes;
                    Configuration.Settings.General.RightToLeftMode = true;
                }
                MainResize();
                TextBoxListViewTextTextChanged(null, null);
                textBoxListViewTextAlternate_TextChanged(null, null);
                if (focusedItem != null)
                {
                    SubtitleListview1.SelectIndexAndEnsureVisible(focusedItem.Index, true);
                }
            }

            private void joinSubtitlesToolStripMenuItem_Click(object sender, EventArgs e)
            {
                ReloadFromSourceView();
                using (var joinSubtitles = new JoinSubtitles())
                {
                    if (joinSubtitles.ShowDialog(this) == DialogResult.OK && joinSubtitles.JoinedSubtitle != null && joinSubtitles.JoinedSubtitle.Paragraphs.Count > 0 && ContinueNewOrExit())
                    {
                        MakeHistoryForUndo(_language.BeforeDisplaySubtitleJoin);

                        ResetSubtitle();
                        _subtitle = joinSubtitles.JoinedSubtitle;
                        SetCurrentFormat(joinSubtitles.JoinedFormat);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        SubtitleListview1.SelectIndexAndEnsureVisible(0);

                        if (IsFramesRelevant && CurrentFrameRate > 0)
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        ShowSource();

                        ShowStatus(_language.SubtitlesJoined);
                    }
                }
            }

            private void toolStripMenuItemReverseRightToLeftStartEnd_Click(object sender, EventArgs e)
            {
                ReverseStartAndEndingForRtl();
            }

            private void toolStripMenuItemExportCapMakerPlus_Click(object sender, EventArgs e)
            {
                var capMakerPlus = new CapMakerPlus();
                saveFileDialog1.Filter = capMakerPlus.Name + "|*" + capMakerPlus.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + capMakerPlus.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(capMakerPlus.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += capMakerPlus.Extension;
                    }
                    CapMakerPlus.Save(fileName, GetSaveSubtitle(_subtitle));
                }
            }

            private void toolStripMenuItemExportCheetahCap_Click(object sender, EventArgs e)
            {
                var cheetahCaption = new CheetahCaption();
                saveFileDialog1.Filter = cheetahCaption.Name + "|*" + cheetahCaption.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + cheetahCaption.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(cheetahCaption.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += cheetahCaption.Extension;
                    }
                    CheetahCaption.Save(fileName, GetSaveSubtitle(_subtitle));
                }
            }

            private void toolStripMenuItemExportCaptionInc_Click(object sender, EventArgs e)
            {
                var captionInc = new CaptionsInc();
                saveFileDialog1.Filter = captionInc.Name + "|*" + captionInc.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + captionInc.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(captionInc.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += captionInc.Extension;
                    }
                    CaptionsInc.Save(fileName, GetSaveSubtitle(_subtitle));
                }
            }

            private void toolStripMenuItemExportUltech130_Click(object sender, EventArgs e)
            {
                var ultech130 = new Ultech130();
                saveFileDialog1.Filter = ultech130.Name + "|*" + ultech130.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + ultech130.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(ultech130.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += ultech130.Extension;
                    }
                    Ultech130.Save(fileName, GetSaveSubtitle(_subtitle));
                }
            }

            private void toolStripMenuItemAssStyles_Click(object sender, EventArgs e)
            {
                StylesForm styles = null;
                try
                {
                    var format = GetCurrentSubtitleFormat();
                    var formatType = format.GetType();
                    if (formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha))
                    {
                        styles = new SubStationAlphaStyles(_subtitle, format);
                        if (styles.ShowDialog(this) == DialogResult.OK)
                        {
                            if (_subtitle.Header != styles.Header)
                            {
                                MakeHistoryForUndo(styles.Text);
                            }

                            _subtitle.Header = styles.Header;
                            var styleList = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header);
                            if (styleList.Count > 0)
                            {
                                for (var i = 0; i < _subtitle.Paragraphs.Count; i++)
                                {
                                    var p = _subtitle.Paragraphs[i];
                                    if (p.Extra == null || !styleList.Any(s => s.Equals(p.Extra == "*Default" ? "Default" : p.Extra, StringComparison.OrdinalIgnoreCase)))
                                    {
                                        p.Extra = styleList[0];
                                        SubtitleListview1.SetExtraText(i, p.Extra, SubtitleListview1.ForeColor);
                                    }
                                }
                            }
                        }
                    }
                    else if (formatType == typeof(TimedText10) || formatType == typeof(ItunesTimedText))
                    {
                        styles = new TimedTextStyles(_subtitle);
                        if (styles.ShowDialog(this) == DialogResult.OK)
                        {
                            if (_subtitle.Header != styles.Header)
                            {
                                MakeHistoryForUndo(styles.Text);
                            }
                            _subtitle.Header = styles.Header;
                        }
                    }
                }
                finally
                {
                    mediaPlayer.LastParagraph = null;
                    UiUtil.ShowSubtitle(_subtitle, mediaPlayer);
                    styles?.Dispose();
                }
            }

            private void toolStripMenuItemSubStationAlpha_Click(object sender, EventArgs e)
            {
                using (var properties = new SubStationAlphaProperties(_subtitle, GetCurrentSubtitleFormat(), _videoFileName, _fileName))
                {
                    properties.ShowDialog(this);
                }
            }

            private static void SetAlignTag(Paragraph p, string tag)
            {
                if (p.Text.StartsWith("{\\a", StringComparison.Ordinal) && p.Text.Length > 5 && p.Text[5] == '}')
                    p.Text = p.Text.Remove(0, 6);
                else if (p.Text.StartsWith("{\\a", StringComparison.Ordinal) && p.Text.Length > 4 && p.Text[4] == '}')
                    p.Text = p.Text.Remove(0, 5);
                p.Text = string.Format(@"{0}{1}", tag, p.Text);
            }

            private void toolStripMenuItemAlignment_Click(object sender, EventArgs e)
            {
                using (var f = new AlignmentPicker())
                {
                    f.TopMost = true;
                    f.StartPosition = FormStartPosition.Manual;
                    f.Left = Cursor.Position.X - 150;
                    f.Top = Cursor.Position.Y - 75;
                    if (f.ShowDialog(this) == DialogResult.OK)
                    {
                        string tag = string.Empty;
                        var format = GetCurrentSubtitleFormat();
                        if (format.GetType() == typeof(SubStationAlpha))
                        {
                            //1: Bottom left
                            //2: Bottom center
                            //3: Bottom right
                            //9: Middle left
                            //10: Middle center
                            //11: Middle right
                            //5: Top left
                            //6: Top center
                            //7: Top right
                            switch (f.Alignment)
                            {
                                case ContentAlignment.BottomLeft:
                                    tag = "{\\a1}";
                                    break;
                                case ContentAlignment.BottomCenter:
                                    tag = "{\\a2}";
                                    break;
                                case ContentAlignment.BottomRight:
                                    tag = "{\\a3}";
                                    break;
                                case ContentAlignment.MiddleLeft:
                                    tag = "{\\a9}";
                                    break;
                                case ContentAlignment.MiddleCenter:
                                    tag = "{\\a10}";
                                    break;
                                case ContentAlignment.MiddleRight:
                                    tag = "{\\a11}";
                                    break;
                                case ContentAlignment.TopLeft:
                                    tag = "{\\a5}";
                                    break;
                                case ContentAlignment.TopCenter:
                                    tag = "{\\a6}";
                                    break;
                                case ContentAlignment.TopRight:
                                    tag = "{\\a7}";
                                    break;
                            }
                        }
                        else
                        {
                            //1: Bottom left
                            //2: Bottom center
                            //3: Bottom right
                            //4: Middle left
                            //5: Middle center
                            //6: Middle right
                            //7: Top left
                            //8: Top center
                            //9: Top right
                            switch (f.Alignment)
                            {
                                case ContentAlignment.BottomLeft:
                                    tag = "{\\an1}";
                                    break;
                                case ContentAlignment.BottomCenter:
                                    if (format.GetType() == typeof(SubRip))
                                        tag = string.Empty;
                                    else
                                        tag = "{\\an2}";
                                    break;
                                case ContentAlignment.BottomRight:
                                    tag = "{\\an3}";
                                    break;
                                case ContentAlignment.MiddleLeft:
                                    tag = "{\\an4}";
                                    break;
                                case ContentAlignment.MiddleCenter:
                                    tag = "{\\an5}";
                                    break;
                                case ContentAlignment.MiddleRight:
                                    tag = "{\\an6}";
                                    break;
                                case ContentAlignment.TopLeft:
                                    tag = "{\\an7}";
                                    break;
                                case ContentAlignment.TopCenter:
                                    tag = "{\\an8}";
                                    break;
                                case ContentAlignment.TopRight:
                                    tag = "{\\an9}";
                                    break;
                            }
                        }
                        if (_subtitle.Paragraphs.Count > 0 && SubtitleListview1.SelectedItems.Count > 0)
                        {
                            SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                            MakeHistoryForUndo(string.Format(_language.BeforeAddingTagX, tag));

                            var indices = new List<int>();
                            foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                                indices.Add(item.Index);

                            SubtitleListview1.BeginUpdate();
                            foreach (int i in indices)
                            {
                                if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle)
                                {
                                    var original = Utilities.GetOriginalParagraph(i, _subtitle.Paragraphs[i], _subtitleAlternate.Paragraphs);
                                    if (original != null)
                                    {
                                        SetAlignTag(original, tag);
                                        SubtitleListview1.SetAlternateText(i, original.Text);
                                    }
                                }
                                SetAlignTag(_subtitle.Paragraphs[i], tag);
                                SubtitleListview1.SetText(i, _subtitle.Paragraphs[i].Text);
                            }
                            SubtitleListview1.EndUpdate();

                            ShowStatus(string.Format(_language.TagXAdded, tag));
                            ShowSource();
                            RefreshSelectedParagraph();
                            SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                        }
                    }
                }
            }

            private void toolStripMenuItemRestoreAutoBackup_Click(object sender, EventArgs e)
            {
                _lastDoNotPrompt = string.Empty;
                using (var restoreAutoBackup = new RestoreAutoBackup())
                {
                    if (restoreAutoBackup.ShowDialog(this) == DialogResult.OK && !string.IsNullOrEmpty(restoreAutoBackup.AutoBackupFileName))
                    {
                        if (ContinueNewOrExit())
                        {
                            OpenSubtitle(restoreAutoBackup.AutoBackupFileName, null);
                            _fileName = _fileName.Remove(0, Configuration.AutoBackupDirectory.Length).TrimStart(Path.DirectorySeparatorChar);
                            _converted = true;
                            SetTitle();
                        }
                    }
                }
            }

            private void labelStatus_Click(object sender, EventArgs e)
            {
                if (_statusLog.Count == 0)
                {
                    return;
                }

                if (_statusLogForm == null || _statusLogForm.IsDisposed)
                {
                    _statusLogForm = new StatusLog(_statusLog);
                    _statusLogForm.Show(this);
                }
                else
                {
                    _statusLogForm.Show();
                }
            }

            private void toolStripMenuItemStatistics_Click(object sender, EventArgs e)
            {
                using (var stats = new Statistics(_subtitle, _fileName, GetCurrentSubtitleFormat()))
                {
                    stats.ShowDialog(this);
                }
            }

            private void toolStripMenuItemDCinemaProperties_Click(object sender, EventArgs e)
            {
                PositionAndSizeForm properties = null;
                try
                {
                    if (GetCurrentSubtitleFormat().GetType() == typeof(DCSubtitle))
                    {
                        properties = new DCinema.DCinemaPropertiesInterop();
                    }
                    else
                    {
                        properties = new DCinema.DCinemaPropertiesSmpte();
                    }
                    properties.ShowDialog(this);
                }
                finally
                {
                    properties?.Dispose();
                }
            }

            private void toolStripMenuItemTextTimeCodePair_Click(object sender, EventArgs e)
            {
                if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    saveFileDialog1.Filter = _language.TextFiles + "|*.txt";
                    saveFileDialog1.Title = _language.SaveSubtitleAs;
                    saveFileDialog1.DefaultExt = "*.txt";
                    saveFileDialog1.AddExtension = true;

                    string fname = saveFileDialog1.FileName;
                    if (string.IsNullOrEmpty(fname))
                        fname = "ATS";
                    if (!fname.EndsWith(".txt", StringComparison.Ordinal))
                        fname += ".txt";
                    string fileNameTimeCode = fname.Insert(fname.Length - 4, "_timecode");
                    string fileNameText = fname.Insert(fname.Length - 4, "_text");

                    var timeCodeLines = new StringBuilder();
                    var textLines = new StringBuilder();

                    const string timeCodeWriteFormat = "{0:00}:{1:00}:{2:00}:{3:00}";
                    foreach (var p in GetSaveSubtitle(_subtitle).Paragraphs)
                    {
                        timeCodeLines.AppendLine(string.Format(timeCodeWriteFormat, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, SubtitleFormat.MillisecondsToFramesMaxFrameRate(p.StartTime.Milliseconds)));
                        timeCodeLines.AppendLine(string.Format(timeCodeWriteFormat, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, SubtitleFormat.MillisecondsToFramesMaxFrameRate(p.EndTime.Milliseconds)));

                        textLines.AppendLine(HtmlUtil.RemoveHtmlTags(p.Text).Replace(Environment.NewLine, "|"));
                        textLines.AppendLine();
                    }

                    File.WriteAllText(fileNameTimeCode, timeCodeLines.ToString(), Encoding.UTF8);
                    File.WriteAllText(fileNameText, textLines.ToString(), Encoding.UTF8);
                }
            }

            private void textWordsPerMinutewpmToolStripMenuItem_Click(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.WordsPerMinute, (sender as ToolStripItem).Text);
            }

            private void toolStripMenuItemTTPropertiesClick(object sender, EventArgs e)
            {
                var subtitleFormatType = GetCurrentSubtitleFormat().GetType();
                if (subtitleFormatType != typeof(TimedText10) && subtitleFormatType != typeof(ItunesTimedText))
                {
                    return;
                }

                using (var properties = new TimedTextProperties(_subtitle))
                {
                    properties.ShowDialog(this);
                }
            }

            private void ToolStripMenuItemSaveSelectedLinesClick(object sender, EventArgs e)
            {
                var newSub = new Subtitle(_subtitle);
                newSub.Header = _subtitle.Header;
                newSub.Paragraphs.Clear();
                foreach (int index in SubtitleListview1.SelectedIndices)
                    newSub.Paragraphs.Add(_subtitle.Paragraphs[index]);

                SubtitleFormat currentFormat = GetCurrentSubtitleFormat();
                UiUtil.SetSaveDialogFilter(saveFileDialog1, currentFormat);
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + currentFormat.Extension;
                saveFileDialog1.AddExtension = true;
                if (!string.IsNullOrEmpty(_fileName))
                    saveFileDialog1.InitialDirectory = Path.GetDirectoryName(_fileName);

                if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    int index = 0;
                    foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
                    {
                        if (saveFileDialog1.FilterIndex == index + 1)
                        {
                            if (format.IsTextBased)
                            {
                                // only allow current extension or ".txt"
                                string fileName = saveFileDialog1.FileName;
                                string ext = Path.GetExtension(fileName).ToLowerInvariant();
                                bool extOk = ext.Equals(format.Extension, StringComparison.OrdinalIgnoreCase) || format.AlternateExtensions.Contains(ext) || ext == ".txt";
                                if (!extOk)
                                {
                                    if (fileName.EndsWith('.'))
                                        fileName = fileName.TrimEnd('.');
                                    fileName += format.Extension;
                                }

                                string allText = newSub.ToText(format);
                                File.WriteAllText(fileName, allText, GetCurrentEncoding());
                                ShowStatus(string.Format(_language.XLinesSavedAsY, newSub.Paragraphs.Count, fileName));
                                return;
                            }
                        }
                        index++;
                    }
                }
            }

            private void GuessTimeCodesToolStripMenuItemClick(object sender, EventArgs e)
            {
                using (var form = new WaveformGenerateTimeCodes())
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndoOnlyIfNotResent(string.Format(_language.BeforeGuessingTimeCodes));

                        double startFromSeconds = 0;
                        if (form.StartFromVideoPosition)
                            startFromSeconds = mediaPlayer.CurrentPosition;

                        if (form.DeleteAll)
                        {
                            _subtitle.Paragraphs.Clear();
                        }
                        else if (form.DeleteForward)
                        {
                            for (int i = _subtitle.Paragraphs.Count - 1; i > 0; i--)
                            {
                                if (_subtitle.Paragraphs[i].EndTime.TotalSeconds + 1 > startFromSeconds)
                                    _subtitle.Paragraphs.RemoveAt(i);
                            }
                        }
                        audioVisualizer.GenerateTimeCodes(_subtitle, startFromSeconds, form.BlockSize, form.VolumeMinimum, form.VolumeMaximum, form.DefaultMilliseconds);
                        if (IsFramesRelevant && CurrentFrameRate > 0)
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RefreshSelectedParagraph();
                    }
                }
            }

            private void DvdStudioProStl_Click(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), "STL", _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void toolStripMenuItemPlugins_Click(object sender, EventArgs e)
            {
                using (var form = new PluginsGet())
                {
                    form.ShowDialog(this);
                    LoadPlugins();
                }
            }

            private void toolStripMenuItemUndo_Click(object sender, EventArgs e)
            {
                UndoToIndex(true);
            }

            private void toolStripMenuItemRedo_Click(object sender, EventArgs e)
            {
                UndoToIndex(false);
            }

            private void seekSilenceToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (audioVisualizer == null)
                    return;

                using (var form = new SeekSilence())
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        if (form.SeekForward)
                        {
                            audioVisualizer.FindDataBelowThreshold(form.VolumeBelow, form.SecondsDuration);
                        }
                        else
                        {
                            audioVisualizer.FindDataBelowThresholdBack(form.VolumeBelow, form.SecondsDuration);
                        }
                    }
                }
            }

            private void toolStripMenuItemPasteSpecial_Click(object sender, EventArgs e)
            {
                string text = Clipboard.GetText();
                var tmp = new Subtitle();
                var format = new SubRip();
                var list = new List<string>(text.SplitToLines());
                format.LoadSubtitle(tmp, list, null);

                if (SubtitleListview1.SelectedItems.Count == 1 && text.Length > 0)
                {
                    var form = new ColumnPaste(SubtitleListview1.IsAlternateTextColumnVisible && _subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle, tmp.Paragraphs.Count == 0);
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeColumnPaste);

                        if (tmp.Paragraphs.Count == 0)
                        {
                            foreach (var line in text.SplitToLines())
                                tmp.Paragraphs.Add(new Paragraph(0, 0, line));
                        }

                        int index = FirstSelectedIndex;

                        if (!form.PasteOverwrite)
                        {
                            for (int i = 0; i < tmp.Paragraphs.Count; i++)
                            {
                                if (form.PasteAll)
                                {
                                    for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                                    {
                                        _subtitle.Paragraphs[k + 1] = new Paragraph(_subtitle.Paragraphs[k]);
                                    }
                                    if (index + i < _subtitle.Paragraphs.Count)
                                        _subtitle.Paragraphs[index + i].Text = string.Empty;
                                }
                                else if (form.PasteTimeCodesOnly)
                                {
                                    for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                                    {
                                        _subtitle.Paragraphs[k + 1].StartTime.TotalMilliseconds = _subtitle.Paragraphs[k].StartTime.TotalMilliseconds;
                                        _subtitle.Paragraphs[k + 1].EndTime.TotalMilliseconds = _subtitle.Paragraphs[k].EndTime.TotalMilliseconds;
                                        _subtitle.Paragraphs[k + 1].StartFrame = _subtitle.Paragraphs[k].StartFrame;
                                        _subtitle.Paragraphs[k + 1].EndFrame = _subtitle.Paragraphs[k].EndFrame;
                                    }
                                }
                                else if (form.PasteTextOnly)
                                {
                                    for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                                    {
                                        _subtitle.Paragraphs[k + 1].Text = _subtitle.Paragraphs[k].Text;
                                    }
                                }
                                else if (form.PasteOriginalTextOnly)
                                {
                                    for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                                    {
                                        var original = Utilities.GetOriginalParagraph(index, _subtitle.Paragraphs[k], _subtitleAlternate.Paragraphs);
                                        var originalNext = Utilities.GetOriginalParagraph(index, _subtitle.Paragraphs[k + 1], _subtitleAlternate.Paragraphs);
                                        if (original != null)
                                        {
                                            originalNext.Text = original.Text;
                                        }
                                    }
                                    if (index + i < _subtitle.Paragraphs.Count)
                                    {
                                        var original = Utilities.GetOriginalParagraph(index, _subtitle.Paragraphs[index + i], _subtitleAlternate.Paragraphs);
                                        if (original != null)
                                            original.Text = string.Empty;
                                    }
                                }
                            }
                        }
                        if (form.PasteOverwrite)
                        {
                            for (int i = 0; i + index < _subtitle.Paragraphs.Count && i < tmp.Paragraphs.Count; i++)
                                _subtitle.Paragraphs[index + i].Text = tmp.Paragraphs[i].Text;
                        }
                        else
                        {
                            for (int i = 0; i + index < _subtitle.Paragraphs.Count && i < tmp.Paragraphs.Count; i++)
                            {
                                if (index + i + 1 < _subtitle.Paragraphs.Count)
                                    _subtitle.Paragraphs[index + i + 1].Text = tmp.Paragraphs[i].Text;
                            }
                        }

                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                        RefreshSelectedParagraph();
                    }
                    form.Dispose();
                }
            }

            private void deleteAndShiftCellsUpToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedIndices.Count < 1)
                    return;

                int first = FirstSelectedIndex;
                List<int> list = new List<int>();
                foreach (int index in SubtitleListview1.SelectedIndices)
                    list.Add(index);
                list.Sort();
                list.Reverse();

                MakeHistoryForUndo(_language.BeforeColumnDelete);
                foreach (int index in list)
                {
                    for (int k = index; k < _subtitle.Paragraphs.Count - 1; k++)
                    {
                        _subtitle.Paragraphs[k].Text = _subtitle.Paragraphs[k + 1].Text;
                    }
                    _subtitle.Paragraphs[_subtitle.Paragraphs.Count - 1].Text = string.Empty;
                }
                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                SubtitleListview1.SelectIndexAndEnsureVisible(first, true);
                RefreshSelectedParagraph();
            }

            private void toolStripMenuItemColumnImportText_Click(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedIndices.Count < 1)
                    return;

                using (var importText = new ImportText())
                {
                    if (importText.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeColumnImportText);
                        int index = FirstSelectedIndex;
                        for (int i = 0; i < importText.FixedSubtitle.Paragraphs.Count; i++)
                        {
                            for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                            {
                                _subtitle.Paragraphs[k + 1].Text = _subtitle.Paragraphs[k].Text;
                            }
                            if (index + i < _subtitle.Paragraphs.Count)
                                _subtitle.Paragraphs[index + i].Text = string.Empty;
                        }

                        for (int i = 0; i + index < _subtitle.Paragraphs.Count && i < importText.FixedSubtitle.Paragraphs.Count; i++)
                            _subtitle.Paragraphs[index + i].Text = importText.FixedSubtitle.Paragraphs[i].Text;

                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                        RefreshSelectedParagraph();
                    }
                }
            }

            private void ShiftTextCellsDownToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedIndices.Count < 1)
                    return;

                int index = FirstSelectedIndex;
                int count = SubtitleListview1.SelectedIndices.Count;
                MakeHistoryForUndo(_language.BeforeColumnShiftCellsDown);
                for (int i = 0; i < count; i++)
                {
                    for (int k = _subtitle.Paragraphs.Count - 2; k >= index; k--)
                    {
                        _subtitle.Paragraphs[k + 1].Text = _subtitle.Paragraphs[k].Text;
                    }
                    if (index + i < _subtitle.Paragraphs.Count)
                        _subtitle.Paragraphs[index + i].Text = string.Empty;
                }

                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                RefreshSelectedParagraph();
            }

            private void toolStripMenuItemInsertTextFromSub_Click(object sender, EventArgs e)
            {
                openFileDialog1.Title = _languageGeneral.OpenSubtitle;
                openFileDialog1.FileName = string.Empty;
                openFileDialog1.Filter = UiUtil.SubtitleExtensionFilter.Value;
                if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    if (!File.Exists(openFileDialog1.FileName))
                        return;

                    var fi = new FileInfo(openFileDialog1.FileName);
                    if (fi.Length > 1024 * 1024 * 10) // max 10 mb
                    {
                        var text = string.Format(_language.FileXIsLargerThan10MB + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, openFileDialog1.FileName);
                        if (MessageBox.Show(this, text, Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                            return;
                    }

                    Encoding encoding;
                    var tmp = new Subtitle();
                    SubtitleFormat format = tmp.LoadSubtitle(openFileDialog1.FileName, out encoding, null);

                    if (format != null)
                    {
                        if (format.IsFrameBased)
                            tmp.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                        else
                            tmp.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                        if (Configuration.Settings.General.RemoveBlankLinesWhenOpening)
                            tmp.RemoveEmptyLines();

                        if (SubtitleListview1.SelectedIndices.Count < 1)
                            return;

                        MakeHistoryForUndo(_language.BeforeColumnShiftCellsDown);

                        int index = FirstSelectedIndex;
                        for (int i = 0; i < tmp.Paragraphs.Count; i++)
                        {
                            {
                                for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                                {
                                    _subtitle.Paragraphs[k + 1].Text = _subtitle.Paragraphs[k].Text;
                                }
                            }
                        }
                        for (int i = 0; i + index < _subtitle.Paragraphs.Count && i < tmp.Paragraphs.Count; i++)
                            _subtitle.Paragraphs[index + i].Text = tmp.Paragraphs[i].Text;
                        if (IsFramesRelevant && CurrentFrameRate > 0)
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                        RefreshSelectedParagraph();
                    }
                }
            }

            private void toolStripMenuItemOpenKeepVideo_Click(object sender, EventArgs e)
            {
                openToolStripMenuItem.Enabled = false;
                ReloadFromSourceView();
                _resetVideo = false;
                OpenNewFile();
                _resetVideo = true;
                openToolStripMenuItem.Enabled = true;
            }

            private void changeSpeedInPercentToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var form = new ChangeSpeedInPercent(SubtitleListview1.SelectedItems.Count))
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeAdjustSpeedInPercent);
                        SaveSubtitleListviewIndices();
                        if (form.AdjustAllLines)
                        {
                            _subtitle = form.AdjustAllParagraphs(_subtitle);
                            if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle && SubtitleListview1.IsAlternateTextColumnVisible)
                                _subtitleAlternate = form.AdjustAllParagraphs(_subtitleAlternate);
                        }
                        else
                        {
                            foreach (int index in SubtitleListview1.SelectedIndices)
                            {
                                var p = _subtitle.GetParagraphOrDefault(index);
                                if (p != null)
                                {
                                    form.AdjustParagraph(p);
                                    if (_subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle && SubtitleListview1.IsAlternateTextColumnVisible)
                                    {
                                        var original = Utilities.GetOriginalParagraph(index, p, _subtitle.Paragraphs);
                                        if (original != null)
                                            form.AdjustParagraph(original);
                                    }
                                }
                            }
                        }
                        if (IsFramesRelevant && CurrentFrameRate > 0)
                            _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void toolStripMenuItemAvidStl_Click(object sender, EventArgs e)
            {
                var avidStl = new AvidStl();
                saveFileDialog1.Filter = avidStl.Name + "|*" + avidStl.Extension;
                saveFileDialog1.Title = _language.SaveSubtitleAs;
                saveFileDialog1.DefaultExt = "*" + avidStl.Extension;
                saveFileDialog1.AddExtension = true;

                if (!string.IsNullOrEmpty(_videoFileName))
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_videoFileName);
                else
                    saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(_fileName);

                if (!string.IsNullOrEmpty(openFileDialog1.InitialDirectory))
                    saveFileDialog1.InitialDirectory = openFileDialog1.InitialDirectory;

                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    openFileDialog1.InitialDirectory = saveFileDialog1.InitialDirectory;
                    string fileName = saveFileDialog1.FileName;
                    string ext = Path.GetExtension(fileName);
                    bool extOk = ext.Equals(avidStl.Extension, StringComparison.OrdinalIgnoreCase);
                    if (!extOk)
                    {
                        if (fileName.EndsWith('.'))
                            fileName = fileName.Substring(0, fileName.Length - 1);
                        fileName += avidStl.Extension;
                    }

                    AvidStl.Save(fileName, GetSaveSubtitle(_subtitle));
                }
            }

            private Subtitle GetSaveSubtitle(Subtitle subtitle)
            {
                var sub = new Subtitle(subtitle);
                if (string.IsNullOrEmpty(sub.FileName))
                    sub.FileName = "Untitled";
                if (Configuration.Settings.General.CurrentVideoOffsetInMs > 0)
                {
                    sub.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(Configuration.Settings.General.CurrentVideoOffsetInMs));
                }
                return sub;
            }

            private void columnDeleteTextOnlyToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (SubtitleListview1.SelectedIndices.Count < 1)
                    return;

                MakeHistoryForUndo(_language.BeforeColumnDelete);
                foreach (int index in SubtitleListview1.SelectedIndices)
                {
                    _subtitle.Paragraphs[index].Text = string.Empty;
                    SubtitleListview1.SetText(index, string.Empty);
                    SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, index, _subtitle.Paragraphs[index]);
                }
                RefreshSelectedParagraph();
            }

            private void toolStripMenuItemBatchConvert_Click(object sender, EventArgs e)
            {
                Visible = false;
                using (var form = new BatchConvert(Icon))
                {
                    form.ShowDialog(this);
                }
                Visible = true;
            }

            private void copyOriginalTextToCurrentToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (_subtitleAlternate == null || !SubtitleListview1.IsAlternateTextColumnVisible || SubtitleListview1.SelectedIndices.Count < 1)
                    return;

                bool first = true;
                foreach (int index in SubtitleListview1.SelectedIndices)
                {
                    var original = Utilities.GetOriginalParagraph(index, _subtitle.Paragraphs[index], _subtitleAlternate.Paragraphs);
                    if (original != null)
                    {
                        if (first)
                        {
                            MakeHistoryForUndo(_language.BeforeColumnPaste);
                        }
                        SubtitleListview1.SetText(index, original.Text);
                        _subtitle.Paragraphs[index].Text = original.Text;
                        SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, index, _subtitle.Paragraphs[index]);
                        first = false;
                    }
                }
                RefreshSelectedParagraph();
            }

            private void toolStripMenuItemColumn_DropDownOpening(object sender, EventArgs e)
            {
                copyOriginalTextToCurrentToolStripMenuItem.Visible = !string.IsNullOrEmpty(copyOriginalTextToCurrentToolStripMenuItem.Text) &&
                                                                     SubtitleListview1.IsAlternateTextColumnVisible &&
                                                                     _subtitleAlternate != null;
            }

            private void toolStripMenuItemMergeDuplicateText_Click(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var form = new MergeDoubleLines())
                {
                    form.Initialize(_subtitle);
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeMergeLinesWithSameText);
                        _subtitle.Paragraphs.Clear();
                        foreach (var p in form.MergedSubtitle.Paragraphs)
                            _subtitle.Paragraphs.Add(p);
                        ShowStatus(string.Format(_language.MergedShortLinesX, form.NumberOfMerges));
                        SaveSubtitleListviewIndices();
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void toolStripMenuItemMergeLinesWithSameTimeCodes_Click(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                ReloadFromSourceView();
                using (var form = new MergeTextWithSameTimeCodes())
                {
                    form.Initialize(_subtitle);
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        MakeHistoryForUndo(_language.BeforeMergeLinesWithSameText);
                        _subtitle.Paragraphs.Clear();
                        foreach (var p in form.MergedSubtitle.Paragraphs)
                            _subtitle.Paragraphs.Add(p);
                        ShowStatus(string.Format(_language.MergedShortLinesX, form.NumberOfMerges));
                        SaveSubtitleListviewIndices();
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void toolStripMenuItem2_Click(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.Spumux, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void toolStripMenuItemModifySelection_Click(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                using (var form = new ModifySelection(_subtitle, SubtitleListview1))
                {
                    form.ShowDialog(this);
                }
            }

            private void toolStripMenuItemInverseSelection_Click(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }
                foreach (ListViewItem item in SubtitleListview1.Items)
                    item.Selected = !item.Selected;
            }

            private void toolStripMenuItemSpellCheckFromCurrentLine_Click(object sender, EventArgs e)
            {
                _spellCheckForm = null;
                SpellCheck(true, FirstSelectedIndex);
            }

            private void toolStripMenuItemImportXSub_Click(object sender, EventArgs e)
            {
                if (ContinueNewOrExit())
                {
                    openFileDialog1.Title = _language.OpenXSubFiles;
                    openFileDialog1.FileName = string.Empty;
                    openFileDialog1.Filter = _language.XSubFiles + "|*.divx;*.avi";
                    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                    {
                        ShowStatus(_languageGeneral.PleaseWait);
                        if (ImportSubtitleFromDivX(openFileDialog1.FileName))
                        {
                            ShowStatus(string.Format(_language.LoadedSubtitleX, openFileDialog1.FileName));
                        }
                        else
                        {
                            ShowStatus(string.Empty);
                            MessageBox.Show(_language.NotAValidXSubFile);
                        }
                    }
                }
            }

            private void toolStripMenuItemImportOcrHardSub_Click(object sender, EventArgs e)
            {
                using (var form = new HardSubExtract(_videoFileName))
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        if (!string.IsNullOrEmpty(form.OcrFileName))
                        {
                            MakeHistoryForUndo(_language.BeforeAutoBalanceSelectedLines);
                            OpenSubtitle(form.OcrFileName, null);
                        }
                    }
                }
            }

            private void toolStripMenuItemExportFcpIImage_Click(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.Fcp, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void ToolStripMenuItemNuendoPropertiesClick(object sender, EventArgs e)
            {
                using (var form = new NuendoProperties())
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        Configuration.Settings.SubtitleSettings.NuendoCharacterListFile = form.CharacterListFile;
                    }
                }
            }

            private void toolStripMenuItemDost_Click(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.Dost, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void toolStripMenuItemMeasurementConverter_Click(object sender, EventArgs e)
            {
                var form = new MeasurementConverter();
                form.Show(this);
            }

            private void toolStripMenuItemImportSceneChanges_Click(object sender, EventArgs e)
            {
                using (var form = new ImportSceneChanges(_videoInfo, _videoFileName))
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        audioVisualizer.SceneChanges = form.SceneChangesInSeconds;
                        SceneChangeHelper.SaveSceneChanges(_videoFileName, audioVisualizer.SceneChanges);
                        ShowStatus(string.Format(_language.XSceneChangesImported, form.SceneChangesInSeconds.Count));
                    }
                }
            }

            private void toolStripMenuItemRemoveSceneChanges_Click(object sender, EventArgs e)
            {
                if (audioVisualizer != null && audioVisualizer.SceneChanges != null)
                {
                    audioVisualizer.SceneChanges = new List<double>();
                    SceneChangeHelper.DeleteSceneChanges(_videoFileName);
                }
            }

            private void toolStripMenuItemDurationBridgeGaps_Click(object sender, EventArgs e)
            {
                if (!IsSubtitleLoaded)
                {
                    DisplaySubtitleNotLoadedMessage();
                    return;
                }

                using (var form = new DurationsBridgeGaps(_subtitle))
                {
                    if (form.ShowDialog(this) == DialogResult.OK && form.FixedCount > 0)
                    {
                        int index = FirstSelectedIndex;
                        if (index < 0)
                            index = 0;
                        MakeHistoryForUndo(_language.BeforeDurationsBridgeGap);
                        SaveSubtitleListviewIndices();
                        _subtitle.Paragraphs.Clear();
                        _subtitle.Paragraphs.AddRange(form.FixedSubtitle.Paragraphs);

                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        SubtitleListview1.SelectIndexAndEnsureVisible(index);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void toolStripMenuItemOpenDvd_Click(object sender, EventArgs e)
            {
                using (var form = new OpenVideoDvd())
                {
                    if (form.ShowDialog(this) == DialogResult.OK && !string.IsNullOrEmpty(form.DvdPath))
                    {
                        VideoFileName = form.DvdPath;
                        if (mediaPlayer.VideoPlayer != null)
                        {
                            mediaPlayer.PauseAndDisposePlayer();
                        }
                        _endSeconds = -1;

                        _videoInfo = new VideoInfo();
                        _videoInfo.Width = 720;
                        _videoInfo.Height = 576;
                        _videoInfo.FramesPerSecond = 25;
                        _videoInfo.VideoCodec = "MPEG2";
                        toolStripComboBoxFrameRate.Text = string.Format("{0:0.###}", _videoInfo.FramesPerSecond);

                        var oldVideoPlayer = Configuration.Settings.General.VideoPlayer;
                        try
                        {
                            Configuration.Settings.General.VideoPlayer = "VLC";
                            UiUtil.InitializeVideoPlayerAndContainer(VideoFileName, _videoInfo, mediaPlayer, VideoLoaded, VideoEnded);
                            mediaPlayer.ShowFullscreenButton = Configuration.Settings.General.VideoPlayerShowFullscreenButton;
                            mediaPlayer.OnButtonClicked -= MediaPlayer_OnButtonClicked;
                            mediaPlayer.OnButtonClicked += MediaPlayer_OnButtonClicked;
                            mediaPlayer.Volume = 0;
                            labelVideoInfo.Text = string.Format("DVD {0}x{1} {2}", _videoInfo.Width, _videoInfo.Height, _videoInfo.VideoCodec.Trim());
                            if (_videoInfo.FramesPerSecond > 0)
                                labelVideoInfo.Text += string.Format(" {0:0.0##}", _videoInfo.FramesPerSecond);
                        }
                        finally
                        {
                            Configuration.Settings.General.VideoPlayer = oldVideoPlayer;
                        }
                    }
                }
            }

            private void toolStripMenuItemFcpProperties_Click(object sender, EventArgs e)
            {
                using (var form = new FcpProperties())
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        Configuration.Settings.SubtitleSettings.FcpFontSize = form.FcpFontSize;
                        Configuration.Settings.SubtitleSettings.FcpFontName = form.FcpFontName;
                    }
                }
            }

            private void styleToolStripMenuItem_Click(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.Style, (sender as ToolStripItem).Text);
            }

            private void toolStripMenuItemFocusTextbox_Click(object sender, EventArgs e)
            {
                int index = _subtitle.GetIndex(audioVisualizer.RightClickedParagraph);
                if (index >= 0)
                    SubtitleListview1.SelectIndexAndEnsureVisible(index);
                textBoxListViewText.Focus();
                textBoxListViewText.SelectAll();
            }

            private void AscendingToolStripMenuItem_Click(object sender, EventArgs e)
            {
                descendingToolStripMenuItem.Checked = false;
                AscendingToolStripMenuItem.Checked = true;
                toolsToolStripMenuItem.ShowDropDown();
                toolStripMenuItem1.ShowDropDown();
            }

            private void descendingToolStripMenuItem_Click(object sender, EventArgs e)
            {
                AscendingToolStripMenuItem.Checked = false;
                descendingToolStripMenuItem.Checked = true;
                toolsToolStripMenuItem.ShowDropDown();
                toolStripMenuItem1.ShowDropDown();
            }

            private void exportCustomTextFormatToolStripMenuItem_Click(object sender, EventArgs e)
            {
                using (var form = new ExportCustomText(GetSaveSubtitle(_subtitle), GetSaveSubtitle(_subtitleAlternate), _fileName))
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        ShowStatus(form.LogMessage);
                    }
                }
            }

            private void PasteIntoActiveTextBox(string s, bool allowMultiLine = false)
            {
                if (tabControlSubtitle.SelectedIndex == TabControlSourceView)
                {
                    textBoxSource.SelectedText = s;
                }
                else
                {
                    if (textBoxListViewTextAlternate.Visible && textBoxListViewTextAlternate.Enabled && textBoxListViewTextAlternate.Focused)
                    {
                        textBoxListViewTextAlternate.SelectedText = s;
                        textBoxListViewTextAlternate.Text = textBoxListViewTextAlternate.Text.Insert(textBoxListViewTextAlternate.SelectionStart, s);
                    }
                    else
                    {
                        if (SubtitleListview1.SelectedItems.Count > 1 && !textBoxListViewText.Focused && allowMultiLine)
                        {
                            foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                            {
                                var p = _subtitle.GetParagraphOrDefault(item.Index);
                                if (p == null)
                                    continue;
                                p.Text = s + " " + p.Text;
                                SubtitleListview1.SetText(item.Index, p.Text);
                            }
                        }
                        else
                        {
                            textBoxListViewText.SelectedText = s;
                        }
                        ShowSource();
                        RefreshSelectedParagraph();
                    }
                }
            }

            private void leftToolStripMenuItem_Click(object sender, EventArgs e)
            {
                PasteIntoActiveTextBox("\u200E"); // LRM, Left-to-Right Mark, acts as a Latin character.
            }

            private void righttoleftMarkToolStripMenuItem_Click(object sender, EventArgs e)
            {
                PasteIntoActiveTextBox("\u200F"); // RLM, Right-to-Left Mark, acts as an Arabic character.
            }

            private void startOfLefttorightEmbeddingLREToolStripMenuItem_Click(object sender, EventArgs e)
            {
                PasteIntoActiveTextBox("\u202A");
            }

            private void startOfRighttoleftEmbeddingRLEToolStripMenuItem_Click(object sender, EventArgs e)
            {
                PasteIntoActiveTextBox("\u202B");
            }

            private void startOfLefttorightOverrideLROToolStripMenuItem_Click(object sender, EventArgs e)
            {
                PasteIntoActiveTextBox("\u202D");
            }

            private void startOfRighttoleftOverrideRLOToolStripMenuItem_Click(object sender, EventArgs e)
            {
                PasteIntoActiveTextBox("\u202E");
            }

            private void toolStripMenuItemRtlUnicodeControlChar_Click(object sender, EventArgs e)
            {
                string rtl = "\u202B";
                int selectedIndex = FirstSelectedIndex;
                foreach (int index in SubtitleListview1.SelectedIndices)
                {
                    var p = _subtitle.Paragraphs[index];
                    var text = p.Text.Replace(rtl, string.Empty);
                    p.Text = rtl + text.Replace(Environment.NewLine, Environment.NewLine + rtl);
                    SubtitleListview1.SetText(index, p.Text);
                    if (index == selectedIndex)
                        textBoxListViewText.Text = p.Text;
                }
                RefreshSelectedParagraph();
            }

            private void toolStripMenuItemImportImages_Click(object sender, EventArgs e)
            {
                if (!ContinueNewOrExit())
                    return;

                if (!string.IsNullOrEmpty(_videoFileName) && mediaPlayer.VideoPlayer != null)
                    mediaPlayer.Pause();

                using (var form = new ImportImages())
                {
                    if (form.ShowDialog(this) == DialogResult.OK && form.Subtitle.Paragraphs.Count > 0)
                    {
                        ImportAndOcrSrt(form.Subtitle);
                    }
                }
            }

            private void audioVisualizer_MouseEnter(object sender, EventArgs e)
            {
                if (Configuration.Settings.VideoControls.WaveformFocusOnMouseEnter && audioVisualizer.WavePeaks != null && !audioVisualizer.Focused && audioVisualizer.CanFocus)
                {
                    if (Math.Abs(_lastWaveformMenuCloseTicks - DateTime.UtcNow.Ticks) > 10000 * 500) // only if last change was longer ago than 500 milliseconds
                    {
                        audioVisualizer.Focus();
                    }
                }
            }

            private void SubtitleListview1_MouseEnter(object sender, EventArgs e)
            {
                if (Configuration.Settings.VideoControls.WaveformFocusOnMouseEnter && Configuration.Settings.VideoControls.WaveformListViewFocusOnMouseEnter && SubtitleListview1.CanFocus)
                {
                    SubtitleListview1.Focus();
                }
            }

            private void toolStripButtonFixCommonErrors_Click(object sender, EventArgs e)
            {
                FixCommonErrors(false);
            }

            private void toolStripButtonRemoveTextForHi_Click(object sender, EventArgs e)
            {
                RemoveTextForHearImpairedToolStripMenuItemClick(sender, e);
            }

            private void toolStripMenuItemExportDcinemaInteropClick(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.DCinemaInterop, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            internal Subtitle UndoFromSpellCheck(Subtitle subtitle)
            {
                var idx = FirstSelectedIndex;
                for (int i = 0; i < _subtitle.Paragraphs.Count; i++)
                {
                    if (_subtitle.Paragraphs[i].Text != subtitle.Paragraphs[i].Text)
                    {
                        _subtitle.Paragraphs[i].Text = subtitle.Paragraphs[i].Text;
                        SubtitleListview1.SetText(i, _subtitle.Paragraphs[i].Text);
                    }
                    if (idx == i)
                    {
                        SubtitleListview1.SetText(idx, _subtitle.Paragraphs[idx].Text);
                    }
                }
                RefreshSelectedParagraph();
                return _subtitle;
            }

            private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
            {
                try
                {
                    if (_timerCheckForUpdates != null)
                        _timerCheckForUpdates.Stop();
                }
                catch
                {
                }

                using (var form = new CheckForUpdates(this))
                {
                    form.ShowDialog(this);
                }
                Configuration.Settings.General.LastCheckForUpdates = DateTime.Now;
            }

            private void setVideoOffsetToolStripMenuItem_Click(object sender, EventArgs e)
            {
                if (!string.IsNullOrEmpty(_videoFileName) && mediaPlayer.VideoPlayer != null)
                    mediaPlayer.Pause();

                using (var form = new SetVideoOffset())
                {
                    form.VideoOffset = new TimeCode(10, 0, 0, 0);
                    if (Configuration.Settings.General.CurrentVideoOffsetInMs > 0)
                        form.VideoOffset = new TimeCode(Configuration.Settings.General.CurrentVideoOffsetInMs);
                    var oldVideoOffset = Configuration.Settings.General.CurrentVideoOffsetInMs;
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        if (form.FromCurrentVideoPosition && mediaPlayer.VideoPlayer != null)
                        {
                            Configuration.Settings.General.CurrentVideoOffsetInMs = (long)(Math.Round((form.VideoOffset.TotalSeconds - mediaPlayer.VideoPlayer.CurrentPosition) * 1000.0));
                        }
                        else
                        {
                            Configuration.Settings.General.CurrentVideoOffsetInMs = (long)(Math.Round(form.VideoOffset.TotalSeconds * 1000.0));
                        }
                        if (form.DoNotaddVideoOffsetToTimeCodes)
                        {
                            if (form.Reset)
                            {
                                _subtitle.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(oldVideoOffset));
                                _subtitleAlternate?.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(oldVideoOffset));
                            }
                            else
                            {
                                _subtitle.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(-Configuration.Settings.General.CurrentVideoOffsetInMs));
                                _subtitleAlternate?.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(-Configuration.Settings.General.CurrentVideoOffsetInMs));
                            }
                        }
                        SaveSubtitleListviewIndices();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RefreshSelectedParagraph();
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void toolStripMenuItemEbuProperties_Click(object sender, EventArgs e)
            {
                using (var properties = new EbuSaveOptions())
                {
                    if (_subtitle != null && _subtitle.Header != null && (_subtitle.Header.Contains("STL2") || _subtitle.Header.Contains("STL3")))
                    {
                        var header = Ebu.ReadHeader(Encoding.UTF8.GetBytes(_subtitle.Header));
                        properties.Initialize(header, Ebu.EbuUiHelper.JustificationCode, null, _subtitle);
                    }
                    else
                    {
                        var header = new Ebu.EbuGeneralSubtitleInformation();
                        if (!string.IsNullOrEmpty(_fileName) && new Ebu().IsMine(null, _fileName))
                            properties.Initialize(header, Ebu.EbuUiHelper.JustificationCode, _fileName, _subtitle);
                        else
                            properties.Initialize(header, Ebu.EbuUiHelper.JustificationCode, null, _subtitle);
                    }
                    if (properties.ShowDialog(this) == DialogResult.OK)
                    {
                        Ebu.EbuUiHelper.JustificationCode = properties.JustificationCode;
                    }
                }
            }

            private void ExportToEdlWithClipName(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.EdlClipName, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void ExportToEdl(object sender, EventArgs e)
            {
                using (var exportBdnXmlPng = new ExportPngXml())
                {
                    exportBdnXmlPng.Initialize(_subtitle, GetCurrentSubtitleFormat(), ExportPngXml.ExportFormats.Edl, _fileName, _videoInfo, _videoFileName);
                    exportBdnXmlPng.ShowDialog(this);
                }
            }

            private void ToolStripMenuItemAddWaveformBatchClick(object sender, EventArgs e)
            {
                using (var form = new AddWaveformBatch())
                {
                    form.ShowDialog(this);
                }
            }

            private void DisplaySubtitleNotLoadedMessage()
            {
                MessageBox.Show(this, _language.NoSubtitleLoaded, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            private void toolStripMenuItemExportBdTextSt_Click(object sender, EventArgs e)
            {
                using (var form = new ExportTextST(_subtitle))
                {
                    form.ShowDialog(this);
                }
            }

            private void toolStripSelected_Click(object sender, EventArgs e)
            {
                labelStatus_Click(sender, e);
            }

            private void contextMenuStripWaveform_Closing(object sender, ToolStripDropDownClosingEventArgs e)
            {
                _lastWaveformMenuCloseTicks = DateTime.UtcNow.Ticks;
            }

            private void MenuOpened(object sender, EventArgs e)
            {
                IsMenuOpen = true;
            }

            private void MenuClosed(object sender, ToolStripDropDownClosedEventArgs e)
            {
                IsMenuOpen = false;
            }

            private void MenuClosed(object sender, EventArgs e)
            {
                IsMenuOpen = false;
            }

            private void UpdateNetflixGlyphCheckToolsVisibility()
            {
                bool showTools = IsNetflixGlyphCheckAvailable();
                netflixQualityCheckToolStripMenuItem.Visible = showTools;
                toolStripButtonNetflixQualityCheck.Visible = showTools && Configuration.Settings.General.ShowToolbarNetflixGlyphCheck;
            }

            private bool IsNetflixGlyphCheckAvailable()
            {
                var formatType = GetCurrentSubtitleFormat().GetType();
                return formatType == typeof(TimedText10) || formatType == typeof(NetflixTimedText);
            }

            private void NetflixGlyphCheck(bool isSaving)
            {
                ReloadFromSourceView();

                string fileName = string.IsNullOrEmpty(_fileName) ? "UntitledSubtitle" : Path.GetFileNameWithoutExtension(_fileName);
                string language = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitle);
                var messages = new List<string>();
                var reportFiles = new List<string>();

                var netflixController = new NetflixQualityController { Language = language };
                if (!string.IsNullOrEmpty(_videoFileName) && _videoInfo != null && _videoInfo.FramesPerSecond > 20)
                {
                    netflixController.FrameRate = _videoInfo.FramesPerSecond;
                }
                netflixController.CheckAll(_subtitle);

                if (netflixController.Records.Count > 0)
                {
                    string reportPath = Path.GetTempPath() + fileName + "_NetflixQualityCheck.csv";
                    netflixController.SaveCsv(reportPath);
                    string msgFormat = string.Format("{0}\r\n\r\n{1}", string.Format(Configuration.Settings.Language.NetflixQualityCheck.FoundXIssues, netflixController.Records.Count),
                                                     Configuration.Settings.Language.NetflixQualityCheck.ReportPrompt);
                    messages.Add(string.Format(msgFormat, reportPath));
                    reportFiles.Add(reportPath);
                    using (var dialog = new NetflixQCResult(string.Join(Environment.NewLine, messages), reportFiles))
                    {
                        if (!isSaving)
                        {
                            dialog.ShowDialog(this);
                        }
                        else
                        {
                            ShowStatus(string.Format(_language.SavedSubtitleX, _fileName) + " - " +
                                       string.Format(Configuration.Settings.Language.NetflixQualityCheck.FoundXIssues, netflixController.Records.Count));
                        }
                    }
                }
                else if (!isSaving)
                {
                    messages.Add(Configuration.Settings.Language.NetflixQualityCheck.CheckOk);
                    using (var dialog = new NetflixQCResult(string.Join(Environment.NewLine, messages), reportFiles))
                    {
                        dialog.ShowDialog(this);
                    }
                }
            }

            private void netflixGlyphCheckToolStripMenuItem_Click(object sender, EventArgs e)
            {
                NetflixGlyphCheck(false);
            }

            private void toolStripButtonNetflixGlyphCheck_Click(object sender, EventArgs e)
            {
                NetflixGlyphCheck(false);
            }

            private void insertSubtitleHereToolStripMenuItem_Click(object sender, EventArgs e)
            {
                openFileDialog1.Title = _languageGeneral.OpenSubtitle;
                openFileDialog1.FileName = string.Empty;
                openFileDialog1.Filter = UiUtil.SubtitleExtensionFilter.Value;
                if (openFileDialog1.ShowDialog(this) == DialogResult.OK && File.Exists(openFileDialog1.FileName))
                {
                    var fi = new FileInfo(openFileDialog1.FileName);
                    if (fi.Length > 1024 * 1024 * 10) // max 10 mb
                    {
                        var text = string.Format(_language.FileXIsLargerThan10MB + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, openFileDialog1.FileName);
                        if (MessageBox.Show(this, text, Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                            return;
                    }

                    Encoding encoding;
                    var subtitle = new Subtitle();
                    SubtitleFormat format = subtitle.LoadSubtitle(openFileDialog1.FileName, out encoding, null);
                    if (format != null && subtitle.Paragraphs.Count > 0)
                    {
                        SaveSubtitleListviewIndices();
                        if (format.IsFrameBased)
                            subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                        else
                            subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                        if (Configuration.Settings.General.RemoveBlankLinesWhenOpening)
                            subtitle.RemoveEmptyLines();

                        var adjustment = mediaPlayer.CurrentPosition - subtitle.Paragraphs[0].StartTime.TotalSeconds;
                        if (adjustment < 0)
                            adjustment = 0;

                        foreach (Paragraph newP in subtitle.Paragraphs)
                        {
                            newP.Adjust(1.0d, adjustment);
                            if (_subtitle.Paragraphs.Any(p => newP.StartTime.TotalMilliseconds >= p.StartTime.TotalMilliseconds &&
                                                              newP.StartTime.TotalMilliseconds <= p.EndTime.TotalMilliseconds ||
                                                              newP.EndTime.TotalMilliseconds >= p.StartTime.TotalMilliseconds &&
                                                              newP.EndTime.TotalMilliseconds <= p.EndTime.TotalMilliseconds))
                            {
                                // new subs will overlap existing subs
                                if (MessageBox.Show(_language.PromptInsertSubtitleOverlap, _languageGeneral.Title, MessageBoxButtons.YesNo) == DialogResult.No)
                                {
                                    return;
                                }
                                break;
                            }
                        }

                        MakeHistoryForUndo(string.Format(_language.BeforeInsertSubtitleAtVideoPosition, openFileDialog1.FileName));

                        foreach (var p in subtitle.Paragraphs)
                        {
                            _subtitle.InsertParagraphInCorrectTimeOrder(p);
                        }
                        _subtitle.Renumber();
                        ShowSource();
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        RestoreSubtitleListviewIndices();
                    }
                }
            }

            private void actorToolStripMenuItemClick(object sender, EventArgs e)
            {
                SortSubtitle(SubtitleSortCriteria.Actor, (sender as ToolStripItem).Text);
            }

            private void toolStripMenuItemFcpXmlAdvanced_Click(object sender, EventArgs e)
            {
                using (var dialog = new ExportFcpXmlAdvanced(_subtitle, _videoFileName))
                {
                    dialog.ShowDialog(this);
                }
            }

            private void toolStripMenuItemOpenVideoFromUrl_Click(object sender, EventArgs e)
            {
                using (var form = new TextPrompt(Configuration.Settings.Language.Main.OpenVideoFile, "Url"))
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        string url = form.InputText;
                        if (!string.IsNullOrEmpty(url))
                        {
                            if (audioVisualizer.WavePeaks != null)
                            {
                                audioVisualizer.WavePeaks = null;
                                audioVisualizer.Spectrogram = null;
                                audioVisualizer.SceneChanges = new List<double>();
                            }
                            if (!panelVideoPlayer.Visible)
                                toolStripButtonToggleVideo_Click(null, null);

                            ShowSubtitleTimer.Stop();
                            Cursor = Cursors.WaitCursor;
                            VideoFileName = url;
                            if (mediaPlayer.VideoPlayer != null)
                            {
                                mediaPlayer.PauseAndDisposePlayer();
                            }
                            _endSeconds = -1;
                            UiUtil.InitializeVideoPlayerAndContainer(url, _videoInfo, mediaPlayer, VideoLoaded, VideoEnded);
                            mediaPlayer.Volume = 0;
                            mediaPlayer.ShowFullscreenButton = Configuration.Settings.General.VideoPlayerShowFullscreenButton;
                            mediaPlayer.OnButtonClicked -= MediaPlayer_OnButtonClicked;
                            mediaPlayer.OnButtonClicked += MediaPlayer_OnButtonClicked;
                            labelVideoInfo.Text = url;
                            Cursor = Cursors.Default;
                            SetUndockedWindowsTitle();
                            ShowSubtitleTimer.Start();
                        }
                    }
                }
            }

            private void SmpteTimeModedropFrameToolStripMenuItem_Click(object sender, EventArgs e)
            {
                smpteTimeModedropFrameToolStripMenuItem.Checked = !smpteTimeModedropFrameToolStripMenuItem.Checked;
                mediaPlayer.SmpteMode = smpteTimeModedropFrameToolStripMenuItem.Checked;
            }

            private void moveTextUpToolStripMenuItem_Click(object sender, EventArgs e)
            {
                var indices = SubtitleListview1.SelectedIndices.OfType<int>().OrderBy(p => p).ToList();
                if (indices.Count == 0 || indices[0] - 1 < 0)
                    return;

                MakeHistoryForUndo(string.Format(_language.BeforeX, _language.Menu.ContextMenu.ColumnTextUp));
                SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                SubtitleListview1.BeginUpdate();
                foreach (int index in indices)
                {
                    if (index - 1 >= 0)
                    {
                        var p = _subtitle.Paragraphs[index];
                        var prev = _subtitle.Paragraphs[index - 1];
                        var prevText = prev.Text;
                        prev.Text = p.Text;
                        p.Text = prevText;
                        SubtitleListview1.Items[index - 1].Selected = true;
                        SubtitleListview1.Items[index].Selected = false;
                        SubtitleListview1.SetText(index - 1, prev.Text);
                        SubtitleListview1.SetText(index, p.Text);
                        SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, index - 1, prev);
                        SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, index, p);
                    }
                }
                SubtitleListview1.EndUpdate();
                SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                SubtitleListview1.EnsureVisible(FirstSelectedIndex);
                _subtitleListViewIndex = -1;
                SubtitleListview1_SelectedIndexChanged(null, null);
            }

            private void moveTextDownToolStripMenuItem_Click(object sender, EventArgs e)
            {
                var indices = SubtitleListview1.SelectedIndices.OfType<int>().OrderByDescending(p => p).ToList();
                if (indices.Count == 0 || indices[0] + 1 >= _subtitle.Paragraphs.Count)
                    return;

                MakeHistoryForUndo(string.Format(_language.BeforeX, _language.Menu.ContextMenu.ColumnTextDown));
                SubtitleListview1.SelectedIndexChanged -= SubtitleListview1_SelectedIndexChanged;
                SubtitleListview1.BeginUpdate();
                foreach (int index in indices)
                {
                    if (index + 1 < _subtitle.Paragraphs.Count)
                    {
                        var p = _subtitle.Paragraphs[index];
                        var next = _subtitle.Paragraphs[index + 1];
                        var nextText = next.Text;
                        next.Text = p.Text;
                        p.Text = nextText;
                        SubtitleListview1.Items[index + 1].Selected = true;
                        SubtitleListview1.Items[index].Selected = false;
                        SubtitleListview1.SetText(index, p.Text);
                        SubtitleListview1.SetText(index + 1, next.Text);
                        SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, index, p);
                        SubtitleListview1.SyntaxColorLine(_subtitle.Paragraphs, index + 1, next);
                    }
                }
                SubtitleListview1.EndUpdate();
                SubtitleListview1.SelectedIndexChanged += SubtitleListview1_SelectedIndexChanged;
                SubtitleListview1.EnsureVisible(FirstSelectedIndex);
                SubtitleListview1.EnsureVisible(indices[0]);
                _subtitleListViewIndex = -1;
                SubtitleListview1_SelectedIndexChanged(null, null);
            }

            private void generateTextFromCurrentVideoToolStripMenuItem_Click(object sender, EventArgs e)
            {
                using (var form = new AudioToText(_videoFileName, _videoInfo))
                {
                    if (form.ShowDialog(this) == DialogResult.OK)
                    {
                        _subtitle.Paragraphs.Clear();
                        _subtitle.Paragraphs.AddRange(form.Subtitle.Paragraphs);
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    }
                }
            }

            private void toolStripMenuItemSplitAtWaveTextBoxPos_Click(object sender, EventArgs e)
            {
                toolStripMenuItemSplitViaWaveform_Click(sender, e);
            }
        }
    }

↑ V3022 Expression 'pos > 0' is always true.

↑ V3022 Expression 'splitContainer1.Panel2.Controls.Count > 0' is always true.

↑ V3095 The 'format' object was used before it was verified against null. Check lines: 3988, 3994.

↑ V3022 Expression 'replaceDialog != null' is always true.

↑ V3022 Expression '!replaceDialog.FindOnly' is always true.

↑ V3022 Expression '_findHelper.FindReplaceType.FindType == FindType.RegEx' is always true.

↑ V3095 The '_subtitle' object was used before it was verified against null. Check lines: 5994, 5996.

↑ V3027 The variable 'currentTextAlternate' was utilized in the logical expression before it was verified against null in the same logical expression.

↑ V3022 Expression 'SubtitleListview1.SelectedItems.Count >= 2' is always true.

↑ V3022 Expression 'audioVisualizer' is always not null. The operator '?.' is excessive.

↑ V3095 The '_subtitleAlternate' object was used before it was verified against null. Check lines: 16823, 16824.

↑ V3027 The variable 'currentText' was utilized in the logical expression before it was verified against null in the same logical expression.

↑ V3022 Expression '_networkSession != null && _networkSession.LastSubtitle != null && i < _networkSession.LastSubtitle.Paragraphs.Count' is always false.

↑ V3022 Expression 'originalCurrent != null && originalNew != null' is always true.

↑ V3022 Expression 'SubtitleListview1.SelectedItems.Count > 2' is always true.

↑ V3095 The 'old2' object was used before it was verified against null. Check lines: 9070, 9074.

↑ V3125 The 'format' object was used after it was verified against null. Check lines: 3662, 3583.

↑ V3057 The 'GetFileNameWithoutExtension' function is expected to receive a valid path string. Inspect the first argument.

↑ V3063 A part of conditional expression is always false if it is evaluated: _subtitleAlternate.Paragraphs.Count == 0.

↑ V3063 A part of conditional expression is always true if it is evaluated: info != null.

↑ V3081 The 'i' counter is not used inside a nested loop. Consider inspecting usage of 'k' counter.

↑ V3137 The 'isFirst' variable is assigned but is not used until the end of the function.

↑ V3125 The '_subtitle' object was used after it was verified against null. Check lines: 3595, 3589.

↑ V3063 A part of conditional expression is always true if it is evaluated: replaceDialog != null.

↑ V3063 A part of conditional expression is always true if it is evaluated: replaceDialog != null.

↑ V3095 The 'currentParagraph' object was used before it was verified against null. Check lines: 8745, 8753.

↑ V3095 The 'old1' object was used before it was verified against null. Check lines: 9025, 9029.

↑ V3095 The 'old2' object was used before it was verified against null. Check lines: 9025, 9032.

↑ V3095 The 'old1' object was used before it was verified against null. Check lines: 9070, 9074.

↑ V3127 Two similar code fragments were found. Perhaps, this is a typo and 'originalNew' variable should be used instead of 'originalCurrent'

↑ V3088 The expression was enclosed by parentheses twice: ((expression)). One pair of parentheses is unnecessary or misprint is present.

↑ V3009 It's odd that this method always returns one and the same value of 'true'.

↑ V3125 The 'data' object was used after it was verified against null. Check lines: 10261, 10244.

↑ V3063 A part of conditional expression is always true if it is evaluated: next != null.

↑ V3031 An excessive check can be simplified. The '||' operator is surrounded by opposite expressions.

↑ V3114 IDisposable object 'clusterStream' is not disposed before method returns.

↑ V3063 A part of conditional expression is always true if it is evaluated: existing != null.

↑ V3095 The 'message' object was used before it was verified against null. Check lines: 5247, 5249.

↑ V3063 A part of conditional expression is always true if it is evaluated: format == null.

↑ V3063 A part of conditional expression is always false if it is evaluated: _subtitleAlternate == null.

↑ V3063 A part of conditional expression is always false if it is evaluated: index < 0.

↑ V3127 Two similar code fragments were found. Perhaps, this is a typo and 'p' variable should be used instead of 'next'

↑ V3127 Two similar code fragments were found. Perhaps, this is a typo and 'Width' variable should be used instead of 'Left'

↑ V3063 A part of conditional expression is always true if it is evaluated: replaceDialog != null.

↑ V3063 A part of conditional expression is always true if it is evaluated: checkBoxAutoRepeatOn.Checked.

↑ V3063 A part of conditional expression is always true if it is evaluated: replaceDialog != null.