using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Data;
using System.Globalization;

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.ComponentModel;
using Microsoft.Win32;
using ZedGraph;

using TwinCatIdent;
using SpectAnalysis;
using TcBode;


namespace SysIdentifi
{ 
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// Class for control external generator in PLC and storage of measured data
        /// </summary>
        private TwinCatExtGen TwinCatExtGen1;

        /// <summary>
        /// List of Bode diagram from Bechoff TwinCAT tool
        /// </summary>
        private List<TwinCatBode> ListTcBode;

        /// <summary>
        /// List of asymptotes
        /// </summary>
        private List<AsymptoteProperties> ListAsymptoteProperties;

        /// <summary>
        /// Timer - Watchdog
        /// </summary>
        private System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();

        /// <summary>
        /// Open file dialog - load measured data from spectral analysis (SysIdentifi data)
        /// </summary>
        private OpenFileDialog openFileDialog_LoadData = new OpenFileDialog();
        /// <summary>
        /// Open file dialog - load measured data from Beckhoff TwinCAT tool
        /// </summary>
        private OpenFileDialog openFileDialog_LoadTcBodeData = new OpenFileDialog();
        /// <summary>
        /// Open file dialog - load motion profile data
        /// </summary>
        private OpenFileDialog openFileDialog_LoadProfData = new OpenFileDialog();
        /// <summary>
        /// Open file dialog - load generator settings data
        /// </summary>
        private OpenFileDialog openFileDialog_SettingsData = new OpenFileDialog();
        /// <summary>
        /// Save file dialog - save measured data from spectral analysis (SysIdentifi data)
        /// </summary>
        private SaveFileDialog saveFileDialog_SaveData = new SaveFileDialog();
        /// <summary>
        /// Save file dialog - save generator settings data
        /// </summary>
        private SaveFileDialog saveFileDialog_SaveSettingsData = new SaveFileDialog();

        /// <summary>
        /// Constructor for Main window
        /// </summary>
        public MainWindow()
        {
            TwinCatExtGen1 = new TwinCatExtGen();
            InitializeComponent();

            TwinCatExtGen1.ChangedState += new StateEventHandler(ChangedStateEvent);   // registr event for change state
            TwinCatExtGen1.DataArrived += new ActionEventHandler(DataArrivedEvent);   // registr event for arrived data
            TwinCatExtGen1.CurrentArrived += new ActionEventHandler(CurrentArrivedEvent);   // registr event for arrived current values
            TwinCatExtGen1.ErrorOccured += new ActionEventHandler(ErrorOccuredEvent);   // registr event for error occuring in TwinCatExtGen event methods        
            TwinCatExtGen1.LoadInputSignal();   // load input identification signals

            ListTcBode = new List<TwinCatBode>();

            ListAsymptoteProperties = new List<AsymptoteProperties>();

            // Transfer input signal for indentification to combobox
            for (int i = 0; i < TwinCatExtGen1.ListInputIdentSignal.Count; i++)
            {
                comboBox_SelectedInputSignal.Items.Add(TwinCatExtGen1.ListInputIdentSignal[i].Name);
            }
            comboBox_SelectedInputSignal.SelectedIndex = 0;

            openFileDialog_LoadData.FileName = "Load data";
            openFileDialog_LoadData.FileOk += new System.ComponentModel.CancelEventHandler(openFileDialog_LoadData_FileOk);
            openFileDialog_LoadTcBodeData.FileName = "Load TwinCAT Bode plot data";
            openFileDialog_LoadTcBodeData.FileOk += new System.ComponentModel.CancelEventHandler(openFileDialog_LoadTcBodeData_FileOk);
            openFileDialog_LoadProfData.FileName = "Load profile";
            openFileDialog_LoadProfData.FileOk += new System.ComponentModel.CancelEventHandler(openFileDialog_LoadProfData_FileOk);
            openFileDialog_SettingsData.FileName = "Load settings";
            openFileDialog_SettingsData.FileOk += new System.ComponentModel.CancelEventHandler(openFileDialog_SettingsData_FileOk);
            saveFileDialog_SaveData.FileName = "Save data";
            saveFileDialog_SaveData.FileOk += new System.ComponentModel.CancelEventHandler(saveFileDialog_SaveData_FileOk);
            saveFileDialog_SaveSettingsData.FileName = "Save Settings";
            saveFileDialog_SaveSettingsData.FileOk += new System.ComponentModel.CancelEventHandler(saveFileDialog_SaveSettingsData_FileOk);

            InitzedGraphControl_BodePlot();
            InitzedGraphControl_CurrentPlot();
            InitzedGraphControl_StepResponse();

            // Init combobox for mode of spectral analysis
            comboBoxModeAnalysis.ItemsSource = Enum.GetValues(typeof(eModeAnalysis));
            comboBoxModeAnalysis.SelectedIndex = 0;

            // Init timer
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
            EstimatedTimeRunnigProcess = 0;

            // Set actual state
            ChangedStateEvent(TwinCatExtGen1, new StateEvent(eStateExtGen.Offline));
        }

        #region Events from TwinCAT external generator 
        
        /// <summary>
        /// Event - change state of generator
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"> Actual state of external generator </param>
        private void ChangedStateEvent(object source, StateEvent e)
        {
            eStateExtGen StateGenerator;    
            StateGenerator = e.GetInfo();
            switch(StateGenerator)
            {
                case eStateExtGen.Offline:
                    button_Run.IsEnabled = false;
                    MenuRun.IsEnabled = false;
                    button_Stop.IsEnabled = false;
                    button_Stop.Background = button_LoadData.Background;
                    MenuStop.IsEnabled = false;
                    MenuStop.Background = MenuExit.Background;
                    button_Connect.IsEnabled = true;
                    button_Connect.Background = button_LoadData.Background;
                    button_Connect.Content = "Connect";
                    MenuConnect.IsEnabled = true;
                    MenuConnect.Background = MenuExit.Background;
                    MenuConnect.Header = "Connect";
                    button_LoadData.IsEnabled = true;
                    button_Asymptote.IsEnabled = true;
                    MenuLoadData.IsEnabled = true;
                    button_ResetError.IsEnabled = false;
                    MenuResetError.IsEnabled = false;
                    button_EditNotes.IsEnabled = true;
                    FreezeSetProperties();
                    DefrostTargetProperties();
                    textBox_Date.Visibility = Visibility.Visible;
                    textBox_Date.Height = 26;
                    label_Date.Visibility = Visibility.Visible;
                    label_Date.Height = 26;
                    treeViewListCurves.IsHitTestVisible = true;
                    // stop timer
                    TimerStop();
                    if (((TreeViewItemExt)treeViewListCurves.SelectedItem) != null)
                    {
                        if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.SpectAnalysis)
                        {
                            // Refresh properties
                            SetProperties(TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData]);
                            ShowCurrentAllPlot(TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData]);
                        } 
                        else if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.TcBode)
                        {
                            SetProperties(ListTcBode[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData].ListTcBodeData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexAuxData]);
                        }
                        else if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.Asymptote)
                        {
                            SetProperties(ListAsymptoteProperties[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData]);
                        }
                    }
                    lblStatus.Text = TwinCatExtGen1.GetActStateExtGen.ToString();                   
                    break;

                case eStateExtGen.Online:
                    button_Connect.Background = Brushes.Red;
                    button_Connect.IsEnabled = true;
                    button_Connect.Content = "Disconnect";
                    MenuConnect.IsEnabled = true;
                    MenuConnect.Background = Brushes.Red;
                    MenuConnect.Header = "Disconnect";
                    button_Run.IsEnabled = true;
                    MenuRun.IsEnabled = true;
                    button_Stop.IsEnabled = false;
                    button_Stop.Background = button_LoadData.Background;
                    MenuStop.IsEnabled = false;
                    MenuStop.Background = MenuExit.Background;
                    button_LoadData.IsEnabled = false;
                    button_Asymptote.IsEnabled = false;
                    MenuLoadData.IsEnabled = false;
                    button_EditNotes.Content = "Edit";
                    button_EditNotes.IsEnabled = false;
                    DefrostSetProperties();
                    FreezeTargetProperties();
                    textBox_Date.Visibility = Visibility.Hidden;
                    textBox_Date.Height = 0;
                    label_Date.Visibility = Visibility.Hidden;
                    label_Date.Height = 0;
                    treeViewListCurves.IsHitTestVisible = false;
                    textBox_TaskTime.Text = (TwinCatExtGen1.ActCycleTime*1000).ToString(System.Globalization.CultureInfo.InvariantCulture);
                    // stop timer
                    TimerStop();
                    lblStatus.Text = TwinCatExtGen1.GetActStateExtGen.ToString();
                    break;

                case eStateExtGen.Running:
                    button_Run.IsEnabled = false;
                    MenuRun.IsEnabled = false;
                    button_Stop.IsEnabled = true;
                    button_Stop.Background = Brushes.Red;
                    MenuStop.IsEnabled = true;
                    MenuStop.Background = Brushes.Red;
                    FreezeSetProperties();
                    // re-initial and start timer
                    TimerStart();                    
                    lblStatus.Text = TwinCatExtGen1.GetActStateExtGen.ToString();
                    break;

                case eStateExtGen.Error:
                    button_Run.IsEnabled = false;
                    MenuRun.IsEnabled = false;
                    button_Stop.IsEnabled = false;
                    button_Stop.Background = button_LoadData.Background;
                    MenuStop.IsEnabled = false;
                    MenuStop.Background = MenuExit.Background;
                    button_Connect.IsEnabled = false;
                    button_Connect.Background = Brushes.Transparent;
                    MenuConnect.Background = Brushes.Transparent;
                    MenuConnect.IsEnabled = false;
                    button_LoadData.IsEnabled = true;
                    button_Asymptote.IsEnabled = true;
                    MenuLoadData.IsEnabled = true;
                    button_ResetError.IsEnabled = true;
                    MenuResetError.IsEnabled = true;
                    FreezeSetProperties();
                    FreezeTargetProperties();
                    textBox_Date.Visibility = Visibility.Visible;
                    textBox_Date.Height = 26;
                    label_Date.Visibility = Visibility.Visible;
                    label_Date.Height = 26;
                    treeViewListCurves.IsHitTestVisible = true;
                    if (((TreeViewItemExt)treeViewListCurves.SelectedItem) != null)
                    {
                        if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.SpectAnalysis)
                        {
                            // refresh properties and current plot
                            SetProperties(TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData]);
                            ShowCurrentAllPlot(TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData]);
                        }
                        else if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.TcBode)
                        {
                            SetProperties(ListTcBode[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData].ListTcBodeData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexAuxData]);
                        }
                        else if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.Asymptote)
                        {
                            SetProperties(ListAsymptoteProperties[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData]);
                        }
                    }
                    // stop timer
                    TimerStop();
                    lblStatus.Text = TwinCatExtGen1.GetActStateExtGen.ToString();         
                    break;

                default:
                    button_Run.IsEnabled = false;
                    MenuRun.IsEnabled = false;
                    button_Stop.IsEnabled = false;
                    button_Stop.Background = button_LoadData.Background;
                    MenuStop.IsEnabled = false;
                    MenuStop.Background = MenuExit.Background;
                    button_Connect.IsEnabled = false;
                    button_Connect.Background = button_LoadData.Background;
                    MenuConnect.Background = MenuExit.Background;
                    MenuConnect.IsEnabled = false;
                    button_LoadData.IsEnabled = false;
                    button_Asymptote.IsEnabled = false;
                    MenuLoadData.IsEnabled = false;
                    button_ResetError.IsEnabled = false;
                    MenuResetError.IsEnabled = false;
                    FreezeSetProperties();
                    FreezeTargetProperties();
                    treeViewListCurves.IsEnabled = false;
                    // stop timer
                    TimerStop();
                    lblStatus.Text = eStateExtGen.Error.ToString() + "- Please restart application";
                    MessageBox.Show("General error.\nPlease restart application.");
                    break;
            }
        }

        /// <summary>
        /// Arrived all data from measurement from PLC
        /// </summary>
        /// <param name="source"></param>
        private void DataArrivedEvent(object source)
        {
            try
            {
                AddCurveMd(TwinCatExtGen1);

                SetProperties(TwinCatExtGen1.MeasuredData.Last());
                ShowCurrentAllPlot(TwinCatExtGen1.MeasuredData.Last());
                button_SaveData.IsEnabled = true;
                MenuSaveData.IsEnabled = true;
                MenuSaveSettingsData.IsEnabled = true;
                button_DeleteAllCurve.IsEnabled = true;
                MenuDeleteAll.IsEnabled = true;
            }
            catch (Exception err)
            {
                MessageBox.Show("Data from PLC came but there is problem.\n " + err.Message);
            }
        }

        /// <summary>
        /// Arrived data set with current values
        /// </summary>
        /// <param name="source"></param>
        private void CurrentArrivedEvent(object source)
        {
            ShowCurrentPlot(TwinCatExtGen1.MeasuredData.Last());
        }

        /// <summary>
        /// Occured error in PLC
        /// </summary>
        /// <param name="source"> Error message from PLC </param>
        private void ErrorOccuredEvent(object source)
        {
            MessageBox.Show((string)source);
        }

        #endregion

        #region Events from GUI

        #region Events from buttons
        /// <summary>
        /// Connect/Disconnect to PLC
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Connect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (CheckTargetProp() != true)
                {
                    eStateExtGen StateGenerator = TwinCatExtGen1.GetActStateExtGen;
                    switch (StateGenerator)
                    {
                        case eStateExtGen.Offline:
                            if(PropertiesGrid.Visibility == Visibility.Hidden)
                            {
                                PropertiesTcBodeGrid.Visibility = Visibility.Hidden;
                                PropertiesAsymptote.Visibility = Visibility.Hidden;
                                PropertiesGrid.Visibility = Visibility.Visible;
                                MenuSaveSettingsData.IsEnabled = true; // enable button for save settings
                            }
                            else
                            {
                                ClearCurrentPlot();
                                TwinCatExtGen1.Connect(textBox_AmsNetIdTarget.Text, Convert.ToInt32(textBox_AdsPort.Text), textBox_ExternGenerator.Text);
                            }
                            break;

                        case eStateExtGen.Online:
                            TwinCatExtGen1.Disconnect();
                            break;

                        case eStateExtGen.Running:
                            TwinCatExtGen1.Disconnect();
                            break;

                        case eStateExtGen.Error:
                            TwinCatExtGen1.Disconnect();
                            break;

                        default:
                            TwinCatExtGen1.Disconnect();
                            break;
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        /// <summary>
        /// Run external genrator
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Run_Click(object sender, RoutedEventArgs e)
        {
           if (TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Online)
            {
                try
                {
                    if (CheckGenerProp() != true)
                    {
                        CheckTargetProp();  // update sources
                        ClearCurrentPlot();
                        // Get data from InDataProp(.xaml)
                        Binding BindInDataProp = BindingOperations.GetBinding(textBox_AmsNetIdTarget, TextBox.TextProperty);
                        DataProperties DataProp = BindInDataProp.Source as DataProperties;
                        DataProp.DateTimeMd = DateTime.Now;
                        // Start external generator
                        TwinCatExtGen1.Start(DataProp);                        
                    }
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            }
        }

        /// <summary>
        /// Stop external generator
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Stop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Stop external generator
                TwinCatExtGen1.Stop();
                // stop timer
                TimerStop();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        /// <summary>
        /// Last path used in saveFileDialog_SaveData
        /// </summary>
        private string LastPathSaveData = "";
        /// <summary>
        /// Show saveFileDialog_SaveData 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_SaveData_Click(object sender, RoutedEventArgs e)
        {
            if (((TreeViewItemExt)treeViewListCurves.SelectedItem) != null)
            {
                if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.SpectAnalysis)
                {
                    saveFileDialog_SaveData.Filter = "Identification data files (.identdat)|*.identdat";
                    saveFileDialog_SaveData.FilterIndex = 1;
                    if (LastPathSaveData != "")
                        saveFileDialog_SaveData.InitialDirectory = LastPathSaveData;
                    saveFileDialog_SaveData.FileName = TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData].GetSaveName();
                    saveFileDialog_SaveData.ShowDialog();
                }
            }          
        }

        /// <summary>
        /// saveFileDialog_SaveData is closed - save data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveFileDialog_SaveData_FileOk(object sender, CancelEventArgs e)
        {
            if (((TreeViewItemExt)treeViewListCurves.SelectedItem) != null)
            {
                if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.SpectAnalysis)
                {
                    string path = saveFileDialog_SaveData.FileName;
                    LastPathSaveData = saveFileDialog_SaveData.FileName.Substring(0, saveFileDialog_SaveData.FileName.Length - saveFileDialog_SaveData.SafeFileName.Length);
                    TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData].SaveData(path);
                }
            }
        }

        /// <summary>
        /// Last path used in saveFileDialog_SaveSettingsData
        /// </summary>
        private string LastPathSaveSettingsData = "";
        /// <summary>
        /// Count of saved settings
        /// </summary>
        private int CountSavedSettings = 0;
        /// <summary>
        /// Show saveFileDialog_SaveSettingsData
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_SaveSettingsData_Click(object sender, RoutedEventArgs e)
        {
            CheckTargetProp();  // update sources
            CheckGenerProp();
            // Get data from InDataProp(.xaml)
            Binding BindInDataProp = BindingOperations.GetBinding(textBox_AmsNetIdTarget, TextBox.TextProperty);
            DataProperties DataProp = BindInDataProp.Source as DataProperties;

            saveFileDialog_SaveSettingsData.Filter = "Generator settings (.genset)|*.genset";
            saveFileDialog_SaveSettingsData.FilterIndex = 1;
            if (LastPathSaveSettingsData != "")
                saveFileDialog_SaveSettingsData.InitialDirectory = LastPathSaveSettingsData;
            saveFileDialog_SaveSettingsData.FileName = CountSavedSettings.ToString(System.Globalization.CultureInfo.InvariantCulture) + "_" + DataProp.NameAxis + "_Settings" ;
            ++CountSavedSettings;
            saveFileDialog_SaveSettingsData.ShowDialog(); 
        }

        /// <summary>
        /// saveFileDialog_SaveSettingsData is closed - save settings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveFileDialog_SaveSettingsData_FileOk(object sender, CancelEventArgs e)
        {
            string path = saveFileDialog_SaveSettingsData.FileName;
            LastPathSaveSettingsData = saveFileDialog_SaveSettingsData.FileName.Substring(0, saveFileDialog_SaveSettingsData.FileName.Length - saveFileDialog_SaveSettingsData.SafeFileName.Length);

            CheckTargetProp();  // update sources
            CheckGenerProp();
            // Get data from InDataProp(.xaml)
            Binding BindInDataProp = BindingOperations.GetBinding(textBox_AmsNetIdTarget, TextBox.TextProperty);
            DataProperties DataProp = BindInDataProp.Source as DataProperties;
            DataProp.DateTimeMd = DateTime.Now;

            DataProp.SaveSettingsData(path);

        }

        /// <summary>
        /// Last path used in openFileDialog_LoadData
        /// </summary>
        private string LastPathLoadData = "";
        /// <summary>
        /// Show openFileDialog_LoadData
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_LoadData_Click(object sender, RoutedEventArgs e)
        {
            openFileDialog_LoadData.Filter = "Identification data files (.identdat)|*.identdat";
            openFileDialog_LoadData.FilterIndex = 1;
            openFileDialog_LoadData.Multiselect = false;
            if (LastPathLoadData != "")
                openFileDialog_LoadData.InitialDirectory = LastPathLoadData;
            openFileDialog_LoadData.ShowDialog();
        }

        /// <summary>
        /// Last path used in openFileDialog_LoadTcBodeData
        /// </summary>
        private string LastPathTcBodePlotData = "";
        /// <summary>
        /// Show openFileDialog_LoadTcBodeData
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_LoadTcBodePlotData_Click(object sender, RoutedEventArgs e)
        {
            openFileDialog_LoadTcBodeData.Filter = "TwinCAT bode plot data (.tcbodeproj)|*.tcbodeproj";
            openFileDialog_LoadTcBodeData.FilterIndex = 1;
            openFileDialog_LoadTcBodeData.Multiselect = false;
            if (LastPathTcBodePlotData != "")
                openFileDialog_LoadTcBodeData.InitialDirectory = LastPathTcBodePlotData;
            openFileDialog_LoadTcBodeData.ShowDialog();
        }

        /// <summary>
        /// Last path used in openFileDialog_LoadProfData
        /// </summary>
        private string LastPathProfData = "";
        /// <summary>
        /// Show openFileDialog_LoadProfData
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_LoadProfData_Click(object sender, RoutedEventArgs e)
        {
            openFileDialog_LoadProfData.Filter = "Motion profile data (.mtprofile)|*.mtprofile";
            openFileDialog_LoadProfData.FilterIndex = 1;
            openFileDialog_LoadProfData.Multiselect = false;
            if (LastPathProfData != "")
                openFileDialog_LoadProfData.InitialDirectory = LastPathProfData;
            openFileDialog_LoadProfData.ShowDialog();
        }

        /// <summary>
        /// Last path used in openFileDialog_LoadProfData
        /// </summary>
        private string LastPathSetData = "";
        /// <summary>
        /// Show openFileDialog_SettingsData
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_LoadSettings_Click(object sender, RoutedEventArgs e)
        {
            openFileDialog_SettingsData.Filter = "Generator settings (.genset)|*.genset";
            openFileDialog_SettingsData.FilterIndex = 1;
            openFileDialog_SettingsData.Multiselect = false;
            if(LastPathSetData != "")
                openFileDialog_SettingsData.InitialDirectory = LastPathSetData;
            openFileDialog_SettingsData.ShowDialog();
        }

        /// <summary>
        /// openFileDialog_LoadData is closed - load data from spectral analysis (SysIdentifi data)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileDialog_LoadData_FileOk(object sender, CancelEventArgs e)
        {
            string path = openFileDialog_LoadData.FileName;
            LastPathLoadData = openFileDialog_LoadData.FileName.Substring(0, openFileDialog_LoadData.FileName.Length - openFileDialog_LoadData.SafeFileName.Length);
            try
            {               
                // Data from spectral analysis
                TwinCatExtGen1.LoadData(path);

                AddCurveMd(TwinCatExtGen1);

                //display value in Property window
                SetProperties(TwinCatExtGen1.MeasuredData.Last());
                ShowCurrentAllPlot(TwinCatExtGen1.MeasuredData.Last());
                button_SaveData.IsEnabled = true;
                MenuSaveData.IsEnabled = true;
                MenuSaveSettingsData.IsEnabled = true;
                button_DeleteAllCurve.IsEnabled = true;
                MenuDeleteAll.IsEnabled = true;
            }
            catch(Exception exc)
            {
                MessageBox.Show("Wrong file. " + exc.Message);
            }
        }

        /// <summary>
        /// openFileDialog_LoadTcBodeData is closed - load data from Beckhoff TwinCAT tool
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileDialog_LoadTcBodeData_FileOk(object sender, CancelEventArgs e)
        {
            string path = openFileDialog_LoadTcBodeData.FileName;
            LastPathTcBodePlotData = openFileDialog_LoadTcBodeData.FileName.Substring(0, openFileDialog_LoadTcBodeData.FileName.Length - openFileDialog_LoadTcBodeData.SafeFileName.Length);
            try
            {
                // Data from TwinCAT Bode plot
                TwinCatBode tempTcBode = new TwinCatBode();
                tempTcBode.LoadXmlData(path);
                ListTcBode.Add(tempTcBode);

                AddCurveMd(ListTcBode);

                SetProperties(ListTcBode.Last().ListTcBodeData.Last());
                ClearCurrentPlot();
                button_SaveData.IsEnabled = false;
                MenuSaveData.IsEnabled = false;
                MenuSaveSettingsData.IsEnabled = false;
                button_DeleteAllCurve.IsEnabled = true;
                MenuDeleteAll.IsEnabled = true;
            }
            catch (Exception exc)
            {
                MessageBox.Show("Wrong file. " + exc.Message);
            }
        }

        /// <summary>
        /// openFileDialog_LoadProfData is closed - load motion profile data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileDialog_LoadProfData_FileOk(object sender, CancelEventArgs e)
        {
            string path = openFileDialog_LoadProfData.FileName;
            LastPathProfData = openFileDialog_LoadProfData.FileName.Substring(0, openFileDialog_LoadProfData.FileName.Length - openFileDialog_LoadProfData.SafeFileName.Length);
            try
            {
                DataProperties LoadedData = DataProperties.LoadProfileData(path);
                textBox_xScale.Text = LoadedData.sxScale;
                textBox_vScale.Text = LoadedData.svScale;
                textBox_OffsetIOdata.Text = LoadedData.sOffsetIOdata;
                textBox_Notes.Text = LoadedData.Notes;
            }
            catch (Exception exc)
            {
                MessageBox.Show("Wrong file. " + exc.Message);
            }
        }

        /// <summary>
        /// openFileDialog_SettingsData is closed - load generator settings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileDialog_SettingsData_FileOk(object sender, CancelEventArgs e)
        {
            string path = openFileDialog_SettingsData.FileName;
            LastPathSetData = openFileDialog_SettingsData.FileName.Substring(0, openFileDialog_SettingsData.FileName.Length - openFileDialog_SettingsData.SafeFileName.Length);
            try
            {
                DataProperties LoadedData = DataProperties.LoadSettingsData(path);
                SetProperties(LoadedData);
            }
            catch (Exception exc)
            {
                MessageBox.Show("Wrong file. " + exc.Message);
            }
        }

        /// <summary>
        /// Reset error state of external generator (TwinCatExtGen1)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_ResetError_Click(object sender, RoutedEventArgs e)
        {
            TwinCatExtGen1.ResetErrorState();
        }

        /// <summary>
        /// Reset zoom of all graphs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_ResetZoom_Click(object sender, RoutedEventArgs e)
        {
            PlotChartMagnitude.RestoreScale(PlotChartMagnitude.GraphPane);
            PlotChartPhase.RestoreScale(PlotChartPhase.GraphPane);
            PlotChartStepResponse.RestoreScale(PlotChartStepResponse.GraphPane);
            PlotChartCurrent.RestoreScale(PlotChartCurrent.GraphPane);
        }      

        /// <summary>
        /// Delete of curves
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_DeleteAllCurve_Click(object sender, RoutedEventArgs e)
        {
            TwinCatExtGen1.MeasuredData.Clear();
            ListAsymptoteProperties.Clear();
            ListTcBode.Clear();
            treeViewListCurves.Items.Clear();
            PlotChartMagnitude.GraphPane.CurveList.Clear();
            PlotChartMagnitude.Refresh();
            PlotChartPhase.GraphPane.CurveList.Clear();
            PlotChartPhase.Refresh();
            ((PointPairList)PlotChartCurrent.GraphPane.CurveList[0].Points).Clear();
            PlotChartCurrent.Refresh();
            PlotChartStepResponse.GraphPane.CurveList.Clear();
            PlotChartStepResponse.Refresh();

            button_DeleteAllCurve.IsEnabled = false;
            MenuDeleteAll.IsEnabled = false;

            PropertiesGrid.Visibility = Visibility.Visible;
            PropertiesTcBodeGrid.Visibility = Visibility.Hidden;
            PropertiesAsymptote.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// Active event for addition of asymptote
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Asymptote_Click(object sender, RoutedEventArgs e)
        {
            PropertiesGrid.Visibility = Visibility.Hidden;
            PropertiesTcBodeGrid.Visibility = Visibility.Hidden;
            PropertiesAsymptote.Visibility = Visibility.Visible;

            PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClickEditAsymp;
            PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClick;
            PlotChartMagnitude.MouseClick += PlotChartMagnitude_MouseClick;
            
            textBox_SlopeOfDecade.Background = Brushes.White;
            textBox_SlopeOfDecade.IsReadOnly = false;
            comboBox_AsymptoteColor.Background = Brushes.White;
            comboBox_AsymptoteColor.IsEnabled = true;
            button_EditAsymptote.Content = "OK";
        }

        /// <summary>
        /// Active event for editing of asymptote
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_EditAsymptote_Click(object sender, RoutedEventArgs e)
        {
            if ((TreeViewItemExt)treeViewListCurves.SelectedItem != null)
            {
                if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.Asymptote)
                {
                    if ((string)button_EditAsymptote.Content == "Edit")
                    {
                        // edit only existing asymptote
                        if (textBox_SlopeOfDecade.IsReadOnly == true)
                        {
                            PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClick;
                            PlotChartMagnitude.MouseClick += PlotChartMagnitude_MouseClickEditAsymp;

                            button_EditAsymptote.Content = "OK";
                            textBox_SlopeOfDecade.Background = Brushes.White;
                            textBox_SlopeOfDecade.IsReadOnly = false;
                            comboBox_AsymptoteColor.Background = Brushes.White;
                            comboBox_AsymptoteColor.IsEnabled = true;
                        }
                    }
                    else
                    {
                        // Close edit of Asymptote
                        PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClickEditAsymp;
                        // Cancel new asymptote
                        PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClick;

                        textBox_SlopeOfDecade.IsReadOnly = true;
                        textBox_SlopeOfDecade.Background = Brushes.LightGray;
                        comboBox_AsymptoteColor.IsEnabled = false;
                        button_EditAsymptote.Content = "Edit";
                    }
                }
            }
            else
            {
                textBox_SlopeOfDecade.IsReadOnly = true;
                textBox_SlopeOfDecade.Background = Brushes.LightGray;
                comboBox_AsymptoteColor.IsEnabled = false;
                button_EditAsymptote.Content = "Edit";
                // Close edit of Asymptote
                PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClickEditAsymp;
                // Cancel new asymptote
                PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClick;
            }
        }

        /// <summary>
        /// Close application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// Edit notes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_EditNotes_Click(object sender, RoutedEventArgs e)
        {
            if (TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Offline)
            {
                if ((string)button_EditNotes.Content == "Edit")
                {
                    // Edit section
                    if(TwinCatExtGen1.MeasuredData.Count > 0)
                    {
                        button_EditNotes.Content = "OK";
                        textBox_Notes.IsReadOnly = false;
                        textBox_Notes.Background = Brushes.White;
                    }

                }
                else
                {
                    // OK section
                    TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData].Notes = textBox_Notes.Text;
                    textBox_Notes.IsReadOnly = true;
                    textBox_Notes.Background = Brushes.LightGray;
                    button_EditNotes.Content = "Edit";
                }
            }
        }

        /// <summary>
        /// Manual in Slovak
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuHelpSk_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(@"Manual\SysIdentifiManualSk.pdf");
            }
            catch(Exception err)
            {
                MessageBox.Show("Cannot open file with manual in Slovak language.\n" + err.Message);
            }
        }

        /// <summary>
        /// Manual in English
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuHelpEn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(@"Manual\SysIdentifiManualEn.pdf");
            }
            catch (Exception err)
            {
                MessageBox.Show("Cannot open file with manual in English language.\n" + err.Message);
            }
        }

        #endregion

        #region Events from TreeView - List of curves

        /* COMMON METHODS */

        /// <summary>
        /// Event for click on main checkbox in TreeView element(list of curves) - all curves expect for asymptote TreeViewElement
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventChangeTreeItem(object source, System.Windows.RoutedEventArgs e)
        {

            int NumItem = Convert.ToInt32(((CheckBox)source).Name.Substring(15, ((CheckBox)source).Name.Length - 15));   //14, ((CheckBox)source).Name.Length-1

            int CountItems = ((TreeViewItem)treeViewListCurves.Items[NumItem]).Items.Count;

            if (((CheckBox)source).IsChecked == true)
            {
                for (int i = 0; i < CountItems; i++)
                {
                    ((CheckBox)((TreeViewItem)((TreeViewItemExt)treeViewListCurves.Items[NumItem]).Items[i]).Header).IsEnabled = true;
                }
            }
            else
            {
                for (int i = 0; i < CountItems; i++)
                {
                    ((CheckBox)((TreeViewItem)((TreeViewItemExt)treeViewListCurves.Items[NumItem]).Items[i]).Header).IsEnabled = false;
                }
            }

            PlotChartMagnitude.AxisChange();
            PlotChartMagnitude.Invalidate();
            PlotChartPhase.AxisChange();
            PlotChartPhase.Invalidate();
            if (((TreeViewItemExt)treeViewListCurves.Items[NumItem]).DataType == MeasurementType.SpectAnalysis)
            {
                PlotChartStepResponse.AxisChange();
                PlotChartStepResponse.Invalidate();
            }
            
        }

        /// <summary>
        /// Event for click on main checkbox in TreeView element(list of curves) - only asymptote TreeViewElement
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventChangeAsymptoteTreeItem(object source, System.Windows.RoutedEventArgs e)
        {
            // ID of curves
            int NumItem = Convert.ToInt32(((CheckBox)source).Name.Substring(15, ((CheckBox)source).Name.Length - 15));

            if ((((CheckBox)source).IsChecked == true) && (((CheckBox)source).IsEnabled == true))
            {
                PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphClosedLoopMg].IsVisible = true;
            }
            else
            {
                PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphClosedLoopMg].IsVisible = false;
            }

            PlotChartMagnitude.AxisChange();
            PlotChartMagnitude.Invalidate();
        }

        /// <summary>
        /// Event from change Closed loop TreeView element (Click event)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventChangeTreeClosedLoopItem(object source, System.Windows.RoutedEventArgs e)
        {
            // ID of curves
            int NumItem = Convert.ToInt32(((CheckBox)source).Name.Substring(17, ((CheckBox)source).Name.Length - 17));

            if ((((CheckBox)source).IsChecked == true) && (((CheckBox)source).IsEnabled == true))
            {
                PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphClosedLoopMg].IsVisible = true;
                PlotChartPhase.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphClosedLoopPh].IsVisible = true;
            }
            else
            {
                PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphClosedLoopMg].IsVisible = false;
                PlotChartPhase.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphClosedLoopPh].IsVisible = false;
            }

            PlotChartMagnitude.AxisChange();
            PlotChartMagnitude.Invalidate();
            PlotChartPhase.AxisChange();
            PlotChartPhase.Invalidate();
        }

        /// <summary>
        /// Event from change Closed loop TreeView element (Enabled property changed - event)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventEnabledTreeClosedLoopItem(object source, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            System.Windows.RoutedEventArgs EvArg = new RoutedEventArgs();
            eventChangeTreeClosedLoopItem(source, EvArg);
        }

        /// <summary>
        /// Event from change Open loop TreeView element (Click event)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventChangeTreeOpenLoopItem(object source, System.Windows.RoutedEventArgs e)
        {
            // ID of curves
            int NumItem = Convert.ToInt32(((CheckBox)source).Name.Substring(17, ((CheckBox)source).Name.Length - 17));

            if ((((CheckBox)source).IsChecked == true) && (((CheckBox)source).IsEnabled == true))
            {
                PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphOpenLoopMg].IsVisible = true;
                PlotChartPhase.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphOpenLoopPh].IsVisible = true;
            }
            else
            {
                PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphOpenLoopMg].IsVisible = false;
                PlotChartPhase.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphOpenLoopPh].IsVisible = false;
            }

            PlotChartMagnitude.AxisChange();
            PlotChartMagnitude.Invalidate();
            PlotChartPhase.AxisChange();
            PlotChartPhase.Invalidate();
        }

        /// <summary>
        /// Event from change Open loop TreeView element (Enabled property changed - event)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventEnabledTreeOpenLoopItem(object source, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            System.Windows.RoutedEventArgs EvArg = new RoutedEventArgs();
            eventChangeTreeOpenLoopItem(source, EvArg);
        }

        /// <summary>
        /// Event - TreeView item got focus
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventGotFocusTreeItem(object source, System.Windows.RoutedEventArgs e)
        {

            if (((TreeViewItemExt)source).DataType == MeasurementType.SpectAnalysis)
            {
                SetProperties(TwinCatExtGen1.MeasuredData[((TreeViewItemExt)source).IndexData]);
                ShowCurrentAllPlot(TwinCatExtGen1.MeasuredData[((TreeViewItemExt)source).IndexData]);

                button_SaveData.IsEnabled = true;
                MenuSaveData.IsEnabled = true;
                MenuSaveSettingsData.IsEnabled = true;

                LabelProcessLegend1.Visibility = Visibility.Hidden;
                LabelProcessLegend2.Visibility = Visibility.Hidden;
            }
            else if (((TreeViewItemExt)source).DataType == MeasurementType.TcBode)
            {
                SetProperties(ListTcBode[((TreeViewItemExt)source).IndexData].ListTcBodeData[((TreeViewItemExt)source).IndexAuxData]);
                ClearCurrentPlot();

                button_SaveData.IsEnabled = false;
                MenuSaveData.IsEnabled = false;
                MenuSaveSettingsData.IsEnabled = false;

                LabelProcessLegend1.Visibility = Visibility.Visible;
                LabelProcessLegend2.Visibility = Visibility.Visible;
            }
            else if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.Asymptote)
            {
                SetProperties(ListAsymptoteProperties[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData]);
            }
                ((TreeViewItem)source).IsSelected = true;

            // code for edit notes - close editing
            if (TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Offline)
            {
                textBox_Notes.IsReadOnly = true;
                textBox_Notes.Background = Brushes.LightGray;
                button_EditNotes.Content = "Edit";
            }

            // Close edit of Asymptote
            PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClickEditAsymp;
            // Cancel new asymptote
            PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClick;
        }

        /* Methods only for Spectral analysis DATA  */

        /// <summary>
        /// Event from change Step TreeView element (Click event)
        /// </summary>Load
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventChangeTreeStepItem(object source, System.Windows.RoutedEventArgs e)
        {
            // ID of curves
            int NumItem = Convert.ToInt32(((CheckBox)source).Name.Substring(17, ((CheckBox)source).Name.Length - 17));

            // index of step response subitems
            int NumSubItem = 0;     // without bode plot
            if (TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexData].Count() > 0)
            {
                NumSubItem = 2;     // with bode plot
            }

            if ((((CheckBox)source).IsChecked == true) && (((CheckBox)source).IsEnabled == true))
            {
                if (((CheckBox)((TreeViewItem)((TreeViewItem)((TreeViewItem)treeViewListCurves.Items[NumItem]).Items[NumSubItem]).Items[1]).Header).IsChecked == true)
                    PlotChartStepResponse.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphOutStepRes].IsVisible = true;
                if (((CheckBox)((TreeViewItem)((TreeViewItem)((TreeViewItem)treeViewListCurves.Items[NumItem]).Items[NumSubItem]).Items[0]).Header).IsChecked == true)
                    PlotChartStepResponse.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphInStepRes].IsVisible = true;

                ((TreeViewItem)((TreeViewItem)((TreeViewItem)treeViewListCurves.Items[NumItem]).Items[NumSubItem]).Items[0]).IsEnabled = true;
                ((TreeViewItem)((TreeViewItem)((TreeViewItem)treeViewListCurves.Items[NumItem]).Items[NumSubItem]).Items[1]).IsEnabled = true;
            }
            else
            {
                PlotChartStepResponse.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphOutStepRes].IsVisible = false;
                PlotChartStepResponse.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphInStepRes].IsVisible = false;

                ((TreeViewItem)((TreeViewItem)((TreeViewItem)treeViewListCurves.Items[NumItem]).Items[NumSubItem]).Items[0]).IsEnabled = false;
                ((TreeViewItem)((TreeViewItem)((TreeViewItem)treeViewListCurves.Items[NumItem]).Items[NumSubItem]).Items[1]).IsEnabled = false;
            }

            PlotChartStepResponse.AxisChange();
            PlotChartStepResponse.Invalidate();
        }

        /// <summary>
        /// Event from change Step response TreeView element (Enabled property changed - event)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventEnabledTreeStepItem(object source, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            System.Windows.RoutedEventArgs EvArg = new RoutedEventArgs();
            eventChangeTreeStepItem(source, EvArg);
        }

        /// <summary>
        /// Event from change In item in Step response TreeView element (Click event)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventChangeTreeStepResInItem(object source, System.Windows.RoutedEventArgs e)
        {
            string strNumItem = ((CheckBox)source).Name.Substring(19, ((CheckBox)source).Name.Length - 19);
            int NumItem = Convert.ToInt32(strNumItem);

            if (((CheckBox)source).IsChecked == true)
            {
                PlotChartStepResponse.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphInStepRes].IsVisible = true;
            }
            else
            {
                PlotChartStepResponse.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphInStepRes].IsVisible = false;
            }

            PlotChartStepResponse.AxisChange();
            PlotChartStepResponse.Invalidate();
        }

        /// <summary>
        /// Event from change Out item in Step response TreeView element (Click event)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventChangeTreeStepResOutItem(object source, System.Windows.RoutedEventArgs e)
        {
            string strNumItem = ((CheckBox)source).Name.Substring(20, ((CheckBox)source).Name.Length - 20);
            int NumItem = Convert.ToInt32(strNumItem);

            if (((CheckBox)source).IsChecked == true)
            {
                PlotChartStepResponse.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphOutStepRes].IsVisible = true;
            }
            else
            {
                PlotChartStepResponse.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphOutStepRes].IsVisible = false;
            }

            PlotChartStepResponse.AxisChange();
            PlotChartStepResponse.Invalidate();
        }

        /// <summary>
        /// Event from change Process TreeView element (Click event)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventChangeTreeProcessItem(object source, System.Windows.RoutedEventArgs e)
        {
                        // ID of curves
                        int NumItem = Convert.ToInt32(((CheckBox)source).Name.Substring(17, ((CheckBox)source).Name.Length - 17));

                        if ((((CheckBox)source).IsChecked == true) && (((CheckBox)source).IsEnabled == true))
                        {
                            PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphProcessMg].IsVisible = true;
                            PlotChartPhase.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphProcessPh].IsVisible = true;
                        }
                        else
                        {
                            PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphProcessMg].IsVisible = false;
                            PlotChartPhase.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[NumItem]).IndexGraphProcessPh].IsVisible = false;
                        }

                        PlotChartMagnitude.AxisChange();
                        PlotChartMagnitude.Invalidate();
                        PlotChartPhase.AxisChange();
                        PlotChartPhase.Invalidate();
        }

        /// <summary>
        /// Event from change Process TreeView element (Enabled property changed - event)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void eventEnabledTreeProcessItem(object source, System.Windows.DependencyPropertyChangedEventArgs e)
        {
                       System.Windows.RoutedEventArgs EvArg = new RoutedEventArgs();
                       eventChangeTreeProcessItem(source, EvArg);
        }

        #endregion

        #region Events from items in Properties

        /// <summary>
        /// Changed selection comboBox_ModeControl - control mode
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox_ModeControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RefreshUnits();
        }

        /// <summary>
        /// Changed selection comboBox_Units - units
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox_Units_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RefreshUnits();
        }

        /// <summary>
        /// Changed count of repeat of identification signal set
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_CountOfRepeat_TextChanged(object sender, TextChangedEventArgs e)
        {
            if((textBox_CountOfRepeat != null) && (textBox_Period != null) && (comboBox_SelectedInputSignal != null) && (textBox_PreTriggerStep != null) && (textBox_TimeStep != null))
                UpdateTimeRunnigProcess(TwinCatExtGen1);
        }

        /// <summary>
        /// Changed period of identification signal
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_Period_LostFocus(object sender, RoutedEventArgs e)
        {
            if ((textBox_CountOfRepeat != null) && (textBox_Period != null) && (comboBox_SelectedInputSignal != null) && (textBox_PreTriggerStep != null) && (textBox_TimeStep != null))
                UpdateTimeRunnigProcess(TwinCatExtGen1);
        }

        /// <summary>
        /// Changed type of identification signal
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox_SelectedInputSignal_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((textBox_CountOfRepeat != null) && (textBox_Period != null) && (comboBox_SelectedInputSignal != null) && (textBox_PreTriggerStep != null) && (textBox_TimeStep != null))
                UpdateTimeRunnigProcess(TwinCatExtGen1);
        }

        /// <summary>
        /// Changed pre-trigger time for step response
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_PreTriggerStep_LostFocus(object sender, RoutedEventArgs e)
        {
            if ((textBox_CountOfRepeat != null) && (textBox_Period != null) && (comboBox_SelectedInputSignal != null) && (textBox_PreTriggerStep != null) && (textBox_TimeStep != null))
                UpdateTimeRunnigProcess(TwinCatExtGen1);
        }

        /// <summary>
        /// Changed duration of step response
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_TimeStep_LostFocus(object sender, RoutedEventArgs e)
        {
            if ((textBox_CountOfRepeat != null) && (textBox_Period != null) && (comboBox_SelectedInputSignal != null) && (textBox_PreTriggerStep != null) && (textBox_TimeStep != null))
                UpdateTimeRunnigProcess(TwinCatExtGen1);
        }

        /// <summary>
        /// Changed type of x-axis - linear
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton_Linear_Checked(object sender, RoutedEventArgs e)
        {
            if (PlotChartMagnitude.GraphPane != null)
            {
                PlotChartMagnitude.GraphPane.XAxis.Type = AxisType.Linear;

                PlotChartMagnitude.AxisChange();
                PlotChartMagnitude.Invalidate();
            }

            if (PlotChartPhase.GraphPane != null)
            {
                PlotChartPhase.GraphPane.XAxis.Type = AxisType.Linear;

                PlotChartPhase.AxisChange();
                PlotChartPhase.Invalidate();
            }

        }

        /// <summary>
        /// Changed type of x-axis - logarithmic
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton_Logaritmic_Checked(object sender, RoutedEventArgs e)
        {
            if (PlotChartMagnitude.GraphPane != null)
            {
                PlotChartMagnitude.GraphPane.XAxis.Type = AxisType.Log;

                PlotChartMagnitude.AxisChange();
                PlotChartMagnitude.Invalidate();
            }

            if (PlotChartPhase.GraphPane != null)
            {
                PlotChartPhase.GraphPane.XAxis.Type = AxisType.Log;

                PlotChartPhase.AxisChange();
                PlotChartPhase.Invalidate();
            }
        }

        /// <summary>
        /// If set value for allowed position range -> enable position range check
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_AllowPositionRange_GotFocus(object sender, RoutedEventArgs e)
        {
            checkBox_EnablePositionRangeCheck.IsChecked = true;
        }

        /// <summary>
        /// If set value for allowed torque range during indentification -> enable torque range check during indetification
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_AllowedTorqueRangeIdent_GotFocus(object sender, RoutedEventArgs e)
        {
            checkBox_EnableTorqueRangeCheckIdent.IsChecked = true;
        }

        /// <summary>
        /// If set value for allowed torque range during step response -> enable torque range check during step response
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_AllowedTorqueRangeStRes_GotFocus(object sender, RoutedEventArgs e)
        {
            checkBox_EnableTorqueRangeCheckStRes.IsChecked = true;
        }

        #region Graph settings       

        /// <summary>
        /// Changed mode of spectral analysis - refresh bode diagram
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxModeAnalysis_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((TreeViewItemExt)treeViewListCurves.SelectedItem) != null)
            {
                if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.SpectAnalysis)
                {
                    RefreshBodePlot(TwinCatExtGen1, ((TreeViewItemExt)treeViewListCurves.SelectedItem).ID);
                }
            }
        }

        /// <summary>
        /// Changed length window for spectral analysis - refresh bode diagram
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_LengthWindow_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (((TreeViewItemExt)treeViewListCurves.SelectedItem) != null)
            {
                if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.SpectAnalysis)
                {
                    try
                    {
                        if (Convert.ToDouble(textBox_LengthWindow.Text) > 10 && Convert.ToDouble(textBox_LengthWindow.Text) <= TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData].LengthInterestData)
                            RefreshBodePlot(TwinCatExtGen1, ((TreeViewItemExt)treeViewListCurves.SelectedItem).ID);
                    }
                    catch 
                    { }
                }
            }
        }

        /// <summary>
        /// Changed check phase overflow - refresh bode diagram
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox_CheckPhaseOwerflow_Click(object sender, RoutedEventArgs e)
        {
            if (((TreeViewItemExt)treeViewListCurves.SelectedItem) != null)
            {
                if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.SpectAnalysis)
                {
                    try
                    {
                        if (Convert.ToDouble(textBox_LengthWindow.Text) > 10 && Convert.ToDouble(textBox_LengthWindow.Text) <= TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData].LengthInterestData)
                            RefreshBodePlot(TwinCatExtGen1, ((TreeViewItemExt)treeViewListCurves.SelectedItem).ID);
                    }
                    catch
                    { }
                }
            }
        }

        /// <summary>
        /// Changed offset for measured I/O data - refresh bode diagram 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_OffsetIOdata_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (((TreeViewItemExt)treeViewListCurves.SelectedItem) != null)
            {
                if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.SpectAnalysis)
                {
                    try
                    {
                        if (Convert.ToDouble(textBox_LengthWindow.Text) > 10 && Convert.ToDouble(textBox_LengthWindow.Text) < TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData].LengthInterestData)
                            RefreshBodePlot(TwinCatExtGen1, ((TreeViewItemExt)treeViewListCurves.SelectedItem).ID);
                    }
                    catch 
                    { }
                }
            }
        }

        /// <summary>
        /// Changed check abs current - refresh current graph
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox_AbsCurrent_Click(object sender, RoutedEventArgs e)
        {
            if (((TreeViewItemExt)treeViewListCurves.SelectedItem) != null)
            {
                if (((TreeViewItemExt)treeViewListCurves.SelectedItem).DataType == MeasurementType.SpectAnalysis)
                {
                    if (TwinCatExtGen1.MeasuredData.Count > ((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData)
                    {
                        ClearCurrentPlot();
                        ShowCurrentAllPlot(TwinCatExtGen1.MeasuredData[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData]);
                    }
                }
            }
        }

        #endregion

        #endregion

        /// <summary>
        /// Application is closed - Disconnect from PLC
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closed(object sender, EventArgs e)
        {
            if (TwinCatExtGen1.GetActStateExtGen != eStateExtGen.Offline)
                TwinCatExtGen1.Disconnect();
        }

        #endregion

        #region Private methods for validation data

        /// <summary>
        /// Allow only positive integers insert to textBoxes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        /// <summary>
        /// Allow only integers insert to textBoxes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NumberIntValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9-]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        /// <summary>
        /// Allow only float nummbers insert to textBoxes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NumberDoubleValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9.-]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        /// <summary>
        /// Allow only positive float nummbers insert to textBoxes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NumberPositiveDoubleValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9.]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        #endregion

        #region Private methods for timer

        /// <summary>
        /// Actual value estimated time of indetification
        /// </summary>
        private ulong EstimatedTimeRunnigProcess = 0;

        /// <summary>
        /// Final estimated time of indetification
        /// </summary>
        private ulong EstimatedTimeRunnigProcessFinish = 0;

        /// <summary>
        /// Tick of timer for progress bar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if(EstimatedTimeRunnigProcess <= 1000000)
            {
                EstimatedTimeRunnigProcess = 0;
                dispatcherTimer.Stop();
                ProcProgressBar.Value = 100;
            }
            else
            {
                EstimatedTimeRunnigProcess -= 1000000;  // -1s
                ProcProgressBar.Value = ((EstimatedTimeRunnigProcessFinish - EstimatedTimeRunnigProcess) * 100.0) / EstimatedTimeRunnigProcessFinish;
            }

            MyTime TimeRunnigProcess = new MyTime(EstimatedTimeRunnigProcess);
            DateTime iTimeToFinish = new DateTime(2000, 1, 1, TimeRunnigProcess.Hour, TimeRunnigProcess.Minutes, TimeRunnigProcess.Secondes);
            if (label_TimeToFinish != null)
            {
                label_TimeToFinish.Content = iTimeToFinish.ToLongTimeString();
            }                
        }

        /// <summary>
        /// Start timer
        /// </summary>
        private void TimerStart()
        {
            UpdateTimeRunnigProcess(TwinCatExtGen1);
            dispatcherTimer.Start();
            ProcProgressBar.Visibility = Visibility.Visible;
            ProcProgressBar.Value = 0;
        }

        /// <summary>
        /// Stop timer
        /// </summary>
        private void TimerStop()
        {
            dispatcherTimer.Stop();
            UpdateTimeRunnigProcess(TwinCatExtGen1);
            ProcProgressBar.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// Update value of timer for progress bar
        /// </summary>
        /// <param name="TcExtGener"></param>
        private void UpdateTimeRunnigProcess(TwinCatExtGen TcExtGener)
        {
            if (TcExtGener.GetActStateExtGen != eStateExtGen.Running)
            {
                // Update sources
                CheckGenerProp();
                CheckTargetProp();
                // Get data from InDataProp(.xaml)
                Binding BindInDataProp = BindingOperations.GetBinding(textBox_AmsNetIdTarget, TextBox.TextProperty);
                DataProperties DataProp = BindInDataProp.Source as DataProperties;

                if (DataProp.IdInputSignal >= 0)
                {
                    int CountSamples = TcExtGener.ListInputIdentSignal[DataProp.IdInputSignal].SignalData.Count;
                    EstimatedTimeRunnigProcess = (Convert.ToUInt64(CountSamples * DataProp.PeriodInputSignal) * DataProp.CountRepeat + Convert.ToUInt64(DataProp.StepTime) + Convert.ToUInt64(DataProp.StepPreTrigger)) * 1000000;//Estimated time for running process in [us]
                    EstimatedTimeRunnigProcessFinish = EstimatedTimeRunnigProcess;

                    MyTime TimeRunnigProcess = new MyTime(EstimatedTimeRunnigProcess);
                    DateTime iTimeToFinish = new DateTime(2000, 1, 1, TimeRunnigProcess.Hour, TimeRunnigProcess.Minutes, TimeRunnigProcess.Secondes);
                    if (label_TimeToFinish != null)
                    {
                        label_TimeToFinish.Content = iTimeToFinish.ToLongTimeString();
                    }
                }
            }
        }

        #endregion

        #region Private methods for graphs

        /// <summary>
        /// Initialization bode diagram graphs
        /// </summary>
        private void InitzedGraphControl_BodePlot()
        {
            // Magnitude chart
            PlotChartMagnitude.GraphPane.XAxis.Type = AxisType.Log;
            PlotChartMagnitude.AxisChange();
            PlotChartMagnitude.GraphPane.Title.Text = "Bode diagram - Magnitude";
            PlotChartMagnitude.GraphPane.XAxis.Title.Text = "f [Hz]";
            PlotChartMagnitude.GraphPane.YAxis.Title.Text = "Magnitude [dB]";
            PlotChartMagnitude.GraphPane.Fill.Color = System.Drawing.Color.LightGray;
            PlotChartMagnitude.GraphPane.Chart.Fill.Color = System.Drawing.Color.White;
            PlotChartMagnitude.GraphPane.XAxis.MajorGrid.IsVisible = true;
            PlotChartMagnitude.GraphPane.XAxis.MinorGrid.IsVisible = true;      
            PlotChartMagnitude.CursorValueEvent += PlotChartMagnitude_CursorValueEvent;
            PlotChartMagnitude.GraphPane.AxisChangeEvent += GraphPane_AxisChangeEventMagnitude;
            PlotChartMagnitude.IsShowCursorValues = true;
            PlotChartMagnitude.GraphPane.YAxis.MajorGrid.IsVisible = true;
            PlotChartMagnitude.GraphPane.Legend.IsVisible = false;

            PlotChartMagnitude.AxisChange();
            PlotChartMagnitude.Invalidate();

            // Phase chart
            PlotChartPhase.GraphPane.XAxis.Type = AxisType.Log;
            PlotChartPhase.GraphPane.Title.Text = "Bode diagram - Phase";
            PlotChartPhase.GraphPane.XAxis.Title.Text = "f [Hz]";
            PlotChartPhase.GraphPane.YAxis.Title.Text = "Phase [°]";
            PlotChartPhase.GraphPane.Fill.Color = System.Drawing.Color.LightGray;
            PlotChartPhase.GraphPane.Chart.Fill.Color = System.Drawing.Color.White;
            PlotChartPhase.GraphPane.XAxis.MajorGrid.IsVisible = true;
            PlotChartPhase.GraphPane.XAxis.MinorGrid.IsVisible = true;
            PlotChartPhase.CursorValueEvent += PlotChartPhase_CursorValueEvent;
            PlotChartPhase.GraphPane.AxisChangeEvent += GraphPane_AxisChangeEventPhase;
            PlotChartPhase.IsShowCursorValues = true;
            PlotChartPhase.GraphPane.YAxis.MajorGrid.IsVisible = true;
            PlotChartPhase.GraphPane.Legend.IsVisible = false;

            PlotChartPhase.AxisChange();
            PlotChartPhase.Invalidate();
        }

        /// <summary>
        /// Changed size of PlotChartMagnitude - set the same size in PlotChartPhase
        /// </summary>
        /// <param name="pane"></param>
        private void GraphPane_AxisChangeEventMagnitude(GraphPane pane)
        {
            PlotChartPhase.GraphPane.AxisChangeEvent -= GraphPane_AxisChangeEventPhase;
            PlotChartPhase.GraphPane.XAxis.Scale.Max = PlotChartMagnitude.GraphPane.XAxis.Scale.Max;
            PlotChartPhase.GraphPane.XAxis.Scale.Min = PlotChartMagnitude.GraphPane.XAxis.Scale.Min;
            PlotChartPhase.Refresh();
            PlotChartPhase.GraphPane.AxisChangeEvent += GraphPane_AxisChangeEventPhase;
        }

        /// <summary>
        /// Changed size of PlotChartPhase - set the same size in PlotChartMagnitude
        /// </summary>
        /// <param name="pane"></param>
        private void GraphPane_AxisChangeEventPhase(GraphPane pane)
        {
            PlotChartMagnitude.GraphPane.AxisChangeEvent -= GraphPane_AxisChangeEventMagnitude;
            PlotChartMagnitude.GraphPane.XAxis.Scale.Max = PlotChartPhase.GraphPane.XAxis.Scale.Max;
            PlotChartMagnitude.GraphPane.XAxis.Scale.Min = PlotChartPhase.GraphPane.XAxis.Scale.Min;
            PlotChartMagnitude.Refresh();
            PlotChartMagnitude.GraphPane.AxisChangeEvent += GraphPane_AxisChangeEventMagnitude;
        }

        /// <summary>
        /// Mouse click on PlotChartMagnitude - add asymptote
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PlotChartMagnitude_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            
            if (PropertiesAsymptote.Visibility == Visibility.Visible)
            {
                // update and check sources
                BindingExpression BindExpr1 = textBox_SlopeOfDecade.GetBindingExpression(TextBox.TextProperty);
                BindExpr1.UpdateSource();
                BindingExpression BindExpr2 = comboBox_AsymptoteColor.GetBindingExpression(ComboBox.SelectedIndexProperty);
                BindExpr2.UpdateSource();

                if ((!BindExpr1.HasError) && (!BindExpr2.HasError))
                {
                    AsymptoteProperties AsymProp = new AsymptoteProperties();

                    Binding BindInDataProp = BindingOperations.GetBinding(textBox_SlopeOfDecade, TextBox.TextProperty);

                    AsymptoteProperties AsymPropGui = BindInDataProp.Source as AsymptoteProperties;

                    AsymProp.Color = AsymPropGui.Color;
                    AsymProp.Slope = AsymPropGui.Slope;
                    AsymProp.mousePt.X = e.X;
                    AsymProp.mousePt.Y = e.Y;

                    ListAsymptoteProperties.Add(AsymProp);

                    AddCurveMd(ListAsymptoteProperties);

                    textBox_SlopeOfDecade.IsReadOnly = true;
                    textBox_SlopeOfDecade.Background = Brushes.LightGray;
                    comboBox_AsymptoteColor.IsEnabled = false;
                    comboBox_AsymptoteColor.Background = Brushes.LightGray;
                    PlotChartMagnitude.MouseClick -= PlotChartMagnitude_MouseClick;
                    button_EditAsymptote.Content = "Edit";
                    button_DeleteAllCurve.IsEnabled = true;
                    MenuDeleteAll.IsEnabled = true;
                }
            }
        }

        /// <summary>
        /// Mouse click on PlotChartMagnitude - edit asymptote
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PlotChartMagnitude_MouseClickEditAsymp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (PropertiesAsymptote.Visibility == Visibility.Visible)
            {
                // update and check sources
                BindingExpression BindExpr1 = textBox_SlopeOfDecade.GetBindingExpression(TextBox.TextProperty);
                BindExpr1.UpdateSource();
                BindingExpression BindExpr2 = comboBox_AsymptoteColor.GetBindingExpression(ComboBox.SelectedIndexProperty);
                BindExpr2.UpdateSource();

                if ((!BindExpr1.HasError) && (!BindExpr2.HasError))
                {
                    Binding BindInDataProp = BindingOperations.GetBinding(textBox_SlopeOfDecade, TextBox.TextProperty);

                    AsymptoteProperties AsymProp = new AsymptoteProperties();
                    AsymptoteProperties LoadedProp = BindInDataProp.Source as AsymptoteProperties;
                    AsymProp.Color = LoadedProp.Color;
                    AsymProp.Slope = LoadedProp.Slope;
                    AsymProp.mousePt.X = e.X;
                    AsymProp.mousePt.Y = e.Y;

                    ListAsymptoteProperties[((TreeViewItemExt)treeViewListCurves.SelectedItem).IndexData] = AsymProp;

                    RefreshCurveMd(ListAsymptoteProperties, ((TreeViewItemExt)treeViewListCurves.SelectedItem));
                }
            }
        }

        /// <summary>
        /// Show cursor value in PlotChartMagnitude
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pane"></param>
        /// <param name="mousePt"></param>
        /// <returns></returns>
        private string PlotChartMagnitude_CursorValueEvent(ZedGraphControl sender, GraphPane pane, System.Drawing.Point mousePt)
        {
            double x, y;

            pane.ReverseTransform(mousePt, out x, out y);

            return "(f: " + x.ToString("f3", CultureInfo.InvariantCulture) + "[Hz], Mag: " + y.ToString("f3", CultureInfo.InvariantCulture) + "[dB])";

        }

        /// <summary>
        /// Show cursor value in PlotChartPhase
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pane"></param>
        /// <param name="mousePt"></param>
        /// <returns></returns>
        private string PlotChartPhase_CursorValueEvent(ZedGraphControl sender, GraphPane pane, System.Drawing.Point mousePt)
        {
            double x, y;

            pane.ReverseTransform(mousePt, out x, out y);

            return "(f: " + x.ToString("f3", CultureInfo.InvariantCulture) + "[Hz], Phase: " + y.ToString("f3", CultureInfo.InvariantCulture) + "[°])";

        }

        /// <summary>
        /// Add asymptote in PlotChartMagnitude
        /// </summary>
        /// <param name="AsymProp"> Properties of asymptote </param>
        /// <param name="TreeViewIt"> Corresponding TreeViewItem </param>
        private void AddAsymptote(AsymptoteProperties AsymProp, TreeViewItemExt TreeViewIt)
        {
            // x & y variables to store the axis values
            double xVal;
            double yVal;

            double SlopeInDecade = AsymProp.Slope;        

            // Clear the previous values if any
            LineItem UserCurve = new LineItem("userClickCurve");
            PointPairList userClickrList = new PointPairList();

            // Use the current mouse locations to get the corresponding 
            // X & Y CO-Ordinates
            PlotChartMagnitude.GraphPane.ReverseTransform(AsymProp.mousePt, out xVal, out yVal);

            // Create a list using the above x & y values
            userClickrList.Add(PlotChartMagnitude.GraphPane.XAxis.Scale.Min, yVal + SlopeInDecade * Math.Log10(PlotChartMagnitude.GraphPane.XAxis.Scale.Min / xVal));
            userClickrList.Add(PlotChartMagnitude.GraphPane.XAxis.Scale.Max, yVal + SlopeInDecade * Math.Log10(PlotChartMagnitude.GraphPane.XAxis.Scale.Max / xVal));

            // Add a curve
            UserCurve = PlotChartMagnitude.GraphPane.AddCurve(" ", userClickrList, WpfBrushToDrawingColor(IntToColor(AsymProp.Color)), SymbolType.None);
            UserCurve.Line.Width = 2;

            TreeViewIt.IndexGraphClosedLoopMg = PlotChartMagnitude.GraphPane.CurveList.Count - 1;

            PlotChartMagnitude.Refresh();
        }

        /// <summary>
        /// Refresh asymptote in PlotChartMagnitude with new settings
        /// </summary>
        /// <param name="AsymProp"> Properties of asymptote </param>
        /// <param name="TreeViewIt"> Corresponding TreeViewItem </param>
        private void RefreshAsymptote(AsymptoteProperties AsymProp, TreeViewItemExt TreeViewIt)
        {
            // x & y variables to store the axis values
            double xVal;
            double yVal;

            double SlopeInDecade = AsymProp.Slope;

            // Use the current mouse locations to get the corresponding 
            // X & Y CO-Ordinates
            PlotChartMagnitude.GraphPane.ReverseTransform(AsymProp.mousePt, out xVal, out yVal);

            // Get old curve
            LineItem curveMagnitudeFw = PlotChartMagnitude.GraphPane.CurveList[TreeViewIt.IndexGraphClosedLoopMg] as LineItem;
            // Clear old curve
            PointPairList listMagnitudeFw = curveMagnitudeFw.Points as PointPairList;
            listMagnitudeFw.Clear();

            // Create a list using the above x & y values
            listMagnitudeFw.Add(PlotChartMagnitude.GraphPane.XAxis.Scale.Min, yVal + SlopeInDecade * Math.Log10(PlotChartMagnitude.GraphPane.XAxis.Scale.Min / xVal));
            listMagnitudeFw.Add(PlotChartMagnitude.GraphPane.XAxis.Scale.Max, yVal + SlopeInDecade * Math.Log10(PlotChartMagnitude.GraphPane.XAxis.Scale.Max / xVal));
            curveMagnitudeFw.Color = WpfBrushToDrawingColor(IntToColor(AsymProp.Color));

            PlotChartMagnitude.AxisChange();
            PlotChartMagnitude.Invalidate();

        }

        /// <summary>
        /// Initialization of current graph
        /// </summary>
        private void InitzedGraphControl_CurrentPlot()
        {
            //Current chart
            PlotChartCurrent.GraphPane.XAxis.Type = AxisType.Linear;

            PointPairList listCurrent = new PointPairList();

            LineItem curveCurrent = PlotChartCurrent.GraphPane.AddCurve("Current", listCurrent, System.Drawing.Color.Blue, SymbolType.Circle);
            curveCurrent.Symbol.Fill = new Fill(System.Drawing.Color.Black);
            curveCurrent.Symbol.Size = 3;

            PlotChartCurrent.GraphPane.Title.Text = "Current";
            PlotChartCurrent.GraphPane.XAxis.Title.Text = "t [s]";
            PlotChartCurrent.GraphPane.YAxis.Title.Text = "I [%]";
            PlotChartCurrent.GraphPane.Fill.Color = System.Drawing.Color.LightGray;
            PlotChartCurrent.GraphPane.Chart.Fill.Color = System.Drawing.Color.White;
            PlotChartCurrent.GraphPane.XAxis.MajorGrid.IsVisible = true;
            PlotChartCurrent.GraphPane.YAxis.MajorGrid.IsVisible = true;

            PlotChartCurrent.AxisChange();
            PlotChartCurrent.Invalidate();
        }

        /// <summary>
        /// Initialization of step response graph
        /// </summary>
        private void InitzedGraphControl_StepResponse()
        {
            // Step response chart
            PlotChartStepResponse.GraphPane.XAxis.Type = AxisType.Linear;

            PlotChartStepResponse.GraphPane.Title.Text = "Step response";
            PlotChartStepResponse.GraphPane.XAxis.Title.Text = "t [s]";
            PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [-]";
            PlotChartStepResponse.GraphPane.Fill.Color = System.Drawing.Color.LightGray;
            PlotChartStepResponse.GraphPane.Chart.Fill.Color = System.Drawing.Color.White;
            PlotChartStepResponse.GraphPane.XAxis.MajorGrid.IsVisible = true;
            PlotChartStepResponse.GraphPane.YAxis.MajorGrid.IsVisible = true;
            PlotChartStepResponse.GraphPane.Legend.IsVisible = false;

            PlotChartStepResponse.AxisChange();
            PlotChartStepResponse.Invalidate();
        }

        /// <summary>
        /// Show current values in PlotChartCurrent - maximum last 10000 values
        /// </summary>
        /// <param name="ReadDataTwinCAT"></param>
        private void ShowCurrentPlot(MeasureData ReadDataTwinCAT)
        {
            if (TwinCatExtGen1.GetActStateExtGen != eStateExtGen.Running)
                return;

            int NumSamples = 10000;
            double[] timeCurrentAxis = new double[NumSamples];
            for (int i = 0; i < NumSamples; i++)
            {
                timeCurrentAxis[i] = ReadDataTwinCAT.TaskTime * i;
            }

            // Get the first CurveItem in the graph
            LineItem curveCurrent = PlotChartCurrent.GraphPane.CurveList[0] as LineItem;

            // Get the PointPairList
            PointPairList listCurrent = curveCurrent.Points as PointPairList;
            listCurrent.Clear();

            if (ReadDataTwinCAT.iCurrentValue.Count >= NumSamples)
            {
                // actual current values
                ReadDataTwinCAT.PostionCurrent = ReadDataTwinCAT.iCurrentValue.Count - NumSamples; // set to NumSamples samples before end of list current values
                for (int i = 0; i < NumSamples; i++)
                {
                    if (checkBox_AbsCurrent.IsChecked == true)
                    {
                        listCurrent.Add(timeCurrentAxis[i], Math.Abs(ReadDataTwinCAT.GetCurrentValue() / 10));
                    }
                    else
                    {
                        listCurrent.Add(timeCurrentAxis[i], ReadDataTwinCAT.GetCurrentValue() / 10);
                    }
                }
            }
            else
            {
                int i;
                // actual current values
                ReadDataTwinCAT.PostionCurrent = 0; // set to NumSamples samples before end of list current values
                for (i = 0; i < ReadDataTwinCAT.iCurrentValue.Count; i++)
                {
                    if (checkBox_AbsCurrent.IsChecked == true)
                    {
                        listCurrent.Add(timeCurrentAxis[i], Math.Abs(ReadDataTwinCAT.GetCurrentValue() / 10));
                    }
                    else
                    {
                        listCurrent.Add(timeCurrentAxis[i], ReadDataTwinCAT.GetCurrentValue() / 10);
                    }
                }
                // zeros values
                for (int j = i; j < NumSamples - ReadDataTwinCAT.iCurrentValue.Count; j++)
                {
                    listCurrent.Add(timeCurrentAxis[j], 0);
                }
            }

            PlotChartCurrent.AxisChange();
            PlotChartCurrent.Invalidate();

        }

        /// <summary>
        /// Show current values in PlotChartCurrent - all values
        /// </summary>
        /// <param name="ReadDataTwinCAT"></param>
        private void ShowCurrentAllPlot(MeasureData ReadDataTwinCAT)
        {


            int NumSamples = ReadDataTwinCAT.iCurrentValue.Count;
            double[] timeCurrentAxis = new double[NumSamples];
            double[] CurrentValues = new double[NumSamples];
            for (int i = 0; i < NumSamples; i++)
            {
                timeCurrentAxis[i] = ReadDataTwinCAT.TaskTime * i;
            }

            // Get the first CurveItem in the graph
            LineItem curveCurrent = PlotChartCurrent.GraphPane.CurveList[0] as LineItem;

            // Get the PointPairList
            PointPairList listCurrent = curveCurrent.Points as PointPairList;
            listCurrent.Clear();

            // actual current values
            ReadDataTwinCAT.PostionCurrent = 0; // set to the beginning
            for (int i = 0; i < NumSamples; i++)
            {
                if (checkBox_AbsCurrent.IsChecked == true)
                {
                    CurrentValues[i] = Math.Abs(ReadDataTwinCAT.GetCurrentValue() / 10);
                    listCurrent.Add(timeCurrentAxis[i], CurrentValues[i]);                    
                }
                else
                {
                    CurrentValues[i] = ReadDataTwinCAT.GetCurrentValue() / 10;
                    listCurrent.Add(timeCurrentAxis[i], CurrentValues[i]);
                    CurrentValues[i] = Math.Abs(CurrentValues[i]);
                }
            }

            textBox_AverageCurrent.Text = CurrentValues.Average().ToString("F4", CultureInfo.InvariantCulture) ;

            PlotChartCurrent.AxisChange();
            PlotChartCurrent.Invalidate();
            PlotChartCurrent.Refresh();
            PlotChartCurrent.AxisChange();
        }

        /// <summary>
        /// Clear current plot 
        /// </summary>
        private void ClearCurrentPlot()
        {
            // Get the first CurveItem in the graph
            LineItem curveCurrent = PlotChartCurrent.GraphPane.CurveList[0] as LineItem;

            // Get the PointPairList
            PointPairList listCurrent = curveCurrent.Points as PointPairList;
            listCurrent.Clear();

            textBox_AverageCurrent.Text = "";

            PlotChartCurrent.AxisChange();
            PlotChartCurrent.Invalidate();
        }

        /// <summary>
        /// Convert System.Windows.Media.SolidcolorBrush to System.Drawing.Color
        /// </summary>
        /// <param name="br"></param>
        /// <returns></returns>
        private System.Drawing.Color WpfBrushToDrawingColor(System.Windows.Media.SolidColorBrush br)
        {
            return System.Drawing.Color.FromArgb(
                br.Color.A,
                br.Color.R,
                br.Color.G,
                br.Color.B);
        }

        /// <summary>
        /// Add curve to graph of bode plot
        /// </summary>
        /// <param name="ReadDataTwinCAT"> Measured data to bode plot </param>
        /// <param name="treeItem"> TreeViewItem corresponding to ReadDataTwinCAT </param>
        private void AddBodePlot(MeasureData ReadDataTwinCAT, TreeViewItemExt treeItem)
        {
            if (ReadDataTwinCAT.Count() > 0)
            {
                SpectralAnalys SpectAnalys = new SpectralAnalys();

                if (TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Online || TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Running)
                    TwinCatExtGen1.DisableTimeout();        // Disable check timeout - SpectAnalys.Compute is time consuming method
                SpectAnalys.Compute(ReadDataTwinCAT);   // Compute Bode Plot
                if (TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Online || TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Running)
                    TwinCatExtGen1.EnableTimeout();         // Enable check timeout

                //Magnitude
                PointPairList listMagnitudeFw = new PointPairList();
                PointPairList listMagnitudeF0 = new PointPairList();

                LineItem curveMagnitudeFw = PlotChartMagnitude.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- closed loop", listMagnitudeFw, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphClosedLoopMg = PlotChartMagnitude.GraphPane.CurveList.Count - 1;
                curveMagnitudeFw.Symbol.IsVisible = false;
                curveMagnitudeFw.Line.Width = 2;
                LineItem curveMagnitudeF0 = PlotChartMagnitude.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- open loop", listMagnitudeF0, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphOpenLoopMg = PlotChartMagnitude.GraphPane.CurveList.Count- 1;
                curveMagnitudeF0.Symbol.Fill = new Fill(System.Drawing.Color.Black);
                curveMagnitudeF0.Symbol.IsVisible = false;
                curveMagnitudeF0.Line.Style = System.Drawing.Drawing2D.DashStyle.Dot;
                curveMagnitudeF0.Line.Width = 2;

                //Phase chart
                PointPairList listPhaseFw = new PointPairList();
                PointPairList listPhaseF0 = new PointPairList();

                LineItem curvePhaseFw = PlotChartPhase.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- closed loop", listPhaseFw, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphClosedLoopPh = PlotChartPhase.GraphPane.CurveList.Count - 1;
                curvePhaseFw.Symbol.IsVisible = false;
                curvePhaseFw.Line.Width = 2;
                LineItem curvePhaseF0 = PlotChartPhase.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- open loop", listPhaseF0, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphOpenLoopPh = PlotChartPhase.GraphPane.CurveList.Count - 1;
                curvePhaseF0.Symbol.Fill = new Fill(System.Drawing.Color.Black);
                curvePhaseF0.Symbol.IsVisible = false;
                curvePhaseF0.Line.Style = System.Drawing.Drawing2D.DashStyle.Dot;
                curvePhaseF0.Line.Width = 2;


                // Get the PointPairList
                listMagnitudeFw = curveMagnitudeFw.Points as PointPairList;
                listMagnitudeF0 = curveMagnitudeF0.Points as PointPairList;
                listPhaseFw = curvePhaseFw.Points as PointPairList;
                listPhaseF0 = curvePhaseF0.Points as PointPairList;
                for (int i = 0; i < SpectAnalys.FrequencyAxis.Length; i++)
                {
                    listMagnitudeFw.Add(SpectAnalys.FrequencyAxis[i], SpectAnalys.MagnitudeFw[i]);
                    listMagnitudeF0.Add(SpectAnalys.FrequencyAxis[i], SpectAnalys.MagnitudeF0[i]);
                    listPhaseFw.Add(SpectAnalys.FrequencyAxis[i], SpectAnalys.PhaseFw[i]);
                    listPhaseF0.Add(SpectAnalys.FrequencyAxis[i], SpectAnalys.PhaseF0[i]);
                }

                PlotChartMagnitude.AxisChange();
                PlotChartMagnitude.Invalidate();

                PlotChartPhase.AxisChange();
                PlotChartPhase.Invalidate();

                LabelProcessLegend1.Visibility = Visibility.Hidden;
                LabelProcessLegend2.Visibility = Visibility.Hidden;           
            }          
        }

        /// <summary>
        /// Add curve to graph of bode plot
        /// </summary>
        /// <param name="ReadDataTwinCAT"> Measured data to bode plot </param>
        /// <param name="treeItem"> TreeViewItem corresponding to ReadDataTwinCAT </param>
        private void AddBodePlot(TcBodeData ReadDataTwinCAT, TreeViewItemExt treeItem)
        {
            if (ReadDataTwinCAT.CloseLoopGain.Count > 0)
            {                
                //Magnitude
                PointPairList listMagnitudeFw = new PointPairList();
                PointPairList listMagnitudeF0 = new PointPairList();
                PointPairList listMagnitudePr = new PointPairList();

                LineItem curveMagnitudeFw = PlotChartMagnitude.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- closed loop", listMagnitudeFw, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphClosedLoopMg = PlotChartMagnitude.GraphPane.CurveList.Count - 1;
                curveMagnitudeFw.Symbol.IsVisible = false;
                curveMagnitudeFw.Line.Width = 2;
                LineItem curveMagnitudeF0 = PlotChartMagnitude.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- open loop", listMagnitudeF0, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphOpenLoopMg = PlotChartMagnitude.GraphPane.CurveList.Count - 1;
                curveMagnitudeF0.Symbol.Fill = new Fill(System.Drawing.Color.Black);
                curveMagnitudeF0.Symbol.IsVisible = false;
                curveMagnitudeF0.Line.Style = System.Drawing.Drawing2D.DashStyle.Dot;
                curveMagnitudeF0.Line.Width = 2;
                LineItem curveMagnitudePr = PlotChartMagnitude.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- process", listMagnitudePr, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphProcessMg = PlotChartMagnitude.GraphPane.CurveList.Count - 1;
                curveMagnitudePr.Symbol.Fill = new Fill(System.Drawing.Color.Black);
                curveMagnitudePr.Symbol.IsVisible = false;
                curveMagnitudePr.Line.Style = System.Drawing.Drawing2D.DashStyle.Dash;
                curveMagnitudePr.Line.Width = 2;

                //Phase chart
                PointPairList listPhaseFw = new PointPairList();
                PointPairList listPhaseF0 = new PointPairList();
                PointPairList listPhasePr = new PointPairList();

                LineItem curvePhaseFw = PlotChartPhase.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- closed loop", listPhaseFw, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphClosedLoopPh = PlotChartPhase.GraphPane.CurveList.Count - 1;
                curvePhaseFw.Symbol.IsVisible = false;
                curvePhaseFw.Line.Width = 2;
                LineItem curvePhaseF0 = PlotChartPhase.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- open loop", listPhaseF0, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphOpenLoopPh = PlotChartPhase.GraphPane.CurveList.Count - 1;
                curvePhaseF0.Symbol.Fill = new Fill(System.Drawing.Color.Black);
                curvePhaseF0.Symbol.IsVisible = false;
                curvePhaseF0.Line.Style = System.Drawing.Drawing2D.DashStyle.Dot;
                curvePhaseF0.Line.Width = 2;
                LineItem curvePhasePr = PlotChartPhase.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- process", listPhasePr, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphProcessPh = PlotChartPhase.GraphPane.CurveList.Count - 1;
                curvePhasePr.Symbol.Fill = new Fill(System.Drawing.Color.Black);
                curvePhasePr.Symbol.IsVisible = false;
                curvePhasePr.Line.Style = System.Drawing.Drawing2D.DashStyle.Dash;
                curvePhasePr.Line.Width = 2;


                // Get the PointPairList
                listMagnitudeFw = curveMagnitudeFw.Points as PointPairList;
                listMagnitudeF0 = curveMagnitudeF0.Points as PointPairList;
                listMagnitudePr = curveMagnitudePr.Points as PointPairList;
                listPhaseFw = curvePhaseFw.Points as PointPairList;
                listPhaseF0 = curvePhaseF0.Points as PointPairList;
                listPhasePr = curvePhasePr.Points as PointPairList;
                for (int i = 0; i < ReadDataTwinCAT.CloseLoopGain.Count; i++)
                {
                    listMagnitudeFw.Add(ReadDataTwinCAT.Frequency[i], ReadDataTwinCAT.CloseLoopGain[i]);
                    listMagnitudeF0.Add(ReadDataTwinCAT.Frequency[i], ReadDataTwinCAT.OpenLoopGain[i]);
                    listMagnitudePr.Add(ReadDataTwinCAT.Frequency[i], ReadDataTwinCAT.ProcessGain[i]);
                    listPhaseFw.Add(ReadDataTwinCAT.Frequency[i], ReadDataTwinCAT.CloseLoopPhase[i]);
                    listPhaseF0.Add(ReadDataTwinCAT.Frequency[i], ReadDataTwinCAT.OpenLoopPhase[i]);
                    listPhasePr.Add(ReadDataTwinCAT.Frequency[i], ReadDataTwinCAT.ProcessPhase[i]);
                }
                
                PlotChartMagnitude.AxisChange();
                PlotChartMagnitude.Invalidate();

                PlotChartPhase.AxisChange();
                PlotChartPhase.Invalidate();

                LabelProcessLegend1.Visibility = Visibility.Visible;
                LabelProcessLegend2.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// Refresh bode diagram (magnitude and phase)
        /// </summary>
        /// <param name="DataTwinCAT"></param>
        /// <param name="SelcID"></param>
        private void RefreshBodePlot(TwinCatExtGen DataTwinCAT, int SelcID)
        {
            // refresh parameters for spectral analysis
            DataTwinCAT.MeasuredData[((TreeViewItemExt)treeViewListCurves.Items[SelcID]).IndexData].LengthWindow = Convert.ToInt32(textBox_LengthWindow.Text);
            DataTwinCAT.MeasuredData[((TreeViewItemExt)treeViewListCurves.Items[SelcID]).IndexData].ModeSpectAnalys = (eModeAnalysis)comboBoxModeAnalysis.SelectedItem;
            DataTwinCAT.MeasuredData[((TreeViewItemExt)treeViewListCurves.Items[SelcID]).IndexData].CheckPhaseOverflow = (bool)checkBox_CheckPhaseOwerflow.IsChecked;
            DataTwinCAT.MeasuredData[((TreeViewItemExt)treeViewListCurves.Items[SelcID]).IndexData].OffsetIOdata = Convert.ToInt32(textBox_OffsetIOdata.Text);

            // Get appropriate data set from TwinCatExtGen.MeasureData list for actual selected curves
            MeasureData ReadDataTwinCAT = DataTwinCAT.MeasuredData[((TreeViewItemExt)treeViewListCurves.Items[SelcID]).IndexData];

            if (ReadDataTwinCAT.Count() > 0)
            {
                SpectralAnalys SpectAnalys = new SpectralAnalys();

                if (TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Online || TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Running)
                    TwinCatExtGen1.DisableTimeout();        // Disable check timeout - SpectAnalys.Compute is time consuming method
                SpectAnalys.Compute(ReadDataTwinCAT);   // Compute Bode Plot
                if (TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Online || TwinCatExtGen1.GetActStateExtGen == eStateExtGen.Running)
                    TwinCatExtGen1.EnableTimeout();         // Enable check timeout

                //Magnitude
                LineItem curveMagnitudeFw = PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[SelcID]).IndexGraphClosedLoopMg] as LineItem;
                LineItem curveMagnitudeF0 = PlotChartMagnitude.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[SelcID]).IndexGraphOpenLoopMg] as LineItem;

                PointPairList listMagnitudeFw = curveMagnitudeFw.Points as PointPairList;
                listMagnitudeFw.Clear();
                PointPairList listMagnitudeF0 = curveMagnitudeF0.Points as PointPairList;
                listMagnitudeF0.Clear();

                //Phase chart
                LineItem curvePhaseFw = PlotChartPhase.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[SelcID]).IndexGraphClosedLoopPh] as LineItem;
                LineItem curvePhaseF0 = PlotChartPhase.GraphPane.CurveList[((TreeViewItemExt)treeViewListCurves.Items[SelcID]).IndexGraphOpenLoopPh] as LineItem;

                PointPairList listPhaseFw = curvePhaseFw.Points as PointPairList;
                listPhaseFw.Clear();
                PointPairList listPhaseF0 = curvePhaseF0.Points as PointPairList;
                listPhaseF0.Clear();

                for (int i = 0; i < SpectAnalys.FrequencyAxis.Length; i++)
                {
                    listMagnitudeFw.Add(SpectAnalys.FrequencyAxis[i], SpectAnalys.MagnitudeFw[i]);
                    listMagnitudeF0.Add(SpectAnalys.FrequencyAxis[i], SpectAnalys.MagnitudeF0[i]);
                    listPhaseFw.Add(SpectAnalys.FrequencyAxis[i], SpectAnalys.PhaseFw[i]);
                    listPhaseF0.Add(SpectAnalys.FrequencyAxis[i], SpectAnalys.PhaseF0[i]);
                }

                PlotChartMagnitude.AxisChange();
                PlotChartMagnitude.Invalidate();

                PlotChartPhase.AxisChange();
                PlotChartPhase.Invalidate();
            }
        }

        /// <summary>
        /// Add curve to graph of Step response plot
        /// </summary>
        /// <param name="ReadDataTwinCAT"> Measured data to bode plot </param>
        /// <param name="treeItem"> TreeViewItem corresponding to ReadDataTwinCAT </param>
        private void AddStepResPlot(MeasureData ReadDataTwinCAT, TreeViewItemExt treeItem)
        {
            if (ReadDataTwinCAT.CountStepRes() > 0)
            {
                PointPairList listStepResOut = new PointPairList();
                PointPairList listStepResIn = new PointPairList();

                LineItem curveStepResOut = PlotChartStepResponse.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- step response - Out", listStepResOut, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphOutStepRes = PlotChartStepResponse.GraphPane.CurveList.Count - 1;
                curveStepResOut.Symbol.IsVisible = false;
                curveStepResOut.Line.Width = 2;

                LineItem curveStepResIn = PlotChartStepResponse.GraphPane.AddCurve(ReadDataTwinCAT.ID.ToString() + "- step response - In", listStepResIn, WpfBrushToDrawingColor(IntToColor(ReadDataTwinCAT.ID)), SymbolType.Circle);
                treeItem.IndexGraphInStepRes = PlotChartStepResponse.GraphPane.CurveList.Count - 1;
                curveStepResIn.Symbol.IsVisible = false;
                curveStepResIn.Line.Width = 2;
                curveStepResIn.Line.Style = System.Drawing.Drawing2D.DashStyle.Dot;

                // Get the PointPairList
                listStepResOut = curveStepResOut.Points as PointPairList;
                listStepResIn = curveStepResIn.Points as PointPairList;

                double[] TimeAxis = ReadDataTwinCAT.GetStepResTimeAxis();
                ReadDataTwinCAT.PositionStepRes = 0;
                for (int i = 0; i < ReadDataTwinCAT.CountStepRes(); i++)
                {
                    MData tempData = ReadDataTwinCAT.GetStepResValue();
                    listStepResOut.Add(TimeAxis[i], tempData.FeedbackValue * ReadDataTwinCAT.GetScale());
                    listStepResIn.Add(TimeAxis[i], tempData.CommandValue * ReadDataTwinCAT.GetScale());
                }

                PlotChartStepResponse.AxisChange();
                PlotChartStepResponse.Invalidate();
            }
        }

        #endregion

        #region Private methods for Properties

        /// <summary>
        /// Set Properties window according to DataProperties
        /// </summary>
        /// <param name="iDataIdent"></param>
        private void SetProperties(DataProperties iDataIdent)
        {
            PropertiesGrid.Visibility = Visibility.Visible;
            PropertiesTcBodeGrid.Visibility = Visibility.Hidden;
            PropertiesAsymptote.Visibility = Visibility.Hidden;

            textBox_AmsNetIdTarget.Text = iDataIdent.AmsNetId;
            textBox_AdsPort.Text = iDataIdent.sAdsPort;
            textBox_ExternGenerator.Text = iDataIdent.PathExtGen;
            textBox_TaskTime.Text = iDataIdent.sTaskTime;
            textBox_NameAxis.Text = iDataIdent.NameAxis;
            comboBox_Units.SelectedIndex = iDataIdent.intUnits;
            checkBox_IsLinear.IsChecked = iDataIdent.IsLinear;
            textBox_xScale.Text = iDataIdent.sxScale;
            textBox_vScale.Text = iDataIdent.svScale;
            textBox_FeedConstant.Text = iDataIdent.sFeedConstant;
            textBox_Date.Text = iDataIdent.sDateTime;
            textBox_CountOfRepeat.Text = iDataIdent.sCountRepeat;
            textBox_Period.Text = iDataIdent.sPeriodInputSignal;
            textBox_Amplitude.Text = iDataIdent.sAmplitudeInputSignal;
            textBox_AmplitudeAuxMove.Text = iDataIdent.sAmplAuxMove;
            textBox_FrequencyAuxMove.Text = iDataIdent.sFreqAuxMove;
            comboBox_ModeControl.SelectedIndex = iDataIdent.intControlMode;
            comboBox_SelectedInputSignal.SelectedIndex = iDataIdent.IdInputSignal;
            textBox_PreTriggerStep.Text = iDataIdent.sStepPreTrigger;
            textBox_TimeStep.Text = iDataIdent.sStepTime;
            textBox_InitLevelStep.Text = iDataIdent.sStepInitLevel;
            textBox_FinalLevelStep.Text = iDataIdent.sStepFinalLevel;
            textBox_AllowPositionRange.Text = iDataIdent.sAllowedPositionRange;
            checkBox_EnablePositionRangeCheck.IsChecked = iDataIdent.EnablePositionRangeCheck;
            textBox_AllowedTorqueRangeIdent.Text = iDataIdent.sAllowedTorqueRangeIdent;
            checkBox_EnableTorqueRangeCheckIdent.IsChecked = iDataIdent.EnableTorqueRangeCheckIdent;
            textBox_AllowedTorqueRangeStRes.Text = iDataIdent.sAllowedTorqueRangeStRes;
            checkBox_EnableTorqueRangeCheckStRes.IsChecked = iDataIdent.EnableTorqueRangeCheckStRes;
            comboBoxModeAnalysis.SelectionChanged -= comboBoxModeAnalysis_SelectionChanged; // protection against useless event - it caused problems
            comboBoxModeAnalysis.SelectedIndex = iDataIdent.intModeSpectAnalys;
            comboBoxModeAnalysis.SelectionChanged += comboBoxModeAnalysis_SelectionChanged;
            textBox_LengthWindow.TextChanged -= textBox_LengthWindow_TextChanged;   // protection against useless event - it caused problems
            textBox_LengthWindow.Text = iDataIdent.sLengthWindow;
            textBox_LengthWindow.TextChanged += textBox_LengthWindow_TextChanged;
            checkBox_CheckPhaseOwerflow.Click -= checkBox_CheckPhaseOwerflow_Click;     // protection against useless event - it caused problems
            checkBox_CheckPhaseOwerflow.IsChecked = iDataIdent.CheckPhaseOverflow;
            checkBox_CheckPhaseOwerflow.Click += checkBox_CheckPhaseOwerflow_Click;
            textBox_OffsetIOdata.TextChanged -= textBox_OffsetIOdata_TextChanged;   // protection against useless event - it caused problems
            textBox_OffsetIOdata.Text = iDataIdent.sOffsetIOdata;
            textBox_OffsetIOdata.TextChanged += textBox_OffsetIOdata_TextChanged;
            textBox_Notes.Text = iDataIdent.Notes;            
        }

        /// <summary>
        /// Set Properties window according to TcBodeData
        /// </summary>
        /// <param name="iDataIdent"></param>
        private void SetProperties(TcBodeData iDataIdent)
        {
            PropertiesGrid.Visibility = Visibility.Hidden;
            PropertiesAsymptote.Visibility = Visibility.Hidden;
            PropertiesTcBodeGrid.Visibility = Visibility.Visible;

            DataContext = iDataIdent;
        }

        /// <summary>
        /// Set Properties window according to TcBodeData
        /// </summary>
        /// <param name="AsymptoteProper"></param>
        private void SetProperties(AsymptoteProperties AsymptoteProper)
        {
            PropertiesGrid.Visibility = Visibility.Hidden;
            PropertiesTcBodeGrid.Visibility = Visibility.Hidden;
            PropertiesAsymptote.Visibility = Visibility.Visible;

            textBox_SlopeOfDecade.Text = AsymptoteProper.sSlope;
            textBox_SlopeOfDecade.IsReadOnly = true;
            textBox_SlopeOfDecade.Background = Brushes.LightGray;
            comboBox_AsymptoteColor.SelectedIndex = AsymptoteProper.Color;
            comboBox_AsymptoteColor.IsEnabled = false;
            button_EditAsymptote.Content = "Edit";
        }

        /// <summary>
        /// Freeze SetProperties in Properties window
        /// </summary>
        private void FreezeSetProperties()
        {           
            comboBox_SelectedInputSignal.IsEnabled = false;
            textBox_Period.IsReadOnly = true;
            textBox_Period.Background = Brushes.LightGray;
            textBox_CountOfRepeat.IsReadOnly = true;
            textBox_CountOfRepeat.Background = Brushes.LightGray;
            textBox_Notes.IsReadOnly = true;
            textBox_Notes.Background = Brushes.LightGray;
            textBox_Amplitude.IsReadOnly = true;
            textBox_Amplitude.Background = Brushes.LightGray;
            textBox_AmplitudeAuxMove.IsReadOnly = true;
            textBox_AmplitudeAuxMove.Background = Brushes.LightGray;
            textBox_FrequencyAuxMove.IsReadOnly = true;
            textBox_FrequencyAuxMove.Background = Brushes.LightGray;            
            textBox_PreTriggerStep.IsReadOnly = true;
            textBox_PreTriggerStep.Background = Brushes.LightGray;
            textBox_TimeStep.IsReadOnly = true;
            textBox_TimeStep.Background = Brushes.LightGray;
            textBox_InitLevelStep.IsReadOnly = true;
            textBox_InitLevelStep.Background = Brushes.LightGray;
            textBox_FinalLevelStep.IsReadOnly = true;
            textBox_FinalLevelStep.Background = Brushes.LightGray;

            textBox_NameAxis.IsReadOnly = true;
            textBox_NameAxis.Background = Brushes.LightGray;
            comboBox_ModeControl.IsEnabled = false;
            comboBox_Units.IsEnabled = false;
            checkBox_IsLinear.IsEnabled = false;
            textBox_xScale.IsReadOnly = true;
            textBox_xScale.Background = Brushes.LightGray;
            textBox_vScale.IsReadOnly = true;
            textBox_vScale.Background = Brushes.LightGray;
            textBox_FeedConstant.IsReadOnly = true;
            textBox_FeedConstant.Background = Brushes.LightGray;
            textBox_AllowPositionRange.IsReadOnly = true;
            textBox_AllowPositionRange.Background = Brushes.LightGray;
            checkBox_EnablePositionRangeCheck.IsEnabled = false;
            textBox_AllowedTorqueRangeIdent.IsReadOnly = true;
            textBox_AllowedTorqueRangeIdent.Background = Brushes.LightGray;
            checkBox_EnableTorqueRangeCheckIdent.IsEnabled = false;
            textBox_AllowedTorqueRangeStRes.IsReadOnly = true;
            textBox_AllowedTorqueRangeStRes.Background = Brushes.LightGray;
            checkBox_EnableTorqueRangeCheckStRes.IsEnabled = false;
        }

        /// <summary>
        /// Defrost SetProperties in Properties window
        /// </summary>
        private void DefrostSetProperties()
        {   
        
            comboBox_SelectedInputSignal.IsEnabled = true;            
            textBox_Period.IsReadOnly = false;
            textBox_Period.Background = Brushes.White;
            textBox_CountOfRepeat.IsReadOnly = false;
            textBox_CountOfRepeat.Background = Brushes.White;
            textBox_Notes.IsReadOnly = false;
            textBox_Notes.Background = Brushes.White;
            textBox_Amplitude.IsReadOnly = false;
            textBox_Amplitude.Background = Brushes.White;
            textBox_AmplitudeAuxMove.IsReadOnly = false;
            textBox_AmplitudeAuxMove.Background = Brushes.White;
            textBox_FrequencyAuxMove.IsReadOnly = false;
            textBox_FrequencyAuxMove.Background = Brushes.White;            
            textBox_PreTriggerStep.IsReadOnly = false;
            textBox_PreTriggerStep.Background = Brushes.White;
            textBox_TimeStep.IsReadOnly = false;
            textBox_TimeStep.Background = Brushes.White;
            textBox_InitLevelStep.IsReadOnly = false;
            textBox_InitLevelStep.Background = Brushes.White;
            textBox_FinalLevelStep.IsReadOnly = false;
            textBox_FinalLevelStep.Background = Brushes.White;

            textBox_NameAxis.IsReadOnly = false;
            textBox_NameAxis.Background = Brushes.White;
            comboBox_ModeControl.IsEnabled = true;
            comboBox_Units.IsEnabled = true;
            checkBox_IsLinear.IsEnabled = true;
            textBox_xScale.IsReadOnly = false;
            textBox_xScale.Background = Brushes.White;
            textBox_vScale.IsReadOnly = false;
            textBox_vScale.Background = Brushes.White;
            textBox_FeedConstant.IsReadOnly = false;
            textBox_FeedConstant.Background = Brushes.White;
            textBox_AllowPositionRange.IsReadOnly = false;
            textBox_AllowPositionRange.Background = Brushes.White;
            checkBox_EnablePositionRangeCheck.IsEnabled = true;
            textBox_AllowedTorqueRangeIdent.IsReadOnly = false;
            textBox_AllowedTorqueRangeIdent.Background = Brushes.White;
            checkBox_EnableTorqueRangeCheckIdent.IsEnabled = true;
            textBox_AllowedTorqueRangeStRes.IsReadOnly = false;
            textBox_AllowedTorqueRangeStRes.Background = Brushes.White;
            checkBox_EnableTorqueRangeCheckStRes.IsEnabled = true;
        }

        /// <summary>
        /// Freeze TragetProperties in Properties window
        /// </summary>
        private void FreezeTargetProperties()
        {
            textBox_AmsNetIdTarget.IsReadOnly = true;
            textBox_AmsNetIdTarget.Background = Brushes.LightGray;
            textBox_AdsPort.IsReadOnly = true;
            textBox_AdsPort.Background = Brushes.LightGray;
            textBox_ExternGenerator.IsReadOnly = true;
            textBox_ExternGenerator.Background = Brushes.LightGray;
        }

        /// <summary>
        /// Defrost TragetProperties in Properties window
        /// </summary>
        private void DefrostTargetProperties()
        {
            textBox_AmsNetIdTarget.IsReadOnly = false;
            textBox_AmsNetIdTarget.Background = Brushes.White;
            textBox_AdsPort.IsReadOnly = false;
            textBox_AdsPort.Background = Brushes.White;
            textBox_ExternGenerator.IsReadOnly = false;
            textBox_ExternGenerator.Background = Brushes.White;
        }

        /// <summary>
        /// Refresh units in Properties window
        /// </summary>
        private void RefreshUnits()
        {
            if ((comboBox_Units != null) && (comboBox_ModeControl != null) && (LabelUnitAmplitude != null) && (LabelUnitAmplAuxMove != null) && (LabelUnitInitLevelStep != null) && (LabelUnitFinalLevelStep != null))
            {
                switch (comboBox_ModeControl.SelectedIndex)
                {
                    case 0: // Position control
                        switch (comboBox_Units.SelectedIndex)
                        {
                            case 0: // °
                                LabelUnitAmplitude.Content = "[°]";
                                LabelUnitAmplAuxMove.Content = "[°]";
                                LabelUnitInitLevelStep.Content = "[°]";
                                LabelUnitFinalLevelStep.Content = "[°]";
                                LabelUnitPositonRange.Content = "[°]";
                                PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [°]";
                                PlotChartStepResponse.AxisChange();
                                PlotChartStepResponse.Invalidate();
                                break;
                            case 1: // mm
                                LabelUnitAmplitude.Content = "[mm]";
                                LabelUnitAmplAuxMove.Content = "[mm]";
                                LabelUnitInitLevelStep.Content = "[mm]";
                                LabelUnitFinalLevelStep.Content = "[mm]";
                                LabelUnitPositonRange.Content = "[mm]";
                                PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [mm]";
                                PlotChartStepResponse.AxisChange();
                                PlotChartStepResponse.Invalidate();
                                break;
                            default: // -
                                LabelUnitAmplitude.Content = "[-]";
                                LabelUnitAmplAuxMove.Content = "[-]";
                                LabelUnitInitLevelStep.Content = "[-]";
                                LabelUnitFinalLevelStep.Content = "[-]";
                                LabelUnitPositonRange.Content = "[-]";
                                PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [-]";
                                PlotChartStepResponse.AxisChange();
                                PlotChartStepResponse.Invalidate();
                                break;
                        }
                        break;
                    case 1: // Velocity control
                        switch (comboBox_Units.SelectedIndex)
                        {
                            case 0: // °
                                LabelUnitAmplitude.Content = "[°/s]";
                                LabelUnitAmplAuxMove.Content = "[°/s]";
                                LabelUnitInitLevelStep.Content = "[°/s]";
                                LabelUnitFinalLevelStep.Content = "[°/s]";
                                LabelUnitPositonRange.Content = "[°]";
                                PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [°/s]";
                                PlotChartStepResponse.AxisChange();
                                PlotChartStepResponse.Invalidate();
                                break;
                            case 1: // mm
                                LabelUnitAmplitude.Content = "[mm/s]";
                                LabelUnitAmplAuxMove.Content = "[mm/s]";
                                LabelUnitInitLevelStep.Content = "[mm/s]";
                                LabelUnitFinalLevelStep.Content = "[mm/s]";
                                LabelUnitPositonRange.Content = "[mm]";
                                PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [mm/s]";
                                PlotChartStepResponse.AxisChange();
                                PlotChartStepResponse.Invalidate();
                                break;
                            default: // -
                                LabelUnitAmplitude.Content = "[-]";
                                LabelUnitAmplAuxMove.Content = "[-]";
                                LabelUnitInitLevelStep.Content = "[-]";
                                LabelUnitFinalLevelStep.Content = "[-]";
                                LabelUnitPositonRange.Content = "[-]";
                                PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [-]";
                                PlotChartStepResponse.AxisChange();
                                PlotChartStepResponse.Invalidate();
                                break;
                        }
                        break;
                    case 2: // Torque control
                        switch (comboBox_Units.SelectedIndex)
                        {
                            case 0: // °
                                LabelUnitAmplitude.Content = "[%]";
                                LabelUnitAmplAuxMove.Content = "[%]";
                                LabelUnitInitLevelStep.Content = "[%]";
                                LabelUnitFinalLevelStep.Content = "[%]";
                                LabelUnitPositonRange.Content = "[°]";
                                PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [%]";
                                PlotChartStepResponse.AxisChange();
                                PlotChartStepResponse.Invalidate();
                                break;
                            case 1: // mm
                                LabelUnitAmplitude.Content = "[%]";
                                LabelUnitAmplAuxMove.Content = "[%]";
                                LabelUnitInitLevelStep.Content = "[%]";
                                LabelUnitFinalLevelStep.Content = "[%]";
                                LabelUnitPositonRange.Content = "[mm]";
                                PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [%]";
                                PlotChartStepResponse.AxisChange();
                                PlotChartStepResponse.Invalidate();
                                break;
                            default: // -
                                LabelUnitAmplitude.Content = "[-]";
                                LabelUnitAmplAuxMove.Content = "[-]";
                                LabelUnitInitLevelStep.Content = "[-]";
                                LabelUnitFinalLevelStep.Content = "[-]";
                                LabelUnitPositonRange.Content = "[-]";
                                PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [-]";
                                PlotChartStepResponse.AxisChange();
                                PlotChartStepResponse.Invalidate();
                                break;
                        }
                        break;
                    default: // -
                        LabelUnitAmplitude.Content = "[-]";
                        LabelUnitAmplAuxMove.Content = "[-]";
                        LabelUnitInitLevelStep.Content = "[-]";
                        LabelUnitFinalLevelStep.Content = "[-]";
                        LabelUnitPositonRange.Content = "[-]";
                        PlotChartStepResponse.GraphPane.YAxis.Title.Text = "h [-]";
                        PlotChartStepResponse.AxisChange();
                        PlotChartStepResponse.Invalidate();
                        break;
                }               
            }
        }

        /// <summary>
        /// Check generator properties in Properties window and update sources
        /// </summary>
        /// <returns>
        /// false - all properties in window are set correctly
        /// true - some property is set incorrectly
        /// </returns>
        private bool CheckGenerProp()
        {
            bool ret = false;

            List<BindingExpression> ioListEvent = new List<BindingExpression>();

            if(textBox_TaskTime != null)
                ioListEvent.Add(textBox_TaskTime.GetBindingExpression(TextBox.TextProperty));
            if(textBox_NameAxis != null)
                ioListEvent.Add(textBox_NameAxis.GetBindingExpression(TextBox.TextProperty));
            if(comboBox_Units != null)
                ioListEvent.Add(comboBox_Units.GetBindingExpression(ComboBox.SelectedIndexProperty));
            if (checkBox_IsLinear != null)
                ioListEvent.Add(checkBox_IsLinear.GetBindingExpression(CheckBox.IsCheckedProperty));
            if (textBox_xScale != null)
                ioListEvent.Add(textBox_xScale.GetBindingExpression(TextBox.TextProperty));
            if(textBox_vScale != null)
                ioListEvent.Add(textBox_vScale.GetBindingExpression(TextBox.TextProperty));
            if (textBox_FeedConstant != null)
                ioListEvent.Add(textBox_FeedConstant.GetBindingExpression(TextBox.TextProperty));
            if (textBox_Date != null)
                ioListEvent.Add(textBox_Date.GetBindingExpression(TextBox.TextProperty));
            if(textBox_CountOfRepeat != null)
                ioListEvent.Add(textBox_CountOfRepeat.GetBindingExpression(TextBox.TextProperty));
            if(textBox_Period != null)
                ioListEvent.Add(textBox_Period.GetBindingExpression(TextBox.TextProperty));
            if(textBox_Amplitude != null)
                ioListEvent.Add(textBox_Amplitude.GetBindingExpression(TextBox.TextProperty));
            if(textBox_AmplitudeAuxMove != null)
                ioListEvent.Add(textBox_AmplitudeAuxMove.GetBindingExpression(TextBox.TextProperty));
            if(textBox_FrequencyAuxMove != null)
                ioListEvent.Add(textBox_FrequencyAuxMove.GetBindingExpression(TextBox.TextProperty));
            if(comboBox_ModeControl != null)
                ioListEvent.Add(comboBox_ModeControl.GetBindingExpression(ComboBox.SelectedIndexProperty));
            if(comboBox_SelectedInputSignal != null)
                ioListEvent.Add(comboBox_SelectedInputSignal.GetBindingExpression(ComboBox.SelectedIndexProperty));
            if (textBox_AllowPositionRange != null)
                ioListEvent.Add(textBox_AllowPositionRange.GetBindingExpression(TextBox.TextProperty));
            if (checkBox_EnablePositionRangeCheck != null)
                ioListEvent.Add(checkBox_EnablePositionRangeCheck.GetBindingExpression(CheckBox.IsCheckedProperty));
            if (textBox_AllowedTorqueRangeIdent != null)
                ioListEvent.Add(textBox_AllowedTorqueRangeIdent.GetBindingExpression(TextBox.TextProperty));
            if (checkBox_EnableTorqueRangeCheckIdent != null)
                ioListEvent.Add(checkBox_EnableTorqueRangeCheckIdent.GetBindingExpression(CheckBox.IsCheckedProperty));
            if (textBox_PreTriggerStep != null)
                ioListEvent.Add(textBox_PreTriggerStep.GetBindingExpression(TextBox.TextProperty));
            if(textBox_TimeStep != null)
                ioListEvent.Add(textBox_TimeStep.GetBindingExpression(TextBox.TextProperty));
            if(textBox_InitLevelStep != null)
                ioListEvent.Add(textBox_InitLevelStep.GetBindingExpression(TextBox.TextProperty));
            if(textBox_FinalLevelStep != null)
                ioListEvent.Add(textBox_FinalLevelStep.GetBindingExpression(TextBox.TextProperty));
            if (textBox_AllowedTorqueRangeStRes != null)
                ioListEvent.Add(textBox_AllowedTorqueRangeStRes.GetBindingExpression(TextBox.TextProperty));
            if (checkBox_EnableTorqueRangeCheckStRes != null)
                ioListEvent.Add(checkBox_EnableTorqueRangeCheckStRes.GetBindingExpression(CheckBox.IsCheckedProperty));
            if (comboBoxModeAnalysis != null)
                ioListEvent.Add(comboBoxModeAnalysis.GetBindingExpression(ComboBox.SelectedIndexProperty));
            if(textBox_LengthWindow != null)
                ioListEvent.Add(textBox_LengthWindow.GetBindingExpression(TextBox.TextProperty));
            if (checkBox_CheckPhaseOwerflow != null)
                ioListEvent.Add(checkBox_CheckPhaseOwerflow.GetBindingExpression(CheckBox.IsCheckedProperty));
            if (textBox_OffsetIOdata != null)
                ioListEvent.Add(textBox_OffsetIOdata.GetBindingExpression(TextBox.TextProperty));
            if (textBox_Notes != null)
                ioListEvent.Add(textBox_Notes.GetBindingExpression(TextBox.TextProperty));

            foreach (BindingExpression element in ioListEvent)
            {
                element.UpdateSource();
                if (element.HasError)
                    ret = true;
            }

            return ret;
        }

        /// <summary>
        /// Check target properties in Properties window and update sources
        /// </summary>
        /// <returns>
        /// false - all properties in window are set correctly
        /// true - some property is set incorrectly
        /// </returns>
        private bool CheckTargetProp()
        {
            bool ret = false;

            List<BindingExpression> ioListEvent = new List<BindingExpression>();

            ioListEvent.Add(textBox_AmsNetIdTarget.GetBindingExpression(TextBox.TextProperty));
            ioListEvent.Add(textBox_AdsPort.GetBindingExpression(TextBox.TextProperty));
            ioListEvent.Add(textBox_ExternGenerator.GetBindingExpression(TextBox.TextProperty));

            foreach (BindingExpression element in ioListEvent)
            {
                element.UpdateSource();
                if (element.HasError)
                    ret = true;
            }

            return ret;
        }
        #endregion

        #region Private methods for TreeView - List of curves

        /// <summary>
        /// Add last item from TwinCatExtGen.MeasuredData to TreeView (list of curves) and to graphs and set ID in TwinCatExtGen.MeasuredData
        /// </summary>
        /// <param name="InData"> Data with bode plot </param>
        private void AddCurveMd(TwinCatExtGen InData)
        {
            if ((InData.MeasuredData.Last().Count() > 0) || (InData.MeasuredData.Last().CountStepRes() > 0))
            {
                string name = InData.MeasuredData.Last().NameAxis;

                int TreeItemID = treeViewListCurves.Items.Count;
                InData.MeasuredData.Last().ID = TreeItemID;
               
                TreeViewItemExt treeItem = new TreeViewItemExt();

                treeItem.IsExpanded = true;
                // Main item
                treeItem.Header = GetTreeMainItem(name, TreeItemID);

                // Type of data
                treeItem.DataType = MeasurementType.SpectAnalysis;
                // Corresponding index in list of bode plot data set
                treeItem.IndexData = InData.MeasuredData.Count - 1;
                // ID of measurement is the sma like ID in TwinCatExtGen.MeasuredData
                treeItem.ID = TreeItemID;

                // Subb items
                if (InData.MeasuredData.Last().Count() > 0)
                {
                    // Closed loop
                    CheckBox chbGwItem = new CheckBox();
                    chbGwItem.Content = "Closed loop";
                    chbGwItem.IsChecked = true;
                    chbGwItem.Name = "SubbTreeChbItemGw" + TreeItemID.ToString();
                    treeItem.Items.Add(new TreeViewItem() { Header = chbGwItem });

                    // Open loop
                    CheckBox chbG0Item = new CheckBox();
                    chbG0Item.Content = "Open loop";
                    chbG0Item.IsChecked = true;
                    chbG0Item.Name = "SubbTreeChbItemG0" + TreeItemID.ToString();
                    treeItem.Items.Add(new TreeViewItem() { Header = chbG0Item });

                    // set events for closed and open loop
                    ((CheckBox)((TreeViewItem)treeItem.Items[0]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeClosedLoopItem);
                    ((CheckBox)((TreeViewItem)treeItem.Items[0]).Header).IsEnabledChanged += new System.Windows.DependencyPropertyChangedEventHandler(eventEnabledTreeClosedLoopItem);
                    ((CheckBox)((TreeViewItem)treeItem.Items[1]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeOpenLoopItem);
                    ((CheckBox)((TreeViewItem)treeItem.Items[1]).Header).IsEnabledChanged += new System.Windows.DependencyPropertyChangedEventHandler(eventEnabledTreeOpenLoopItem);

                    AddBodePlot(InData.MeasuredData.Last(), treeItem);
                }

                if (InData.MeasuredData.Last().CountStepRes() > 0)
                {
                    // Step response
                    TreeViewItem treeItemStepRes = null;
                    treeItemStepRes = new TreeViewItem();
                    treeItemStepRes.IsExpanded = true;

                    CheckBox chbStepItem = new CheckBox();
                    chbStepItem.Content = "Step";
                    chbStepItem.IsChecked = true;
                    chbStepItem.Name = "SubbTreeChbItemSt" + TreeItemID.ToString();
                    treeItemStepRes.Header = chbStepItem;

                    CheckBox chbStepItemIn = new CheckBox();
                    chbStepItemIn.Content = "In";
                    chbStepItemIn.IsChecked = true;
                    chbStepItemIn.Name = "SubbTreeChbItemStIn" + TreeItemID.ToString();
                    treeItemStepRes.Items.Add(new TreeViewItem() { Header = chbStepItemIn });

                    CheckBox chbStepItemOut = new CheckBox();
                    chbStepItemOut.Content = "Out";
                    chbStepItemOut.IsChecked = true;
                    chbStepItemOut.Name = "SubbTreeChbItemStOut" + TreeItemID.ToString();
                    treeItemStepRes.Items.Add(new TreeViewItem() { Header = chbStepItemOut });

                    treeItem.Items.Add(treeItemStepRes);

                    if (InData.MeasuredData.Last().Count() > 0)
                    {
                        ((CheckBox)((TreeViewItem)treeItem.Items[2]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeStepItem);
                        ((CheckBox)((TreeViewItem)treeItem.Items[2]).Header).IsEnabledChanged += new System.Windows.DependencyPropertyChangedEventHandler(eventEnabledTreeStepItem);
                        ((CheckBox)((TreeViewItem)((TreeViewItem)treeItem.Items[2]).Items[0]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeStepResInItem);
                        ((CheckBox)((TreeViewItem)((TreeViewItem)treeItem.Items[2]).Items[1]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeStepResOutItem);
                    }
                    else
                    {
                        ((CheckBox)((TreeViewItem)treeItem.Items[0]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeStepItem);
                        ((CheckBox)((TreeViewItem)treeItem.Items[0]).Header).IsEnabledChanged += new System.Windows.DependencyPropertyChangedEventHandler(eventEnabledTreeStepItem);
                        ((CheckBox)((TreeViewItem)((TreeViewItem)treeItem.Items[0]).Items[0]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeStepResInItem);
                        ((CheckBox)((TreeViewItem)((TreeViewItem)treeItem.Items[0]).Items[1]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeStepResOutItem);
                    }

                    AddStepResPlot(InData.MeasuredData.Last(), treeItem);
                }

                treeViewListCurves.Items.Add(treeItem);

                ((TreeViewItemExt)treeViewListCurves.Items[treeViewListCurves.Items.Count - 1]).IsSelected = true;

                // set event for all curves
                ((CheckBox)((StackPanel)((TreeViewItemExt)treeViewListCurves.Items[TreeItemID]).Header).Children[0]).Click += new System.Windows.RoutedEventHandler(eventChangeTreeItem); //dislay or not all curves in one data set
                ((TreeViewItemExt)treeViewListCurves.Items[TreeItemID]).GotFocus += new System.Windows.RoutedEventHandler(eventGotFocusTreeItem);
            }

        }

        /// <summary>
        /// Add last item from List(TwinCatBode) to TreeView (list of curves) and to graphs and set ID in TwinCatBode
        /// </summary>
        /// <param name="InData"> Data with bode plot </param>
        private void AddCurveMd(List<TwinCatBode> InData)
        {
            if (InData.Last().ListTcBodeData.Count > 0)
            {
                for (int i = 0; i < InData.Last().ListTcBodeData.Count; i++)
                {
                    string name = InData.Last().ListTcBodeData[i].TcB_Name;

                    int TreeItemID = treeViewListCurves.Items.Count;
                    InData.Last().ListTcBodeData[i].ID = TreeItemID;

                    TreeViewItemExt treeItem = new TreeViewItemExt();

                    treeItem.IsExpanded = true;
                    // Main item
                    treeItem.Header = GetTreeMainItem(name, TreeItemID);

                    // Type of data
                    treeItem.DataType = MeasurementType.TcBode;
                    // Corresponding index in list of bode plot data set
                    treeItem.IndexData = InData.Count - 1;
                    // Corresponding index in sub-list of bode plot data set
                    treeItem.IndexAuxData = i;
                    // ID of measurement is the same like ID in TwinCatExtGen.MeasuredData
                    treeItem.ID = TreeItemID;

                    // Sub items

                    // Closed loop
                    CheckBox chbGwItem = new CheckBox();
                    chbGwItem.Content = "Closed loop";
                    chbGwItem.IsChecked = true;
                    chbGwItem.Name = "SubbTreeChbItemGw" + TreeItemID.ToString();
                    treeItem.Items.Add(new TreeViewItem() { Header = chbGwItem });

                    // Open loop
                    CheckBox chbG0Item = new CheckBox();
                    chbG0Item.Content = "Open loop";
                    chbG0Item.IsChecked = true;
                    chbG0Item.Name = "SubbTreeChbItemG0" + TreeItemID.ToString();
                    treeItem.Items.Add(new TreeViewItem() { Header = chbG0Item });

                    // Process
                    CheckBox chbPrItem = new CheckBox();
                    chbPrItem.Content = "Process";
                    chbPrItem.IsChecked = true;
                    chbPrItem.Name = "SubbTreeChbItemPr" + TreeItemID.ToString();
                    treeItem.Items.Add(new TreeViewItem() { Header = chbPrItem });

                    // set events for closed and open loop
                    ((CheckBox)((TreeViewItem)treeItem.Items[0]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeClosedLoopItem);
                    ((CheckBox)((TreeViewItem)treeItem.Items[0]).Header).IsEnabledChanged += new System.Windows.DependencyPropertyChangedEventHandler(eventEnabledTreeClosedLoopItem);
                    ((CheckBox)((TreeViewItem)treeItem.Items[1]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeOpenLoopItem);
                    ((CheckBox)((TreeViewItem)treeItem.Items[1]).Header).IsEnabledChanged += new System.Windows.DependencyPropertyChangedEventHandler(eventEnabledTreeOpenLoopItem);
                    ((CheckBox)((TreeViewItem)treeItem.Items[2]).Header).Click += new System.Windows.RoutedEventHandler(eventChangeTreeProcessItem);
                    ((CheckBox)((TreeViewItem)treeItem.Items[2]).Header).IsEnabledChanged += new System.Windows.DependencyPropertyChangedEventHandler(eventEnabledTreeProcessItem);

                    AddBodePlot(InData.Last().ListTcBodeData[i], treeItem);                  

                    treeViewListCurves.Items.Add(treeItem);

                    ((TreeViewItemExt)treeViewListCurves.Items[treeViewListCurves.Items.Count - 1]).IsSelected = true;

                    // set event for all curves
                    ((CheckBox)((StackPanel)((TreeViewItemExt)treeViewListCurves.Items[TreeItemID]).Header).Children[0]).Click += new System.Windows.RoutedEventHandler(eventChangeTreeItem); //dislay or not all curves in one data set
                    ((TreeViewItemExt)treeViewListCurves.Items[TreeItemID]).GotFocus += new System.Windows.RoutedEventHandler(eventGotFocusTreeItem);
                }
            }

        }

        /// <summary>
        /// Add asymptote to list of curves
        /// </summary>
        /// <param name="InData"> Data asymptote properties </param>
        private void AddCurveMd(List<AsymptoteProperties> InData)
        {
            if (InData.Last() != null)
            {

                string name =  "Asymptote " + InData.Last().sSlope + "[dB/dec]";

                int TreeItemID = treeViewListCurves.Items.Count;

                TreeViewItemExt treeItem = new TreeViewItemExt();

                treeItem.IsExpanded = true;
                // Main item
                treeItem.Header = GetTreeMainItem(name, TreeItemID, InData.Last().Color);

                // Type of data
                treeItem.DataType = MeasurementType.Asymptote;
                // Corresponding index in list of bode plot data set
                treeItem.IndexData = InData.Count - 1;
                // ID of measurement is the same like ID in TwinCatExtGen.MeasuredData
                treeItem.ID = TreeItemID;

                AddAsymptote(InData.Last(), treeItem);

                treeViewListCurves.Items.Add(treeItem);

                ((TreeViewItemExt)treeViewListCurves.Items[treeViewListCurves.Items.Count - 1]).IsSelected = true;

                // set events
                ((CheckBox)((StackPanel)((TreeViewItemExt)treeViewListCurves.Items[TreeItemID]).Header).Children[0]).Click += new System.Windows.RoutedEventHandler(eventChangeAsymptoteTreeItem); //dislay or not all curves in one data set
                ((TreeViewItemExt)treeViewListCurves.Items[TreeItemID]).GotFocus += new System.Windows.RoutedEventHandler(eventGotFocusTreeItem);                
            }

        }

        /// <summary>
        /// Refresh asymptote in list of curves
        /// </summary>
        /// <param name="InData"> Data asymptote properties </param>
        /// <param name="actTreeItem"> Actual editing TreeViewItemExt</param>
        private void RefreshCurveMd(List<AsymptoteProperties> InData, TreeViewItemExt actTreeItem)
        {
            if (InData.Last() != null)
            {
                string name = "Asymptote " + InData[actTreeItem.IndexData].sSlope + "[dB/dec]";

                TreeViewItemExt treeItem = new TreeViewItemExt();

                // copy old properties
                treeItem = actTreeItem;

                // Main item - refresh name and color
                treeItem.Header = GetTreeMainItem(name, actTreeItem.ID, InData[actTreeItem.IndexData].Color);

                actTreeItem = treeItem;

                RefreshAsymptote(InData[actTreeItem.IndexData], treeItem);

                // set event for all curves
                ((CheckBox)((StackPanel)actTreeItem.Header).Children[0]).Click += new System.Windows.RoutedEventHandler(eventChangeAsymptoteTreeItem); //dislay or not curve
                actTreeItem.GotFocus += new System.Windows.RoutedEventHandler(eventGotFocusTreeItem);
            }
        }

        /// <summary>
        /// Create main item for TreeView element
        /// </summary>
        /// <param name="name"> Name of curves </param>
        /// <param name="ID"> ID of curves </param>
        /// <returns></returns>
        private StackPanel GetTreeMainItem(string name, int ID)
        {
            // create stack panel
            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;

            // CheckBox
            CheckBox chbItem = new CheckBox();
            chbItem.VerticalAlignment = VerticalAlignment.Center;
            chbItem.IsChecked = true;
            chbItem.Name = "MainTreeChbItem" + ID.ToString();

            // Rectangle
            // Add a Rectangle Element
            System.Windows.Shapes.Rectangle myRect = new System.Windows.Shapes.Rectangle();
            myRect.Stroke = System.Windows.Media.Brushes.Black;
            myRect.Fill = IntToColor(ID);

            myRect.HorizontalAlignment = HorizontalAlignment.Left;
            myRect.VerticalAlignment = VerticalAlignment.Center;
            myRect.Height = 14;
            myRect.Width = 14;

            // Label
            System.Windows.Controls.Label lbl = new System.Windows.Controls.Label();
            lbl.Content = name;

            stack.Children.Add(chbItem);
            stack.Children.Add(myRect);
            stack.Children.Add(lbl);
            stack.Name = "MainTreeItem" + ID.ToString();

            return stack;
        }

        /// <summary>
        /// Create main item for TreeView element
        /// </summary>
        /// <param name="name"> Name of curves </param>
        /// <param name="ID"> ID of curves </param>
        /// /// <param name="color"> color of curves </param>
        /// <returns></returns>
        private StackPanel GetTreeMainItem(string name, int ID, int color)
        {
            // create stack panel
            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;

            // CheckBox
            CheckBox chbItem = new CheckBox();
            chbItem.VerticalAlignment = VerticalAlignment.Center;
            chbItem.IsChecked = true;
            chbItem.Name = "MainTreeChbItem" + ID.ToString();

            // Rectangle
            // Add a Rectangle Element
            System.Windows.Shapes.Rectangle myRect = new System.Windows.Shapes.Rectangle();
            myRect.Stroke = System.Windows.Media.Brushes.Black;
            myRect.Fill = IntToColor(color);

            myRect.HorizontalAlignment = HorizontalAlignment.Left;
            myRect.VerticalAlignment = VerticalAlignment.Center;
            myRect.Height = 14;
            myRect.Width = 14;

            // Label
            System.Windows.Controls.Label lbl = new System.Windows.Controls.Label();
            lbl.Content = name;

            stack.Children.Add(chbItem);
            stack.Children.Add(myRect);
            stack.Children.Add(lbl);
            stack.Name = "MainTreeItem" + ID.ToString();

            return stack;
        }        

        /// <summary>
        /// Return color for specific ID. Return 15 colors.
        /// </summary>
        /// <param name="ID"> ID of set of curves </param>
        /// <returns></returns>
        public static System.Windows.Media.SolidColorBrush IntToColor(int ID)
        {
            System.Windows.Media.SolidColorBrush rColor = new SolidColorBrush();

            if (ID >= 15)
                ID %= 15;
            if (ID < 0)
                ID *= -1;

            switch (ID)
            {
                case 0:
                    rColor = System.Windows.Media.Brushes.DarkRed;
                    break;
                case 1:
                    rColor = System.Windows.Media.Brushes.DarkBlue;
                    break;
                case 2:
                    rColor = System.Windows.Media.Brushes.DarkGreen;
                    break;
                case 3:
                    rColor = System.Windows.Media.Brushes.DarkOrange;
                    break;
                case 4:
                    rColor = System.Windows.Media.Brushes.DarkMagenta;
                    break;
                case 5:
                    rColor = System.Windows.Media.Brushes.DarkGoldenrod;
                    break;
                case 6:
                    rColor = System.Windows.Media.Brushes.Red;
                    break;
                case 7:
                    rColor = System.Windows.Media.Brushes.MediumSeaGreen;
                    break;
                case 8:
                    rColor = System.Windows.Media.Brushes.Violet;
                    break;
                case 9:
                    rColor = System.Windows.Media.Brushes.Blue;                
                    break;
                case 10:
                    rColor = System.Windows.Media.Brushes.Aqua;
                    break;
                case 11:
                    rColor = System.Windows.Media.Brushes.LightGreen;
                    break;
                case 12:
                    rColor = System.Windows.Media.Brushes.Yellow;
                    break;
                case 13:
                    rColor = System.Windows.Media.Brushes.CadetBlue;
                    break;
                case 14:
                    rColor = System.Windows.Media.Brushes.MediumVioletRed;
                    break;
            }

            return rColor;
        }
        #endregion

        #region Events for display/hide graphs and windows

        /// <summary>
        /// Width of ViewGrid.ColumnDefinitions[0] = Width of ListCurvesCurrentGraph in unwrapped state
        /// </summary>
        private double WidthListCurvesCurrentGraph = 250;

        /// <summary>
        /// Height of Curves list in unwrapped state
        /// </summary>
        private double HeightListCurves = 1;

        /// <summary>
        /// Clik on CheckBox for display/hide list of curves
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuChBDispListCurves_Click(object sender, RoutedEventArgs e)
        {
            if (((CheckBox)sender).IsChecked == true)
            {
                ListCurvesCurrentGraph.RowDefinitions[0].MaxHeight = double.MaxValue;
                GridLength LengthGrid = new GridLength(HeightListCurves, GridUnitType.Star);
                ListCurvesCurrentGraph.RowDefinitions[0].Height = LengthGrid;
            }
            else
            {
                HeightListCurves = ListCurvesCurrentGraph.RowDefinitions[0].Height.Value;       // save old height of ListCurves
                WidthListCurvesCurrentGraph = ViewGrid.ColumnDefinitions[0].Width.Value;        // save old width of ViewGrid
                GridLength LengthGrid = new GridLength(0);
                ListCurvesCurrentGraph.RowDefinitions[0].Height = LengthGrid;
                ListCurvesCurrentGraph.RowDefinitions[0].MaxHeight = 0;
            }

            if((MenuChBDispListCurves.IsChecked == false) && (MenuChBDispCurrentGraph.IsChecked == false))
            {
                GridLength LengthGrid = new GridLength(0);
                ViewGrid.ColumnDefinitions[0].Width = LengthGrid;
                ViewGrid.ColumnDefinitions[0].MaxWidth = 0;
            }
            else
            {
                ViewGrid.ColumnDefinitions[0].MaxWidth = double.MaxValue;
                GridLength LengthGrid = new GridLength(WidthListCurvesCurrentGraph);
                ViewGrid.ColumnDefinitions[0].Width = LengthGrid;
            }
        }

        /// <summary>
        /// Height of GraphCurrent in unwrapped state
        /// </summary>
        private double HeightCurrentGraph = 1;

        /// <summary>
        /// Clik on CheckBox for display/hide current graph
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuChBDispCurrentGraph_Click(object sender, RoutedEventArgs e)
        {
            if (((CheckBox)sender).IsChecked == true)
            {
                ListCurvesCurrentGraph.RowDefinitions[2].MaxHeight = double.MaxValue;
                GridLength LengthGrid = new GridLength(HeightCurrentGraph, GridUnitType.Star);
                ListCurvesCurrentGraph.RowDefinitions[2].Height = LengthGrid;
            }
            else
            {
                HeightCurrentGraph = ListCurvesCurrentGraph.RowDefinitions[2].Height.Value;         // save old height of ListCurves
                WidthListCurvesCurrentGraph = ViewGrid.ColumnDefinitions[0].Width.Value;            // save old width of ViewGrid
                GridLength LengthGrid = new GridLength(0);
                ListCurvesCurrentGraph.RowDefinitions[2].Height = LengthGrid;
                ListCurvesCurrentGraph.RowDefinitions[2].MaxHeight = 0;
            }

            if ((MenuChBDispListCurves.IsChecked == false) && (MenuChBDispCurrentGraph.IsChecked == false))
            {                
                GridLength LengthGrid = new GridLength(0);
                ViewGrid.ColumnDefinitions[0].Width = LengthGrid;
                ViewGrid.ColumnDefinitions[0].MaxWidth = 0;
            }
            else
            {
                ViewGrid.ColumnDefinitions[0].MaxWidth = double.MaxValue;
                GridLength LengthGrid = new GridLength(WidthListCurvesCurrentGraph);
                ViewGrid.ColumnDefinitions[0].Width = LengthGrid;
            }
        }

        /// <summary>
        /// Width of GraphGrid in unwrapped state
        /// </summary>
        private double WidthGraphGrid = 1;

        /// <summary>
        /// Height of Magnitude Graph in unwrapped state 
        /// </summary>
        private double HeightMagnitudeGraph = 1;

        /// <summary>
        /// Clik on CheckBox for display/hide Magnitude graph
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuChBDispMagnitudeGraph_Click(object sender, RoutedEventArgs e)
        {
            if(((CheckBox)sender).IsChecked == true)
            {
                GridLength LengthGrid = new GridLength(HeightMagnitudeGraph, GridUnitType.Star);
                GraphGrid.RowDefinitions[1].Height = LengthGrid;
            }
            else
            {
                WidthGraphGrid = ViewGrid.ColumnDefinitions[2].Width.Value;
                HeightMagnitudeGraph = GraphGrid.RowDefinitions[1].Height.Value;
                GridLength LengthGrid = new GridLength(0);
                GraphGrid.RowDefinitions[1].Height = LengthGrid;
            }

            if((MenuChBDispMagnitudeGraph.IsChecked == false) && (MenuChBDispPhaseGraph.IsChecked == false))
            {
                GridLength LengthGrid = new GridLength(0);
                GraphGrid.RowDefinitions[0].Height = LengthGrid;
            }
            else
            {
                GridLength LengthGrid = new GridLength(25, GridUnitType.Pixel);
                GraphGrid.RowDefinitions[0].Height = LengthGrid;
            }

            if ((MenuChBDispMagnitudeGraph.IsChecked == false) && (MenuChBDispPhaseGraph.IsChecked == false) && (MenuChBDispStepResponse.IsChecked == false))
            {
                GridLength LengthGrid = new GridLength(0);
                ViewGrid.ColumnDefinitions[2].Width = LengthGrid;
                ViewGrid.ColumnDefinitions[2].MaxWidth = 0;
            }
            else
            {
                ViewGrid.ColumnDefinitions[2].MaxWidth = double.MaxValue;
                GridLength LengthGrid = new GridLength(WidthGraphGrid, GridUnitType.Star);
                ViewGrid.ColumnDefinitions[2].Width = LengthGrid;
            }
        }

        /// <summary>
        /// Height of Phase Graph in unwrapped state
        /// </summary>
        private double HeightPhaseGraph = 1;

        /// <summary>
        /// Clik on CheckBox for display/hide Phase graph
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuChBDispPhaseGraph_Click(object sender, RoutedEventArgs e)
        {
            if (((CheckBox)sender).IsChecked == true)
            {
                GridLength LengthGrid = new GridLength(1, GridUnitType.Star);
                GraphGrid.RowDefinitions[3].Height = LengthGrid;
            }
            else
            {
                WidthGraphGrid = ViewGrid.ColumnDefinitions[2].Width.Value;
                HeightPhaseGraph = GraphGrid.RowDefinitions[3].Height.Value;
                GridLength LengthGrid = new GridLength(0);
                GraphGrid.RowDefinitions[3].Height = LengthGrid;
            }

            if ((MenuChBDispMagnitudeGraph.IsChecked == false) && (MenuChBDispPhaseGraph.IsChecked == false))
            {
                GridLength LengthGrid = new GridLength(0);
                GraphGrid.RowDefinitions[0].Height = LengthGrid;
            }
            else
            {
                GridLength LengthGrid = new GridLength(25, GridUnitType.Pixel);
                GraphGrid.RowDefinitions[0].Height = LengthGrid;
            }

            if ((MenuChBDispMagnitudeGraph.IsChecked == false) && (MenuChBDispPhaseGraph.IsChecked == false) && (MenuChBDispStepResponse.IsChecked == false))
            {
                GridLength LengthGrid = new GridLength(0);
                ViewGrid.ColumnDefinitions[2].Width = LengthGrid;
                ViewGrid.ColumnDefinitions[2].MaxWidth = 0;
            }
            else
            {
                ViewGrid.ColumnDefinitions[2].MaxWidth = double.MaxValue;
                GridLength LengthGrid = new GridLength(WidthGraphGrid, GridUnitType.Star);
                ViewGrid.ColumnDefinitions[2].Width = LengthGrid;
            }
        }

        /// <summary>
        /// Height of Phase Graph in unwrapped state
        /// </summary>
        private double HeightStepResponseGraph = 1;

        /// <summary>
        /// Clik on CheckBox for display/hide Step Response graph
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuChBDispStepResponse_Click(object sender, RoutedEventArgs e)
        {
            if (((CheckBox)sender).IsChecked == true)
            {
                GridLength LengthGrid = new GridLength(1, GridUnitType.Star);              
                GraphGrid.RowDefinitions[5].Height = LengthGrid;
                GraphGrid.RowDefinitions[4].Height = new GridLength(25, GridUnitType.Pixel);
            }
            else
            {
                WidthGraphGrid = ViewGrid.ColumnDefinitions[2].Width.Value;
                HeightStepResponseGraph = GraphGrid.RowDefinitions[5].Height.Value;
                GridLength LengthGrid = new GridLength(0);
                GraphGrid.RowDefinitions[5].Height = LengthGrid;
                GraphGrid.RowDefinitions[4].Height = LengthGrid;
            }

            if ((MenuChBDispMagnitudeGraph.IsChecked == false) && (MenuChBDispPhaseGraph.IsChecked == false) && (MenuChBDispStepResponse.IsChecked == false))
            {
                GridLength LengthGrid = new GridLength(0);
                ViewGrid.ColumnDefinitions[2].Width = LengthGrid;
                ViewGrid.ColumnDefinitions[2].MaxWidth = 0;
            }
            else
            {
                ViewGrid.ColumnDefinitions[2].MaxWidth = double.MaxValue;
                GridLength LengthGrid = new GridLength(WidthGraphGrid, GridUnitType.Star);
                ViewGrid.ColumnDefinitions[2].Width = LengthGrid;
            }
        }

        /// <summary>
        /// Clik on CheckBox for display/hide symbols in Step Response graph
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuChBDispStepResponseSymbols_Click(object sender, RoutedEventArgs e)
        {
            if (((CheckBox)sender).IsChecked == true)
            {
                for (int i = 0; i < PlotChartStepResponse.GraphPane.CurveList.Count; i++)
                {
                    LineItem curveStepRes = PlotChartStepResponse.GraphPane.CurveList[i] as LineItem;
                    curveStepRes.Symbol.IsVisible = true;
                }
            }
            else
            {
                for (int i = 0; i < PlotChartStepResponse.GraphPane.CurveList.Count; i++)
                {
                    LineItem curveStepRes = PlotChartStepResponse.GraphPane.CurveList[i] as LineItem;
                    curveStepRes.Symbol.IsVisible = false;
                }
            }

            PlotChartStepResponse.AxisChange();
            PlotChartStepResponse.Invalidate();
        }

        /// <summary>
        /// Width of GraphGrid in unwrapped state
        /// </summary>
        private double WidthPropertiesGrid = 1;

        private void MenuChBDispProperties_Click(object sender, RoutedEventArgs e)
        {
            if (((CheckBox)sender).IsChecked == true)
            {
                ViewGrid.ColumnDefinitions[4].MaxWidth = double.MaxValue;
                GridLength LengthGrid = new GridLength(WidthPropertiesGrid);
                ViewGrid.ColumnDefinitions[4].Width = LengthGrid;
            }
            else
            {
                WidthPropertiesGrid = ViewGrid.ColumnDefinitions[4].Width.Value;
                GridLength LengthGrid = new GridLength(0);
                ViewGrid.ColumnDefinitions[4].Width = LengthGrid;
                ViewGrid.ColumnDefinitions[4].MaxWidth = 0;
            }
        }


        #endregion

        
    }

    /// <summary>
    /// Data type of measurement
    /// </summary>
    public enum MeasurementType
    {
        /// <summary>
        /// Spectral analysis
        /// </summary>
        SpectAnalysis,
        /// <summary>
        /// TwinCAT Bode plot from Beckhoff tool
        /// </summary>
        TcBode,
        /// <summary>
        /// Asymptote in magnitude part of bode plot
        /// </summary>
        Asymptote,
        /// <summary>
        /// None
        /// </summary>
        None
    };

    /// <summary>
    /// Storage time
    /// </summary>
    public class MyTime
    {
        /// <summary>
        /// Hour
        /// </summary>
        public UInt16 Hour;
        /// <summary>
        /// Minutes
        /// </summary>
        public UInt16 Minutes;
        /// <summary>
        /// Seconds
        /// </summary>
        public UInt16 Secondes;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="TotalMicroSeconds"> count of microseconds </param>
        public MyTime(UInt64 TotalMicroSeconds)
        {
            UInt64 TotalSeconds = TotalMicroSeconds / 1000000;
            Hour = Convert.ToUInt16(Math.Floor(Convert.ToDouble(TotalSeconds) / 3600.0));
            TotalSeconds -= Convert.ToUInt64(Hour) * 3600;
            Minutes = Convert.ToUInt16(Math.Floor(Convert.ToDouble(TotalSeconds) / 60.0));
            TotalSeconds -= Convert.ToUInt64(Minutes) * 60;
            Secondes = Convert.ToUInt16(TotalSeconds);
        }
    }

    /// <summary>
    /// TreeViewItem with info about storage data
    /// </summary>
    public class TreeViewItemExt : TreeViewItem
    {
        /// <summary>
        /// ID of measurement. Unique number is the same like ID in appropriate data set class (TwinCatExtGen.MeasuredData / TwinCatBode)
        /// </summary>
        public int ID = -1;

        /// <summary>
        ///  Type of data
        /// </summary>
        public MeasurementType DataType = MeasurementType.None;

        /// <summary>
        /// Corresponding index in list of data
        /// </summary>
        public int IndexData = -1;

        /// <summary>
        /// Corresponding index in list of data ( only for TwinCAT Bode plot data ). Index in TwinCatBode.ListTcBodeData[X]
        /// </summary>
        public int IndexAuxData = -1;

        /// <summary>
        /// Corresponding index in graph (Magnitude) for closed loop
        /// </summary>
        public int IndexGraphClosedLoopMg = -1;

        /// <summary>
        /// Corresponding index in graph (Phase) for closed loop
        /// </summary>
        public int IndexGraphClosedLoopPh = -1;

        /// <summary>
        /// Corresponding index in graph (Magnitude) for open loop
        /// </summary>
        public int IndexGraphOpenLoopMg = -1;

        /// <summary>
        /// Corresponding index in graph (Phase) for open loop
        /// </summary>
        public int IndexGraphOpenLoopPh = -1;

        /// <summary>
        /// Corresponding index in graph (Magnitude) for process ( only for TwinCAT Bode plot data )
        /// </summary>
        public int IndexGraphProcessMg = -1;

        /// <summary>
        /// Corresponding index in graph (Phase) for process ( only for TwinCAT Bode plot data )
        /// </summary>
        public int IndexGraphProcessPh = -1;

        /// <summary>
        /// Corresponding index in Step response graph for input data ( only for Spectral analysis data)
        /// </summary>
        public int IndexGraphInStepRes = -1;

        /// <summary>
        /// Corresponding index in Step response graph for output data ( only for Spectral analysis data)
        /// </summary>
        public int IndexGraphOutStepRes = -1;
    }

    /// <summary>
    /// Calss for storage properties of asymptote
    /// </summary>
    public class AsymptoteProperties
    {
        /// <summary>
        /// Slope of the decade [dB/decade]
        /// </summary>
        private double i_Slope;

        /// <summary>
        /// Color of asymptote
        /// </summary>
        private int i_Color = 0;

        /// <summary>
        /// Position of aymptote
        /// </summary>
        public System.Drawing.Point mousePt;

        /// <summary>
        /// Constructor
        /// </summary>
        public AsymptoteProperties()
        {
            i_Slope = 0;
            i_Color = 0;
            mousePt = new System.Drawing.Point();
        }

        /// <summary>
        /// Get/Set slope of the decade [dB/decade]
        /// </summary>
        public Double Slope
        {
            set { i_Slope = value; }
            get { return i_Slope; }
        }

        /// <summary>
        /// Get/Set slope of the decade [dB/decade]
        /// </summary>
        public string sSlope
        {
            set
            {
                try
                {
                    i_Slope = Convert.ToDouble(value, System.Globalization.CultureInfo.InvariantCulture);
                }
                catch (Exception e)
                {
                    string ErrMes = "";
                    if (e.Source == "SysIdentifi")
                        ErrMes = e.Message;
                    throw (new Exception("Wrong slope of the decade" + ErrMes));
                }

            }
            get { return i_Slope.ToString(System.Globalization.CultureInfo.InvariantCulture); }
        }

        /// <summary>
        /// Get/Set color of asymptote
        /// </summary>
        public int Color
        {
            set { i_Color = value; }
            get { return i_Color; }
        }
    }
}
