using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.NetworkInformation;
using System.IO;

namespace VibrationExciterControl
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 

    public class NetIf
    {
        public string netIp { get; set; }
        public string netDescription { get; set; }
    }


    public partial class MainWindow : Window
    {
        Comm comm;
        Plot plot;
        SignalProcessing sProcess;
        Timer timer1;

        enum CONTROL_TYPE { BUTTON_START_TEST, CONTROL_TEST_CHANGE, CONTROL_HALF_SIN };

        private ObservableCollection<NetIf> interfaces;
        NetIf interfacesItem;

        double[] measuredAccData = new double[2048];
        int measuredAccDataIndex;

        double[] testSrcData;
        double[] testMeasFrequency;
        double[] testMeasAmplitude;

        bool appInControl = false;
        bool dataReady = false;

        int testTimeProgressLast = -1;
        double timeTopLimit = 1200;

        bool testIsRunning = false;

        //const int BROADCAST_PORT = 30303;
        //const string BROADCAST_REQUEST = "Discovery: Who is out there?";
        public MainWindow()
        {
            InitializeComponent();

            interfaces = new ObservableCollection<NetIf>();
            comm = new Comm(CommCallback);
            plot = new Plot(CanvasGraph);
            sProcess = new SignalProcessing();


            timer1 = new Timer();
            timer1.Interval = 100;
            timer1.Elapsed += timer1_Elapsed;

            ListBoxDevices.ItemsSource = comm.devices;
            ComboBoxInterfaces.ItemsSource = interfaces;

            CanvasBorder.BorderThickness = new Thickness(1);        //CanvasBorder.BorderThickness = new Thickness(0);
            
            GetNetInterfaces();
            if (interfaces.Count > 0)
            {
                ComboBoxInterfaces.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("No active network interfaces have been found! \n Connent and power up at least one network interface and click on Interface selection ComboBox. \n\n Tip: If you see this message and network interface is on, use manual connect!");
            }

            
            comm.StartBroadcastListening();
            OutputPrint("Welcome to Vibration Control Interface\nTo connect to the generator make sure it's powered on and connected to the same network as interface selected  above, then click Search in network. Select device from device list and click connect. \nControl is allowed after taking control over device.", Brushes.Blue);

            //this.PreviewMouseUp += new MouseButtonEventHandler(SliderSweepSpeed_MouseLeftButtonUp);
        
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            plot.Init(0,300,0,500+0.1*500);
            plot.ReRender();
            //PlotSizeUpdate();
        }

        private void ControlsDiable(CONTROL_TYPE contol)
        {
            switch(contol)
            {
                case CONTROL_TYPE.BUTTON_START_TEST:
                    ButtonStart.IsEnabled = false;
                    break;

                case CONTROL_TYPE.CONTROL_TEST_CHANGE:
                    ButtonSingleFrequency.IsEnabled = false;
                    ButtonSweep.IsEnabled = false;
                    TextBoxStartFrequency.IsEnabled = false;
                    TextBoxStopFrequency.IsEnabled = false;
                    TextBoxTimeOfTest.IsEnabled = false;
                    SliderSweepSpeed.IsEnabled = false;
                    CheckBoxManualOverride.IsEnabled = false;
                    CheckBoxSweepStartStopBack.IsEnabled = false;
                    CheckBoxHalfSin.IsEnabled = false;
                    CheckBoxFixTime.IsEnabled = false;
                    break;
                case CONTROL_TYPE.CONTROL_HALF_SIN:
                    ButtonSweep.IsEnabled = false;
                    SliderSweepSpeed.IsEnabled = false;
                    break;
            }
        }

        private void ControlsEnable(CONTROL_TYPE contol)
        {
            switch (contol)
            {
                case CONTROL_TYPE.BUTTON_START_TEST:
                    if (appInControl == true && dataReady == true && CheckBoxManualOverride.IsChecked == false)
                    {
                        ButtonStart.IsEnabled = true;
                    }
                    
                    break;

                case CONTROL_TYPE.CONTROL_TEST_CHANGE:
                    if (CheckBoxHalfSin.IsChecked == false)
                    {
                        ButtonSingleFrequency.IsEnabled = true;
                        ButtonSweep.IsEnabled = true;
                        TextBoxStartFrequency.IsEnabled = true;
                        TextBoxStopFrequency.IsEnabled = true;
                        TextBoxTimeOfTest.IsEnabled = true;
                        SliderSweepSpeed.IsEnabled = true;
                        CheckBoxManualOverride.IsEnabled = true;
                        CheckBoxSweepStartStopBack.IsEnabled = true;
                        CheckBoxHalfSin.IsEnabled = true;
                        CheckBoxFixTime.IsEnabled = true;
                    }
                    else
                    {
                        ButtonSingleFrequency.IsEnabled = true;
                        TextBoxStartFrequency.IsEnabled = true;
                        TextBoxStopFrequency.IsEnabled = true;
                        TextBoxTimeOfTest.IsEnabled = true;
                        CheckBoxManualOverride.IsEnabled = true;
                    }

                    break;

                case CONTROL_TYPE.CONTROL_HALF_SIN:
                    ButtonSweep.IsEnabled = true;
                    SliderSweepSpeed.IsEnabled = true;
                    break;

            }
        }
        

        private void ButtonSearchNetwork_Click(object sender, RoutedEventArgs e)
        {
            TextBlockDevicesStatus.Text = "Searching...";
            //comm.SendBroadcastSearchReq(BROADCAST_REQUEST, BROADCAST_PORT, interfaces[ComboBoxInterfaces.SelectedIndex].netIp);
            comm.SendBroadcastSearchReq1(interfaces[ComboBoxInterfaces.SelectedIndex].netIp);
        }

        private void CheckBoxAutoMan_Checked(object sender, RoutedEventArgs e)
        {
            DockPanelNetworkAuto.Visibility = System.Windows.Visibility.Collapsed;
            DockPanelNetworkManual.Visibility = System.Windows.Visibility.Visible;
            ButtonSearchNetwork.IsEnabled = false;
            ButtonConnect.IsEnabled = true;
        }

        private void CheckBoxAutoMan_Unchecked(object sender, RoutedEventArgs e)
        {
            DockPanelNetworkManual.Visibility = System.Windows.Visibility.Collapsed;
            DockPanelNetworkAuto.Visibility = System.Windows.Visibility.Visible;
            ButtonSearchNetwork.IsEnabled = true;

        }

        private void ListBoxDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ListBoxDevices.SelectedIndex != -1)
            {
                ButtonConnect.IsEnabled = true;
            }
            else
            {
                ButtonConnect.IsEnabled = false;
            }
        }

        private void ButtonConnect_Click(object sender, RoutedEventArgs e)
        {
            string ip;

            if (CheckBoxAutoMan.IsChecked == true)
            {
                ip = TextBoxRemoteIP.Text;
            }
            else
            {
                ip = comm.GetDeviceIP(ListBoxDevices.SelectedIndex);
            }
            

            if (ip != null)
	        {
                ButtonConnect.IsEnabled = false;
                comm.ConnectToServer(ip, 3000);

	        }

            
        }

        bool drawInThisTime = false;
        int offcounter = 0;
        void CommCallback(Comm.STATE state)
        {
            if (state.searchCallback == false)
            {
                UpdateConnectionInfo(state.connection);
            }

            if ((state.testComplete == true) && (testIsRunning == true))
            {
                testIsRunning = false;
                System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
                {
                    ButtonStartBackTostart();
                    ControlsEnable(CONTROL_TYPE.CONTROL_TEST_CHANGE);
                    OutputPrint("Test completed.", Brushes.Black);
                });
            }
                    
            System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
            {
                TextBlock3V3Good.Text = state.voltge3V3Good ? "OK" : "X";
                TextBlock5VGood.Text = state.voltage5VGood ? "OK" : "X";
                TextBlock12VGood.Text = state.voltage12VGood ? "OK" : "X";
                TextBlockInputVoltage.Text = state.inputVoltage.ToString("0.00") + " V";
                if (state.temperature == 255)
                {
                    TextBlockGenTemp.Text = "--" + "°C";
                }
                else
                {
                    TextBlockGenTemp.Text = state.temperature.ToString("00") + "°C";
                }

                if ((state.generatorOn == false) && (testTimeProgressLast > 5) && (testIsRunning == true))
                {
                    ButtonStartBackTostart();
                    ControlsEnable(CONTROL_TYPE.CONTROL_TEST_CHANGE);
                    OutputPrint("Test stopped not usual way", Brushes.Red);
                }
                TextBlockGenOn.Text = state.generatorOn ? "Yes" : "No";
                TextBlockGenReady.Text = state.generatorReady ? "Yes" : "No";
                TextBlockGenOvercurret.Text = state.overCurrent ? "Yes" : "No";
                TextBlockGenOverheat.Text = state.overHeat ? "Yes" : "No";


                if (state.voltage12VGood == false)
                {
                    offcounter++;
                    //Title = offcounter.ToString();
                }

                if (state.searchCallback == true)
                {
                    if (state.searching == true)
                    {
                        if (TextBlockDevicesStatus.Text == "Searching.")
                        {
                            TextBlockDevicesStatus.Text = "Searching..";
                        }
                        else
                        {
                            TextBlockDevicesStatus.Text = "Searching.";
                        }

                    }
                    else
                    {
                        if (comm.GetDeviceCount() == 0)
                        {
                            TextBlockDevicesStatus.Text = "No device has been found!";
                        }
                        else
                        {
                            TextBlockDevicesStatus.Text = "";
                        }

                    }
                }

                if (state.testMeasureData == true)
                {
                    int testTimeProgress = comm.GetTestTimeProgress();

                    if (testTimeProgress != testTimeProgressLast)
                    {
                        plot.DrawProgressTimeLine(testTimeProgress);
                        if (plotFreq == true)
                        {
                            plot.PlotAdd(testMeasFrequency, Plot.PLOT_TYPE.PLOT_MEASURE);
                        }
                        else
                        {
                            plot.PlotAdd(testMeasAmplitude, Plot.PLOT_TYPE.PLOT_MEASURE);
                        }
                        
                        measuredAccDataIndex = 0;
                        //testMeasData = new double[0];
                        testTimeProgressLast = testTimeProgress;
                        drawInThisTime = true;
                        measuredAccDataIndex = 0;
                    }
                    
                    PrepareAccDataAndDrawFreq();
                }


               

            });

        }

        void PrepareAccDataAndDrawFreq()
        {
            double[] newData = comm.GetMeasuredData();
            double freq = 0;
            double ampli = 0;
            for (int i = 0; i < newData.Length; i++)
			{
                measuredAccData[measuredAccDataIndex + i] = newData[i];
			}
            measuredAccDataIndex += newData.Length;
            if (measuredAccDataIndex >= 2000)
            {
                //freq = sProcess.GetFrequency(dataTestFft);
                double average = measuredAccData.Sum()/measuredAccDataIndex;
                
                for (int i = 0; i < measuredAccDataIndex; i++)
                {
                    measuredAccData[i] -= average;
                }

                freq = sProcess.GetFrequency(measuredAccData);
                ampli = sProcess.GetAmplitude(measuredAccData, freq);
                if (drawInThisTime == true)
                {
                    drawInThisTime = false;
                    Array.Resize(ref testMeasFrequency, testMeasFrequency.Length + 1);
                    testMeasFrequency[testMeasFrequency.Length - 1] = freq;
                    
                    Array.Resize(ref testMeasAmplitude, testMeasAmplitude.Length + 1);
                    testMeasAmplitude[testMeasAmplitude.Length - 1] = ampli;

                    //plot.PlotAdd(testMeasData, Plot.PLOT_TYPE.PLOT_MEASURE);
                }
                measuredAccDataIndex = 0;
            }
            
        }

        void UpdateConnectionInfo(Comm.CONNECTION connection)
        {
            switch(connection)
            {
                case Comm.CONNECTION.CONNECTED:
                    if (appInControl == false)
                    {
                        System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
                        {
                            TextBlockConnection.Text = "Connected";
                            TextBlockConnection.Foreground = Brushes.Green;
                            ButtonClose.IsEnabled = true;
                            ButtonTakeControl.IsEnabled = false;
                            ButtonConnect.IsEnabled = false;
                            OutputPrint("This application has acuired full control over device!", Brushes.Green);
                            appInControl = true;
                            ControlsEnable(CONTROL_TYPE.BUTTON_START_TEST);
                        });
                    }
                    break;

                case Comm.CONNECTION.CHECKING_STATUS:
                    System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
                    {
                        TextBlockConnection.Text = "State check";
                        TextBlockConnection.Foreground = Brushes.Blue;
                        ButtonClose.IsEnabled = true;
                        ButtonTakeControl.IsEnabled = true;
                        ButtonConnect.IsEnabled = false;
                        appInControl = false;

                    });
                    break;

                case Comm.CONNECTION.CONTROLED_BY_3RD_SITE:
                    System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
                    {
                        TextBlockConnection.Text = "State check";
                        TextBlockConnection.Foreground = Brushes.Blue;
                        ButtonClose.IsEnabled = true;
                        ButtonTakeControl.IsEnabled = true;
                        ButtonConnect.IsEnabled = false;
                        OutputPrint("Someone else is controling device, switching back to State check", Brushes.Red);

                    });
                    break;

                case Comm.CONNECTION.CONNECTION_LOST:
                    System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
                    {
                        TextBlockConnection.Text = "not connected";
                        TextBlockConnection.Foreground = Brushes.Black;
                        ButtonClose.IsEnabled = false;
                        ButtonTakeControl.IsEnabled = false;
                        if (ListBoxDevices.SelectedIndex != -1)
                        {
                            ButtonConnect.IsEnabled = true;
                        }
                        appInControl = false;
                        OutputPrint("Connection lost.", Brushes.Red);
                    });
                    break;

            }
        }



        
        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (CheckBoxAmplitudeInUm.IsChecked == false)
            {
                TextBlockScaleValue.Text = ((int)SliderScale.Value).ToString();
            }
            else
            {
                if (SliderScale.Value < 10E3)
                {
                    TextBlockScaleValue.Text = ((int)SliderScale.Value).ToString() + "um";
                }
                else if (SliderScale.Value < 10E4)
                {
                    TextBlockScaleValue.Text = ((int)SliderScale.Value/1E3).ToString("0.0") + "mm";
                }
                
            }
            
            timer1.Start();
        }
        double scaleValue;
        double scaleVauleInUm;
        void timer1_Elapsed(object sender, ElapsedEventArgs e)
        {
            string command;
            Nullable<bool> scaleUmSelection = false;
            int slideVal = -1;

            System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
            {
                slideVal = (int)(SliderScale.Value);
                scaleUmSelection = CheckBoxAmplitudeInUm.IsChecked;
            });

            if (scaleUmSelection == false)
            {
                if (scaleValue == slideVal)
                {
                    timer1.Stop();
                }
                command = (80 + (slideVal)).ToString();
                comm.SendMessageToServer("genscale " + command);

            }
            else
            {
                if (scaleVauleInUm == slideVal)
                {
                    timer1.Stop();
                }
                command = (slideVal).ToString();
                comm.SendMessageToServer("genmm " + command);
            }


            

            //System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
            //{
            //    Title = command;
            //});
            

            System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
            {
                //scaleValue = (int)(1900 * SliderScale.Value);
                scaleValue = (int)(SliderScale.Value);
            });
            
        }

        private void CheckBoxAmplitudeInUm_Unchecked(object sender, RoutedEventArgs e)
        {
            SliderScale.Maximum = 1956;
        }

        private void CheckBoxAmplitudeInUm_Checked(object sender, RoutedEventArgs e)
        {
            SliderScale.Maximum = 20E3;
        }


        private void CheckBoxManualOverride_Unchecked(object sender, RoutedEventArgs e)
        {
            //TextBoxOutput.Margin = new Thickness(5, 20, 5, 5);
            ManualOverride.Visibility = System.Windows.Visibility.Collapsed;
            ControlsEnable(CONTROL_TYPE.BUTTON_START_TEST);
        }

        private void CheckBoxManualOverride_Checked(object sender, RoutedEventArgs e)
        {
            ManualOverride.Visibility = System.Windows.Visibility.Visible;
            ControlsDiable(CONTROL_TYPE.BUTTON_START_TEST);
            //TextBoxOutput.Margin = new Thickness(5, 134, 5, 5);
        }

        private void ButtonStartGen_Click(object sender, RoutedEventArgs e)
        {
            testMeasFrequency = new double[1];
            testMeasAmplitude = new double[1];
            comm.SendMessageToServer("genstart");
        }

        private void ButtonStopGen_Click(object sender, RoutedEventArgs e)
        {
            comm.SendMessageToServer("genstop");
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            comm.TerminateThreads();
        }

        private void Button12VOn_Click(object sender, RoutedEventArgs e)
        {
            comm.SendMessageToServer("voltage12 on");
        }

        private void Button12VOff_Click(object sender, RoutedEventArgs e)
        {
            comm.SendMessageToServer("voltage12 off");
        }

        private void ListBoxDevices_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            string ip;

            ip = comm.GetDeviceIP(ListBoxDevices.SelectedIndex);

            if (ip != null)
            {
                comm.ConnectToServer(ip, 3000);
            }
        }

        private void ButtonClose_Click(object sender, RoutedEventArgs e)
        {
            ButtonClose.IsEnabled = false;
            comm.StopConnection();
        }



        double frequency;
        string frequencyLastContent;
        private void TextBoxFrequency_TextChanged(object sender, TextChangedEventArgs e)
        {
            double frequency;
            bool isNumber = false;
            bool isInRange = false;

            isNumber = double.TryParse(TextBoxFrequency.Text, out frequency);
            if ((frequency>=5) && (frequency<=5000))
            {
                TextBoxFrequency.Background = Brushes.White;
                isInRange = true;
            }else
	        {
                TextBoxFrequency.Background = new SolidColorBrush(Color.FromArgb(120, 240, 17, 17));
                isInRange = false;
	        }

            if (TextBoxFrequency.Text == "")
            {
                return;
            }

            if (isNumber)
            {
                if (isInRange)
                {
                    this.frequency = frequency;
                    frequencyLastContent = TextBoxFrequency.Text;  
                }   
            }
            else
            {
                TextBoxFrequency.Text = TextBoxFrequency.Text.Substring(0,TextBoxFrequency.Text.Length-1);
                TextBoxFrequency.SelectionStart = TextBoxFrequency.Text.Length;
            }
        }

        private void ButtonSetFrequency_Click(object sender, RoutedEventArgs e)
        {
            TextBoxFrequency.Text = frequencyLastContent;
            comm.SendMessageToServer("genfreq " + (Math.Round(frequency*100)).ToString());
        }



        private void GetNetInterfaces()
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            interfaces.Clear();

            if (nics == null || nics.Length < 1)
            {
                return;
            }

            foreach (NetworkInterface adapter in nics)
            {
                if (adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    if (adapter.OperationalStatus == OperationalStatus.Up)
                    {
                        IPInterfaceProperties properties = adapter.GetIPProperties();
                        foreach (UnicastIPAddressInformation ip in properties.UnicastAddresses)
                        {
                            if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                interfacesItem = new NetIf();
                                interfacesItem.netDescription = adapter.Description;
                                interfacesItem.netIp = ip.Address.ToString();
                                interfaces.Add(interfacesItem);
                            }
                        }
                    }
                }
            }
        }


        private void ComboBoxInterfaces_MouseEnter(object sender, MouseEventArgs e)
        {
            int selectedOld = ComboBoxInterfaces.SelectedIndex;
            GetNetInterfaces();
            if (ComboBoxInterfaces.Items.Count >= selectedOld)
            {
                ComboBoxInterfaces.SelectedIndex = selectedOld;
            }
            else if (ComboBoxInterfaces.Items.Count > 0)
            {
                ComboBoxInterfaces.SelectedIndex = 0;
            }
        }


        private void CanvasGraph_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            plot.SizeUpdate(0, 0, 0, 0,0000);
            plot.ReRender();

            plot.PlotAdd(testSrcData, Plot.PLOT_TYPE.PLOT_SRC);
            if (plotFreq == true)
            {
                plot.PlotAdd(testMeasFrequency, Plot.PLOT_TYPE.PLOT_MEASURE);
            }
            else
            {
                plot.PlotAdd(testMeasAmplitude, Plot.PLOT_TYPE.PLOT_MEASURE);
            }
            
            
        }

        double stoptime;
        string timeLastContent;
        private void TextBoxTimeOfTest_TextChanged(object sender, TextChangedEventArgs e)
        {
            double time;
            bool isNumber = false;
            bool isInRange = false;

            if (CheckBoxSweepStartStopBack.IsChecked == true)
            {
                timeTopLimit = 2400;
            }
            else
            {
                timeTopLimit = 1200;
            }

            dataReady = false;
            ControlsDiable(CONTROL_TYPE.BUTTON_START_TEST);
            isNumber = double.TryParse(TextBoxTimeOfTest.Text, out time);
            if ((time >= 10) && (time <= timeTopLimit))
            {
                TextBoxTimeOfTest.Background = Brushes.White;
                isInRange = true;
            }
            else
            {
                TextBoxTimeOfTest.Background = new SolidColorBrush(Color.FromArgb(120, 240, 17, 17));
                isInRange = false;
            }

            if (TextBoxTimeOfTest.Text == "")
            {
                return;
            }

            if (isNumber)
            {
                if (isInRange)
                {
                    this.stoptime = time;
                    timeLastContent = TextBoxTimeOfTest.Text;
                    if (plot != null)
                    {
                        plot.SizeUpdate(0, this.stoptime, 0, 0,0100);
                        plot.ReRender();
                    }
                    
                }
            }
            else
            {
                TextBoxTimeOfTest.Text = timeLastContent;
                //TextBoxTimeOfTest.Text = TextBoxTimeOfTest.Text.Substring(0, TextBoxTimeOfTest.Text.Length - 1);
                TextBoxTimeOfTest.SelectionStart = TextBoxTimeOfTest.Text.Length;
            }
        }

        double stopFrequency;
        string stopFrequencyLastContent;
        private void TextBoxStopFrequency_TextChanged(object sender, TextChangedEventArgs e)
        {
            double stopFrequency;
            bool isNumber = false;
            bool isInRange = false;

            dataReady = false;
            ControlsDiable(CONTROL_TYPE.BUTTON_START_TEST);

            isNumber = double.TryParse(TextBoxStopFrequency.Text, out stopFrequency);
            if ((stopFrequency >= 5) && (stopFrequency <= 5000))
            {
                TextBoxStopFrequency.Background = Brushes.White;
                isInRange = true;
            }
            else
            {
                TextBoxStopFrequency.Background = new SolidColorBrush(Color.FromArgb(120, 240, 17, 17));
                isInRange = false;
            }

            if (TextBoxStopFrequency.Text == "")
            {
                return;
            }

            if (isNumber)
            {
                if (isInRange)
                {
                    this.stopFrequency = stopFrequency;
                    stopFrequencyLastContent = TextBoxStopFrequency.Text;
                    if (plot != null)
                    {
                        plot.SizeUpdate(0, 0, 0, this.stopFrequency + 0.1 * this.stopFrequency, 0001);
                        plot.ReRender();
                    }

                }
            }
            else
            {
                TextBoxStopFrequency.Text = stopFrequencyLastContent;
                TextBoxStopFrequency.SelectionStart = TextBoxStopFrequency.Text.Length;
            }
        }



        private void ButtonSingleFrequency_Click(object sender, RoutedEventArgs e)
        {
            testSrcData = new double[(int)stoptime+1];
            double f1 = startFrequency;

            for (int t = 0; t < testSrcData.Count(); t++)
            {
                testSrcData[t] = f1;
            }
            plot.PlotAdd(testSrcData,Plot.PLOT_TYPE.PLOT_SRC);
            dataReady = true;
            ControlsEnable(CONTROL_TYPE.BUTTON_START_TEST);
        }

        private void TextBoxFrequency_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key== Key.Enter)
            {
                ButtonSetFrequency_Click(null, null);
                TextBoxFrequency.SelectionStart = 0;
                TextBoxFrequency.SelectionLength = TextBoxFrequency.Text.Length;
            }
        }

        private void ButtonSweep_Click(object sender, RoutedEventArgs e)
        {
            CalculateSweep();
        }

        private void CalculateSweep()
        {
            double f1 = startFrequency;
            int fixedTime = 0;

            if (CheckBoxFixTime.IsChecked == true)
            {
                fixedTime = (int)(60 * Math.Log(stopFrequency / f1, Math.E) / (SliderSweepSpeed.Value * Math.Log(2, Math.E)));

                if (fixedTime > timeTopLimit)
                {
                    fixedTime = (int)timeTopLimit;
                }
                testSrcData = new double[(int)fixedTime + 1];
                SetTimeOfTest(fixedTime);
            }
            else
            {
                testSrcData = new double[(int)stoptime + 1];
            }
            

            if (CheckBoxSweepStartStopBack.IsChecked == false)
            {
                for (int t = 0; t < testSrcData.Count(); t++)
                {
                    testSrcData[t] = f1 * Math.Exp(SliderSweepSpeed.Value*Math.Log(2, Math.E) * t / 60.0);
                    if (testSrcData[t] > stopFrequency)
                    {
                        testSrcData[t] = stopFrequency;
                    }
                }
            }
            else
            {
                for (int t = 0; t < testSrcData.Count(); t++)
                {
                    if (t > (testSrcData.Count()/2))
                    {
                        testSrcData[t] = f1 * Math.Exp(SliderSweepSpeed.Value * Math.Log(2, Math.E) * (testSrcData.Count() - t) / 60.0);
                    }
                    else
                    {
                        testSrcData[t] = f1 * Math.Exp(SliderSweepSpeed.Value * Math.Log(2, Math.E) * t / 60.0);
                    }
                    
                    if (testSrcData[t] > stopFrequency)
                    {
                        testSrcData[t] = stopFrequency;
                        if (CheckBoxFixTime.IsChecked == true)
                        {
                            SetTimeOfTest(t - 1);
                            Array.Resize(ref testSrcData, (int)stoptime);
                            break;
                        }
                    }
                }
            }
            plot.PlotAdd(testSrcData, Plot.PLOT_TYPE.PLOT_SRC);
            dataReady = true;
            ControlsEnable(CONTROL_TYPE.BUTTON_START_TEST);
        }

        private void SetTimeOfTest(int time)
        {
            stoptime = time;
            timeLastContent = stoptime.ToString();
            TextBoxTimeOfTest.Text = timeLastContent;
        }



        double startFrequency;
        string startFrequencyLastContent;
        private void TextBoxStartFrequency_TextChanged(object sender, TextChangedEventArgs e)
        {
            double startFrequency;
            bool isNumber = false;
            bool isInRange = false;

            dataReady = false;
            ControlsDiable(CONTROL_TYPE.BUTTON_START_TEST);

            isNumber = double.TryParse(TextBoxStartFrequency.Text, out startFrequency);
            if ((startFrequency >= 5) && (startFrequency <= 5000))
            {
                TextBoxStartFrequency.Background = Brushes.White;
                isInRange = true;
            }
            else
            {
                TextBoxStartFrequency.Background = new SolidColorBrush(Color.FromArgb(120, 240, 17, 17));
                isInRange = false;
            }

            if (TextBoxStartFrequency.Text == "")
            {
                return;
            }

            if (isNumber)
            {
                if (isInRange)
                {
                    this.startFrequency = startFrequency;
                    startFrequencyLastContent = TextBoxStartFrequency.Text;
                }
            }
            else
            {
                TextBoxStartFrequency.Text = TextBoxStartFrequency.Text.Substring(0, TextBoxStartFrequency.Text.Length - 1);
                TextBoxStartFrequency.SelectionStart = TextBoxStartFrequency.Text.Length;
            }


        }


        private void ButtonStart_Click(object sender, RoutedEventArgs e)
        {
            if (testIsRunning == false)
            {
                UInt32[] data = new UInt32[testSrcData.Length];
                for (int i = 0; i < testSrcData.Length; i++)
                {
                    data[i] = (UInt32)Math.Round(100 * testSrcData[i], 0);
                }
                testMeasFrequency = new double[1];
                testMeasAmplitude = new double[1];

                if (CheckBoxHalfSin.IsChecked == true)
                {
                    comm.SetTest(Comm.TEST_TYPE.TEST_TYPE_HALF_SIN, data, data.Length);
                }
                else if (CheckBoxSweepStartStopBack.IsChecked == true)
                {
                    comm.SetTest(Comm.TEST_TYPE.TEST_TYPE_SWEEP_TO_BACK, data, data.Length);
                }
                else
                {
                    comm.SetTest(Comm.TEST_TYPE.TEST_TYPE_STANDARD, data, data.Length);
                }
                
                testIsRunning = true;
                ButtonStart.Content = "Stop Test";
                ControlsDiable(CONTROL_TYPE.CONTROL_TEST_CHANGE);
                OutputPrint("Starting Test", Brushes.Black);
                testTimeProgressLast = -1;
            }
            else
            {
                comm.StopTest();
                testIsRunning = false;
                ButtonStart.Content = "Start Test";
                OutputPrint("Stopping Test", Brushes.Black);
                ControlsEnable(CONTROL_TYPE.CONTROL_TEST_CHANGE);
            }
            
        }

        private void ButtonStartBackTostart()
        {
            testIsRunning = false;
            ButtonStart.Content = "Start Test";
        }

        private void ButtonTakeControl_Click(object sender, RoutedEventArgs e)
        {
            ButtonTakeControl.IsEnabled = false;
            comm.TakeControl();

        }


        private void OutputPrint(string s, Brush brushText)
        {
            Dispatcher.Invoke((Action)delegate
            {
                //TextBoxOutput.Text += string.Format("[{0}]:{1} \n", DateTime.Now.ToLongTimeString(), s);
                //TextBoxOutput.ScrollToEnd();
                TextRange TRTime = new TextRange(TextBoxOutput.Document.ContentEnd, TextBoxOutput.Document.ContentEnd);

                TRTime.Text = string.Format("[{0}]:", DateTime.Now.ToLongTimeString());
                TRTime.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
                TRTime.ApplyPropertyValue(TextElement.FontSizeProperty, (double)10);

                TextRange TRText = new TextRange(TextBoxOutput.Document.ContentEnd, TextBoxOutput.Document.ContentEnd);

                TRText.Text = s + "\r";
                TRText.ApplyPropertyValue(TextElement.ForegroundProperty, brushText);
                TRText.ApplyPropertyValue(TextElement.FontSizeProperty, (double)12);

                TextBoxOutput.ScrollToEnd();
            });

        }

        double[] dataTestFft = {0,9,18,27,36,45,53,62,71,79,88,96,105,113,121,129,136,144,151,158,165,172,178,185,191,197,202,208,213,218,222,227,231,234,238,241,244,246,249,251,252,254,255,255,256,256,256,255,254,253,252,250,248,245,243,240,237,233,229,225,220,216,211,206,200,194,188,182,176,169,162,155,148,141,133,125,117,109,101,93,85,76,67,59,50,41,32,23,14,5,-4,-13,-22,-30,-39,-48,-57,-66,-74,-83,-91,-100,-108,-116,-124,-132,-139,-147,-154,-161,-168,-175,-181,-187,-193,-199,-205,-210,-215,-220,-224,-228,-232,-236,-239,-242,-245,-247,-250,-251,-253,-254,-255,-256,-256,-256,-256,-255,-254,-253,-251,-249,-247,-244,-242,-239,-235,-231,-227,-223,-219,-214,-209,-203,-198,-192,-186,-180,-173,-167,-160,-152,-145,-138,-130,-122,-114,-106,-98,-90,-81,-73,-64,-55,-46,-38,-29,-20,-11,-2,7,16,25,34,43,52,60,69,78,86,95,103,111,119,127,135,142,150,157,164,171,177,184,190,196,201,207,212,217,221,226,230,234,237,240,243,246,248,250,252,253,255,255,256,256,256,255,255,253,252,250,248,246,243,240,237,234,230,226,221,217,212,207,201,196,190,184,177,171,164,157,150,142,135,127,119,111,103,95,86,78,69,60,52,43,34,25,16,7,-2,-11,-20,-29,-38,-46,-55,-64,-73,-81,-90,-98,-106,-114,-122,-130,-138,-145,-152,-160,-167,-173,-180,-186,-192,-198,-203,-209,-214,-219,-223,-227,-231,-235,-239,-242,-244,-247,-249,-251,-253,-254,-255,-256,-256,-256,-256,-255,-254,-253,-251,-250,-247,-245,-242,-239,-236,-232,-228,-224,-220,-215,-210,-205,-199,-193,-187,-181,-175,-168,-161,-154,-147,-139,-132,-124,-116,-108,-100,-91,-83,-74,-66,-57,-48,-39,-30,-22,-13,-4,5,14,23,32,41,50,59,67,76,85,93,101,109,117,125,133,141,148,155,162,169,176,182,188,194,200,206,211,216,220,225,229,233,237,240,243,245,248,250,252,253,254,255,256,256,256,255,255,254,252,251,249,246,244,241,238,234,231,227,222,218,213,208,202,197,191,185,178,172,165,158,151,144,136,129,121,113,105,96,88,79,71,62,53,45,36,27,18,9,0,-9,-18,-27,-36,-45,-53,-62,-71,-79,-88,-96,-105,-113,-121,-129,-136,-144,-151,-158,-165,-172,-178,-185,-191,-197,-202,-208,-213,-218,-222,-227,-231,-234,-238,-241,-244,-246,-249,-251,-252,-254,-255,-255,-256,-256,-256,-255,-254,-253,-252,-250,-248,-245,-243,-240,-237,-233,-229,-225,-220,-216,-211,-206,-200,-194,-188,-182,-176,-169,-162,-155,-148,-141,-133,-125,-117,-109,-101,-93,-85,-76,-67,-59,-50,-41,-32,-23,-14,-5,4,13,22,30,39,48,57,66,74,83,91,100,108,116,124,132,139,147,154,161,168,175,181,187,193,199,205,210,215,220,224,228,232,236,239,242,245,247,250,251,253,254,255,256,256,256,256,255,254,253,251,249,247,244,242,239,235,231,227,223,219,214,209,203,198,192,186,180,173,167,160,152,145,138,130,122,114,106,98,90,81,73,64,55,46,38,29,20,11,2,-7,-16,-25,-34,-43,-52,-60,-69,-78,-86,-95,-103,-111,-119,-127,-135,-142,-150,-157,-164,-171,-177,-184,-190,-196,-201,-207,-212,-217,-221,-226,-230,-234,-237,-240,-243,-246,-248,-250,-252,-253,-255,-255,-256,-256,-256,-255,-255,-253,-252,-250,-248,-246,-243,-240,-237,-234,-230,-226,-221,-217,-212,-207,-201,-196,-190,-184,-177,-171,-164,-157,-150,-142,-135,-127,-119,-111,-103,-95,-86,-78,-69,-60,-52,-43,-34,-25,-16,-7,2,11,20,29,38,46,55,64,73,81,90,98,106,114,122,130,138,145,152,160,167,173,180,186,192,198,203,209,214,219,223,227,231,235,239,242,244,247,249,251,253,254,255,256,256,256,256,255,254,253,251,250,247,245,242,239,236,232,228,224,220,215,210,205,199,193,187,181,175,168,161,154,147,139,132,124,116,108,100,91,83,74,66,57,48,39,30,22,13,4,-5,-14,-23,-32,-41,-50,-59,-67,-76,-85,-93,-101,-109,-117,-125,-133,-141,-148,-155,-162,-169,-176,-182,-188,-194,-200,-206,-211,-216,-220,-225,-229,-233,-237,-240,-243,-245,-248,-250,-252,-253,-254,-255,-256,-256,-256,-255,-255,-254,-252,-251,-249,-246,-244,-241,-238,-234,-231,-227,-222,-218,-213,-208,-202,-197,-191,-185,-178,-172,-165,-158,-151,-144,-136,-129,-121,-113,-105,-96,-88,-79,-71,-62,-53,-45,-36,-27,-18,-9,-0,9,18,27,36,45,53,62,71,79,88,96,105,113,121,129,136,144,151,158,165,172,178,185,191,197,202,208,213,218,222,227,231,234,238,241,244,246,249,251,252,254,255,255,256,256,256,255,254,253,252,250,248,245,243,240,237,233,229,225,220,216,211,206,200,194,188,182,176,169,162,155,148,141,133,125,117,109,101,93,85,76,67,59,50,41,32,23,14,5,-4,-13,-22,-30,-39,-48,-57,-66,-74,-83,-91,-100,-108,-116,-124,-132,-139,-147,-154,-161,-168,-175,-181,-187,-193,-199,-205,-210,-215,-220,-224,-228,-232,-236,-239,-242,-245,-247,-250,-251,-253,-254,-255,-256,-256,-256,-256,-255,-254,-253,-251,-249,-247,-244,-242,-239,-235,-231,-227,-223,-219,-214,-209,-203,-198,-192,-186,-180,-173,-167,-160,-152,-145,-138,-130,-122,-114,-106,-98,-90,-81,-73,-64,-55,-46,-38,-29,-20,-11,-2,7,16,25,34,43,52,60,69,78,86,95,103,111,119,127,135,142,150,157,164,171,177,184,190,196,201,207,212,217,221,226,230,234,237,240,243,246,248,250,252,253,255,255,256,256,256,255,255,253,252,250,248,246,243,240,237,234,230,226,221,217,212,207,201,196,190,184,177,171,164,157,150,142,135,127,119,111,103,95,86,78,69,60,52,43,34,25,16,7,-2,-11,-20,-29,-38,-46,-55,-64,-73,-81,-90,-98,-106,-114,-122,-130,-138,-145,-152,-160,-167,-173,-180,-186,-192,-198,-203,-209,-214,-219,-223,-227,-231,-235,-239,-242,-244,-247,-249,-251,-253,-254,-255,-256,-256,-256,-256,-255,-254,-253,-251,-250,-247,-245,-242,-239,-236,-232,-228,-224,-220,-215,-210,-205,-199,-193,-187,-181,-175,-168,-161,-154,-147,-139,-132,-124,-116,-108,-100,-91,-83,-74,-66,-57,-48,-39,-30,-22,-13,-4,5,14,23,32,41,50,59,67,76,85,93,101,109,117,125,133,141,148,155,162,169,176,182,188,194,200,206,211,216,220,225,229,233,237,240,243,245,248,250,252,253,254,255,256,256,256,255,255,254,252,251,249,246,244,241,238,234,231,227,222,218,213,208,202,197,191,185,178,172,165,158,151,144,136,129,121,113,105,96,88,79,71,62,53,45,36,27,18,9,0,-9,-18,-27,-36,-45,-53,-62,-71,-79,-88,-96,-105,-113,-121,-129,-136,-144,-151,-158,-165,-172,-178,-185,-191,-197,-202,-208,-213,-218,-222,-227,-231,-234,-238,-241,-244,-246,-249,-251,-252,-254,-255,-255,-256,-256,-256,-255,-254,-253,-252,-250,-248,-245,-243,-240,-237,-233,-229,-225,-220,-216,-211,-206,-200,-194,-188,-182,-176,-169,-162,-155,-148,-141,-133,-125,-117,-109,-101,-93,-85,-76,-67,-59,-50,-41,-32,-23,-14,-5,4,13,22,30,39,48,57,66,74,83,91,100,108,116,124,132,139,147,154,161,168,175,181,187,193,199,205,210,215,220,224,228,232,236,239,242,245,247,250,251,253,254,255,256,256,256,256,255,254,253,251,249,247,244,242,239,235,231,227,223,219,214,209,203,198,192,186,180,173,167,160,152,145,138,130,122,114,106,98,90,81,73,64,55,46,38,29,20,11,2,-7,-16,-25,-34,-43,-52,-60,-69,-78,-86,-95,-103,-111,-119,-127,-135,-142,-150,-157,-164,-171,-177,-184,-190,-196,-201,-207,-212,-217,-221,-226,-230,-234,-237,-240,-243,-246,-248,-250,-252,-253,-255,-255,-256,-256,-256,-255,-255,-253,-252,-250,-248,-246,-243,-240,-237,-234,-230,-226,-221,-217,-212,-207,-201,-196,-190,-184,-177,-171,-164,-157,-150,-142,-135,-127,-119,-111,-103,-95,-86,-78,-69,-60,-52,-43,-34,-25,-16,-7,2,11,20,29,38,46,55,64,73,81,90,98,106,114,122,130,138,145,152,160,167,173,180,186,192,198,203,209,214,219,223,227,231,235,239,242,244,247,249,251,253,254,255,256,256,256,256,255,254,253,251,250,247,245,242,239,236,232,228,224,220,215,210,205,199,193,187,181,175,168,161,154,147,139,132,124,116,108,100,91,83,74,66,57,48,39,30,22,13,4,-5,-14,-23,-32,-41,-50,-59,-67,-76,-85,-93,-101,-109,-117,-125,-133,-141,-148,-155,-162,-169,-176,-182,-188,-194,-200,-206,-211,-216,-220,-225,-229,-233,-237,-240,-243,-245,-248,-250,-252,-253,-254,-255,-256,-256,-256,-255,-255,-254,-252,-251,-249,-246,-244,-241,-238,-234,-231,-227,-222,-218,-213,-208,-202,-197,-191,-185,-178,-172,-165,-158,-151,-144,-136,-129,-121,-113,-105,-96,-88,-79,-71,-62,-53,-45,-36,-27,-18,-9,-0,9,18,27,36,45,53,62,71,79,88,96,105,113,121,129,136,144,151,158,165,172,178,185,191,197,202,208,213,218,222,227,231,234,238,241,244,246,249,251,252,254,255,255,256,256,256,255,254,253,252,250,248,245,243,240,237,233,229,225,220,216,211,206,200,194,188,182,176,169,162,155,148,141,133,125,117,109,101,93,85,76,67,59,50,41,32,23,14,5,-4,-13,-22,-30,-39,-48,-57,-66,-74,-83,-91,-100,-108,-116,-124,-132,-139,-147,-154,-161,-168,-175,-181,-187,-193,-199,-205,-210,-215,-220,-224,-228,-232,-236,-239,-242,-245,-247,-250,-251,-253,-254,-255,-256,-256,-256,-256,-255,-254,-253,-251,-249,-247,-244,-242,-239,-235,-231,-227,-223,-219,-214,-209,-203,-198,-192,-186,-180,-173,-167,-160,-152,-145,-138,-130,-122,-114,-106,-98,-90,-81,-73,-64,-55,-46,-38,-29,-20,-11,-2,7,16,25,34,43,52,60,69,78,86,95,103,111,119,127,135,142,150,157,164,171,177,184,190,196,201,207,212,217,221,226,230,234,237,240,243,246,248,250,252,253,255,255,256,256,256,255,255,253,252,250,248,246,243,240,237,234,230,226,221,217,212,207,201,196,190,184,177,171,164,157,150,142,135,127,119
                             };


        private void SliderSweepSpeed_LostMouseCapture(object sender, MouseEventArgs e)
        {
            //double freq;

            
            

            //freq = sProcess.GetFrequency(dataTest);
            //OutputPrint(freq.ToString(), Brushes.Black);

        }

        private void SliderSweepSpeed_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (TextBlockSweepSpeed != null)
            {
                TextBlockSweepSpeed.Text = "Sweep speed: " + SliderSweepSpeed.Value.ToString("0.000");
                CalculateSweep();

            }
            
        }

        private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (TextBlockDispBrig != null)
            { 
                TextBlockDispBrig.Text = "Display Brightness: " + SliderDispBrig.Value.ToString("0");
                comm.SendMessageToServer("dispbrig " + SliderDispBrig.Value.ToString("0"));
            }
        }

        bool plotFreq = true;
        private void PlotChange_Click(object sender, RoutedEventArgs e)
        {
            if (plotFreq == true)
            {
                plotFreq = false;
                ButtonPlotChange.Content = "Show Frequency";
                plot.SizeUpdate(0, this.stoptime, 0, 50000, 0101);
                plot.SetYAxisQuantity(Plot.PLOT_QUANTITY.Amplitude);
                plot.ReRender();
                plot.PlotAdd(testMeasAmplitude, Plot.PLOT_TYPE.PLOT_MEASURE);
                //plot.PlotAdd(testSrcData, Plot.PLOT_TYPE.PLOT_SRC);

            }
            else
            {
                plotFreq = true;
                ButtonPlotChange.Content = "Show Amplitude";
                plot.SizeUpdate(0, this.stoptime, 0, this.stopFrequency,0101);
                plot.SetYAxisQuantity(Plot.PLOT_QUANTITY.Frequency);
                plot.ReRender();
                plot.PlotAdd(testSrcData, Plot.PLOT_TYPE.PLOT_SRC);
                plot.PlotAdd(testMeasFrequency, Plot.PLOT_TYPE.PLOT_MEASURE);
            }

        }

        private void CheckBoxSweepStartStopBack_Unchecked(object sender, RoutedEventArgs e)
        {
            SetTimeOfTest((int)(stoptime/2));
            CheckBoxFixTime.IsEnabled = true;
            testSrcData = null;
        }

        private void CheckBoxSweepStartStopBack_Checked(object sender, RoutedEventArgs e)
        {
            SetTimeOfTest(2 * (int)stoptime);
            CheckBoxFixTime.IsChecked = false;
            CheckBoxFixTime.IsEnabled = false;
        }

        private void CheckBoxHalfSin_Checked(object sender, RoutedEventArgs e)
        {
            ControlsDiable(CONTROL_TYPE.CONTROL_HALF_SIN);
        }


        private void CheckBoxHalfSin_Unchecked(object sender, RoutedEventArgs e)
        {
            ControlsEnable(CONTROL_TYPE.CONTROL_HALF_SIN);
        }

        private void CheckBoxFixTime_Checked(object sender, RoutedEventArgs e)
        {
            CalculateSweep();
        }

        private void ButtonCSVSave_Click(object sender, RoutedEventArgs e)
        {
           
            Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();


            if (testMeasFrequency != null)
            {
                sfd.Filter = "CSV|*.csv";
                sfd.Title = "Save an CSV File";
                sfd.ShowDialog();
                if (sfd.FileName != "")
                {
                    Title = sfd.FileName;
                    StringBuilder sb = new StringBuilder();


                        for (int index = 0; index < testSrcData.Length; index++)
                        {
                            sb.AppendLine(string.Join(",",index, testMeasFrequency[index], testMeasAmplitude[index]));
                        }
                        File.WriteAllText(sfd.FileName, sb.ToString());
                }
            }
            else
            {
                OutputPrint("There are no measured data", Brushes.Red);
            }
        }

        private void ButtonCSVLoad_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.Filter = "CSV|*.csv";

            Nullable<bool> result = ofd.ShowDialog();

            if (result == true)
            {
                var lines = File.ReadAllLines(ofd.FileName);
                int index = 0;
                double doubleData = 0;

                testSrcData = new double[lines.Count()];

                for (int i = 0; i < lines.Count(); i++)
                {
                    string[] data = lines[i].Split(',');
                    if (int.TryParse(data[0], out index))
                    {
                        if (double.TryParse(data[1], out doubleData))
                        {
                            testSrcData[index] = doubleData;
                        }
                        else
                        {
                            OutputPrint("Invalid CSV.", Brushes.Red);
                            return;
                        }
                    }
                    else
                    {
                        OutputPrint("Invalid CSV.", Brushes.Red);
                        return;
                    }
                    
                    
                }

                //stoptime = lines.Count();
                TextBoxTimeOfTest.Text = (lines.Count()-1).ToString();
                TextBoxStopFrequency.Text = (100*Math.Ceiling(testSrcData[testSrcData.Length - 1]/100)).ToString();
                plot.PlotAdd(testSrcData, Plot.PLOT_TYPE.PLOT_SRC);
                dataReady = true;
                ControlsEnable(CONTROL_TYPE.BUTTON_START_TEST);
                OutputPrint("New test data loaded.", Brushes.Gray);

            }
            
        }







    }
}
