using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using Ionic.Zip;
using System.IO;
using FTD2XX_NET;
using IniParser;
using System.Media;
using System.Diagnostics;

namespace Nastavení_PAO
{
    
    public partial class Form1 : Form
    {
        public UsbCom usb = new UsbCom(997,5000,0,FTDI.FT_DATA_BITS.FT_BITS_8,FTDI.FT_STOP_BITS.FT_STOP_BITS_2,FTDI.FT_PARITY.FT_PARITY_EVEN,0x015,0x00,FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE);
        public InfoConsole console = new InfoConsole(ConsoleColor.Green, ConsoleColor.Red, ConsoleColor.Cyan, ConsoleColor.Magenta,ConsoleColor.Yellow,ConsoleColor.White);
        public bool EnableBlockErrorMessage = false;
        public int rohx, rohy;
        public bool shifttop, shiftdown, shiftleft, shiftright;
        public Bitmap Scheme, Sho, Shz, Svo, Svz, Oho, Ohz, Ovo, Ovz, Slv_p1, Slv_p2, Slv_p1x, Slv_p2x;
        public Point[] ControlSettersLoc = new Point[50];
        int shiftconst, timerconst;
        bool FailMuxSettings = true;
        bool Err = false;
        List<ListOfFTDIs> ad;
        bool EventDrivenKeyboard = false;
        Timer KeyDrivenEvent, EmergencyChecker;
        bool waspainted = false;
        bool isMaximalized = false;
        public MsgBoxMod mbm;
    
        public Point defaultLoc;
        public Timer Proftim;

        string RuntimeDir, subDir;

        public void Inicializace()
        {
            DisableControls(true);
            RuntimeDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            mbm = new MsgBoxMod();

            mbm.FComplStatus += new MsgBoxMod.FCompl(mbm_FComplStatus);

            //Inicializace systému
            usb.SendingByteToRAMEventHandlerStatus += new UsbCom.SendingByteToRAMEventHandler(SendingByteToRAMEventInterface);
            usb.SendedByteToRAMEventHandlerStatus += new UsbCom.SendedByteToRAMEventHandler(SendedByteToRAMEventInterface);
            usb.SendingByteToEEPROMEventHandlerStatus += new UsbCom.SendingByteToEEPROMEventHandler(SendingByteToEEPROMEventInterface);
            usb.SendedByteToEEPROMEventHandlerStatus += new UsbCom.SendedByteToEEPROMEventHandler(SendedByteToEEPROMEventInterface);
            usb.RecivingByteFromRAMEventHandlerStatus += new UsbCom.RecivingByteFromRAMEventHandler(RecivingByteFromRAMEventInterface);
            usb.RecivedByteFromRAMEventHandlerStatus += new UsbCom.RecivedByteFromRAMEventHandler(RecivedByteFromRAMEventInterface);
            usb.RecivingByteFromEEPROMEventHandlerStatus += new UsbCom.RecivingByteFromEEPROMEventHandler(RecivingByteFromEEPROMEventInterface);
            usb.RecivedByteFromEEPROMEventHandlerStatus += new UsbCom.RecivedByteFromEEPROMEventHandler(RecivedByteFromEEPROMEventInterface);
            usb.ProgrammingPAOEventHandlerStatus += new UsbCom.ProgrammingPAOEventHandler(ProgrammingPAOEventInterface);
            usb.ProgrammedPAOEventHandlerStatus += new UsbCom.ProgrammedPAOEventHandler(ProgrammedPAOEventInterface);
            usb.CircuitEchoingEventHandlerStatus += new UsbCom.CircuitEchoingEventHandler(CircuitEchoingEventInterface);
            usb.CircuitEchoedEventHandlerStatus += new UsbCom.CircuitEchoedEventHandler(CircuitEchoedEventInterface);
            usb.ErrorMessageEventHandlerStatus += new UsbCom.ErrorMessageEventHandler(ErrorMessageEventInterface);
            usb.ProtocolCrashStatus +=new ProtocolCrash(usb_ProtocolCrashStatus);


            usb.LoadProgressBarInfoStatus +=new UsbCom.LoadProgressBarInfo(LoadProgressBar);

            defaultLoc = label4.Location;
            Proftim = new Timer();
            Proftim.Interval = 1500;
            Proftim.Enabled = false;
            Proftim.Stop();
            Proftim.Tick+=new EventHandler(Proftim_Tick);


            usb.profiler.FilesInDirectoryStatus +=new Profiler.FilesInDirectory(profiler_FilesInDirectoryStatus);

            usb.ReloadThumbinalsHandlerStatus += new ReloadThumbinalsHandler(ReloadThumbinals);
            usb.ReloadSchemeHandlerStatus += new ReloadSchemeSetterHandler(ReloadGUI);
            usb.EmptyDeviceHandlerStatus += new EmptyDeviceHandler(EmptyDeviceMessage);

            usb.GetConnectedDevicesHandlerStatus += new UsbCom.GetConnectedDevicesHandler(ReloadListOfDevices);

            usb.SetBorderAdressValues(0x01, 0xE);
            usb.CountOfElementsOfDataGSX = 14;
            ad = new List<ListOfFTDIs>();

            SetEnabledButtons(false);

            label3.Visible = true;
            checkBox1.Visible = true;

            label4.Visible = false;
            label5.Visible = false;
            textBox1.Visible = false;
            button9.Enabled = false;
            button11.Enabled = false;
            button12.Enabled = false;


            KeyDrivenEvent = new Timer();
            KeyDrivenEvent.Interval = 1500;
            KeyDrivenEvent.Stop();
            KeyDrivenEvent.Enabled = false;
            KeyDrivenEvent.Tick += new EventHandler(KeyPressed);

            EmergencyChecker = new Timer();
            EmergencyChecker.Interval = 100;
            EmergencyChecker.Tick+=new EventHandler(EmergencyChecker_Tick);

            List<int> inidata = new List<int>();

            LoadConfig(ref inidata);

            checkBox3.Checked = false;
           
            trackBar1.Value = inidata[0];
            trackBar2.Value = inidata[1];

            shiftconst = inidata[0];
            timerconst = inidata[1];

            checkBox3.Checked = true;

            trackBar2.Value = inidata[2];
            KeyDrivenEvent.Interval = inidata[2];

            checkBox3.Checked = false;

            //Debugovací režimy

            label3.Visible = checkBox1.Visible = false;
            checkBox2.Checked = false;
            checkBox2.Checked = true;
            checkBox2.Checked = false;
            checkBox2.Visible = false;

            //-----------------

            usb.profiler.SearchFiles();

            try
            {

                InitGUI();

            }

            catch (ZipException e)
            {

                MessageBox.Show("Selhala inicializace renderu, archiv fragmentů se nepodařilo upravit." + Environment.NewLine + Environment.NewLine + "Zpráva chyby: " + e.Message, "Chyba programu", MessageBoxButtons.OK, MessageBoxIcon.Error);

                Err = true;

            }

            catch (Exception e)
            {

                MessageBox.Show("Nezdařilo se incializovat renderer." + Environment.NewLine + Environment.NewLine + "Zpráva chyby: " + e.Message, "Chyba programu", MessageBoxButtons.OK, MessageBoxIcon.Error);

                Err = true;

            }

            }

        public void mbm_FComplStatus(object sender, EventArgs e) {

            mbm.Bridge____SetForegroundWindow(this.Text);
            DisableControls(false);
            SchemePaint();
            this.WindowState = FormWindowState.Maximized;
        
        }

        public void usb_ProtocolCrashStatus() {

            string crash_profiler_name = "crash_" + DateTime.Now.ToString("d_M_yyyy HH_mm_ss");

            MessageBox.Show("Byla detekována kritická chyba hardwaru, nastavení schématu bude uloženo jako \"" + crash_profiler_name + "\" program bude ukončen.\nProsím restartujte hardware a spusťte znovu program, omlouváme se za vzniklé potíže.", "Fatální chyba programu",MessageBoxButtons.OK,MessageBoxIcon.Error);

            try {

                usb.profiler.WriteXmlFile(crash_profiler_name, usb.profiler.ConvertMemToXml(usb.BytesMemory));
            
            }

            catch (Exception x)
            {

                mbm.MakeMessage("Chyba souborové operace profileru." + Environment.NewLine + Environment.NewLine + "Zpráva chyby: " + x.Message, "Chyba", SystemIcons.Error);

            }
            
            Process.GetCurrentProcess().Kill();

        }

        public void InitGUI() {
      

            rohx = 0;
            rohy = 0;

            shifttop = false;
            shiftdown = false;
            shiftleft = false;
            shiftright = false;
            

                MemoryStream a_ = new MemoryStream();
                MemoryStream b_ = new MemoryStream();
                MemoryStream c_ = new MemoryStream();
                MemoryStream d_ = new MemoryStream();
                MemoryStream e_ = new MemoryStream();
                MemoryStream f_ = new MemoryStream();
                MemoryStream g_ = new MemoryStream();
                MemoryStream h_ = new MemoryStream();
                MemoryStream i_ = new MemoryStream();
                MemoryStream x_ = new MemoryStream();
                MemoryStream k_ = new MemoryStream();
                MemoryStream l_ = new MemoryStream();
                MemoryStream m_ = new MemoryStream();


                    ZipFile archiv = ZipFile.Read(RuntimeDir + "\\" + "scheme.zip");
                

                    archiv["scheme.png"].Extract(a_);//!!!!!!!!_scheme_puvodni.png
                    archiv["mux_sho.png"].Extract(b_);
                    archiv["mux_shz.png"].Extract(c_);
                    archiv["mux_svo.png"].Extract(d_);
                    archiv["mux_svz.png"].Extract(e_);
                    archiv["out_oho.png"].Extract(f_);
                    archiv["out_ohz.png"].Extract(g_);
                    archiv["out_ovo.png"].Extract(h_);
                    archiv["out_ovz.png"].Extract(i_);
                    archiv["slv_p1.png"].Extract(x_);
                    archiv["slv_p2.png"].Extract(k_);
                    archiv["slv_p1x.png"].Extract(l_);
                    archiv["slv_p2x.png"].Extract(m_);

                   
                    Scheme = new Bitmap(Bitmap.FromStream(a_));

                    Sho = new Bitmap(Image.FromStream(b_));
                    Shz = new Bitmap(Image.FromStream(c_));
                    Svo = new Bitmap(Image.FromStream(d_));
                    Svz = new Bitmap(Image.FromStream(e_));

                    Oho = new Bitmap(Image.FromStream(f_));
                    Ohz = new Bitmap(Image.FromStream(g_));
                    Ovo = new Bitmap(Image.FromStream(h_));
                    Ovz = new Bitmap(Image.FromStream(i_));

                    Slv_p1 = new Bitmap(Image.FromStream(x_));
                    Slv_p2 = new Bitmap(Image.FromStream(k_));
                    Slv_p1x = new Bitmap(Image.FromStream(l_));
                    Slv_p2x = new Bitmap(Image.FromStream(m_));

                    

                    archiv.Dispose();


                    Premaluj();


                    AddGainsToSettersVGA();

                    ControlSettersLoc[0] = new Point(851, 827);//VGA1
                    ControlSettersLoc[1] = new Point(1160, 811);//VGA2
                    ControlSettersLoc[2] = new Point(677, 805);//mx1
                    ControlSettersLoc[3] = new Point(1011, 805);//mx2
                    ControlSettersLoc[4] = new Point(1347, 805);//mx3
                    ControlSettersLoc[5] = new Point(1683, 805);//mx4
                    ControlSettersLoc[6] = new Point(2015, 805);//mx5
                    ControlSettersLoc[7] = new Point(75, 247);//out1
                    ControlSettersLoc[8] = new Point(509, 189);//Out2
                    ControlSettersLoc[9] = new Point(1266, 260);//Out3
                    ControlSettersLoc[10] = new Point(1818, 799);//FDCAgain
                    ControlSettersLoc[11] = new Point(904, 102);//Sel_lin_ver
                    ControlSettersLoc[12] = new Point(99, 975);//ServoloopS1
                    ControlSettersLoc[13] = new Point(927, 284);//ServoloopS2


                    Graphics j = Graphics.FromImage(Scheme);

                    HatchBrush pozadi = new HatchBrush(HatchStyle.Percent05, Color.Black, Form.DefaultBackColor);

                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[0].X, ControlSettersLoc[0].Y, VGA1_Setter_group_ren.Size.Width, VGA1_Setter_group_ren.Size.Height));
                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[1].X, ControlSettersLoc[1].Y, VGA2_Setter_group_ren.Size.Width, VGA2_Setter_group_ren.Size.Height));

                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[2].X, ControlSettersLoc[2].Y, mx1.Size.Width, mx1.Height));
                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[3].X, ControlSettersLoc[3].Y, mx2.Size.Width, mx2.Height));
                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[4].X, ControlSettersLoc[4].Y, mx3.Size.Width, mx3.Height));
                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[5].X, ControlSettersLoc[5].Y, mx4.Size.Width, mx4.Height));
                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[6].X, ControlSettersLoc[6].Y, mx5.Size.Width, mx5.Height));

                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[7].X, ControlSettersLoc[7].Y, Out1.Size.Width, Out1.Height));
                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[8].X, ControlSettersLoc[8].Y, Out2.Size.Width, Out2.Height));
                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[9].X, ControlSettersLoc[9].Y, Out3.Size.Width, Out3.Height));

                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[10].X, ControlSettersLoc[10].Y, fdcaG.Size.Width, fdcaG.Height));

                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[11].X, ControlSettersLoc[11].Y, SLV_group.Size.Width, SLV_group.Height));

                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[12].X, ControlSettersLoc[12].Y, servoloops1_group.Size.Width, servoloops1_group.Height));
                    j.FillRectangle(pozadi, new Rectangle(ControlSettersLoc[13].X, ControlSettersLoc[13].Y, servoloops2_group.Size.Width, servoloops2_group.Height));

                    j.Dispose();

                    // mx1d.Checked = mx1g.Checked = true;
                    //mx2d.Checked = mx2g.Checked = true;
                    //mx3d.Checked = mx3g.Checked = true;
                    //mx4d.Checked = mx4g.Checked = true;
                    //mx5d.Checked = mx5g.Checked = true;

                    mx1L.Text = mx2L.Text = mx3L.Text = mx4L.Text = mx5L.Text = "Platná kombinace";
                    mx1L.ForeColor = mx2L.ForeColor = mx3L.ForeColor = mx4L.ForeColor = mx5L.ForeColor = Color.Green;

                    //Out1s.Checked = true;
                    //Out2s.Checked = true;
                    //Out3s.Checked = true;

                    ComponentSettingsRendering(true);
                    ComponentSettingsRendering(false);

                
        }

        public void KeyPressed(object sender, EventArgs e) {

            if (EventDrivenKeyboard == true)
            {
                EventDrivenKeyboard = false;
                shiftdown = shiftleft = shiftright = shifttop = false;
                ComponentSettingsRendering(false);
            }

            KeyDrivenEvent.Stop();
            KeyDrivenEvent.Enabled = false;
        
        }

        public void EmergencyCheckerStarter(int c) {

            EmergencyChecker.Interval = c;
            EmergencyChecker.Enabled = true;
            EmergencyChecker.Start();
        
        }

        public void EmergencyChecker_Tick(object sender, EventArgs e) {

            SchemePaint();
            EmergencyChecker.Stop();
            EmergencyChecker.Enabled = false;
        
        }

        
    public void DrawSwitchPositionInOut(String WhatOut, bool sw_a, bool sw_s) { 
        
        //Prototyp Outu
            int Dx, Dy;
            Point a,s;
            Dx = 0;
            Dy = 0;

            a = new Point(1, 37);//Ok
            s = new Point(72, 88);


            Graphics j = Graphics.FromImage(Scheme);
            
            if (WhatOut == "1")
            {

                Dx = 322;
                Dy = 225;

            }

            if (WhatOut == "2")
            {

                Dx = 670;
               Dy = 237;

            }

            if (WhatOut == "3")
            {

                Dx = 1504;
                Dy = 237;
                a.X -= 1;
            }

            a.X += Dx;
            a.Y += Dy;
            s.X += Dx;
            s.Y += Dy;
            
            if (sw_a == true)
            {

                j.DrawImageUnscaled(Ovz, a.X - 1, a.Y);
             

            }
            else
            {

                j.DrawImageUnscaled(Ovo, a.X - 1, a.Y);
               
            }
            if ((!sw_s) == true)
            {

                j.DrawImageUnscaled(Ohz, s.X - 3, s.Y);
                
            }
            else
            {

                j.DrawImageUnscaled(Oho, s.X - 3, s.Y);
            

            }
            j.Dispose();
            SchemePaint();

        }


    public void Premaluj() {


        Color pseudowhite = Slv_p2x.GetPixel(0, 0);

        for (int i = 0; i < Sho.Width; i++)
        {

            for (int h = 0; h < Sho.Height; h++)
            {

                if (Sho.GetPixel(i, h) == pseudowhite)
                {

                    Sho.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }

        if (Scheme.GetPixel(0,0) == pseudowhite) {

            Guid g = Guid.NewGuid();
            string random_string = Convert.ToBase64String(g.ToByteArray());
            random_string = random_string.Replace("=", "");
            random_string = random_string.Replace("+", "");


            Bitmap Scheme_backup = new Bitmap(Scheme);

            for (int i = 0; i < Scheme.Width; i++)
            {

                for (int h = 0; h < Scheme.Height; h++)
                {

                    if (Scheme.GetPixel(i, h) == pseudowhite)
                    {

                        Scheme.SetPixel(i, h, Form.DefaultBackColor);

                    }

                }
            }

            
                Scheme.Save(RuntimeDir + "\\" + "scheme.png", System.Drawing.Imaging.ImageFormat.Png);
                Scheme_backup.Save(RuntimeDir + "\\" + "scheme_" + random_string + ".png", System.Drawing.Imaging.ImageFormat.Png);
            
          

            ZipFile archiv = ZipFile.Read(RuntimeDir + "\\" + "scheme.zip");

            archiv.RemoveEntry("scheme.png");
            archiv.AddFile(@"scheme.png");
            archiv.AddFile(@"scheme_" + random_string + ".png");

            archiv.Save(RuntimeDir + "\\" + random_string + ".zip");

            archiv.Dispose();

            File.Delete(RuntimeDir + "\\" + "scheme.png");
            File.Delete(RuntimeDir + "\\" + "scheme_" + random_string + ".png");
            File.Delete(RuntimeDir + "\\" + "scheme.zip");
            File.Copy(RuntimeDir + "\\" + random_string + ".zip", "scheme.zip");
            File.Delete(RuntimeDir + "\\" + random_string + ".zip");
        }

        for (int i = 0; i < Shz.Width; i++)
        {

            for (int h = 0; h < Shz.Height; h++)
            {

                if (Shz.GetPixel(i, h) == pseudowhite)
                {

                    Shz.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }


        for (int i = 0; i < Svo.Width; i++)
        {

            for (int h = 0; h < Svo.Height; h++)
            {

                if (Svo.GetPixel(i, h) == pseudowhite)
                {

                    Svo.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }


        for (int i = 0; i < Svz.Width; i++)
        {

            for (int h = 0; h < Svz.Height; h++)
            {

                if (Svz.GetPixel(i, h) == pseudowhite)
                {

                    Svz.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }


        for (int i = 0; i < Oho.Width; i++)
        {

            for (int h = 0; h < Oho.Height; h++)
            {

                if (Oho.GetPixel(i, h) == pseudowhite)
                {

                    Oho.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }

        for (int i = 0; i < Ohz.Width; i++)
        {

            for (int h = 0; h < Ohz.Height; h++)
            {

                if (Ohz.GetPixel(i, h) == pseudowhite)
                {

                    Ohz.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }


        for (int i = 0; i < Ovo.Width; i++)
        {

            for (int h = 0; h < Ovo.Height; h++)
            {

                if (Ovo.GetPixel(i, h) == pseudowhite)
                {

                    Ovo.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }


        for (int i = 0; i < Ovz.Width; i++)
        {

            for (int h = 0; h < Ovz.Height; h++)
            {

                if (Ovz.GetPixel(i, h) == pseudowhite)
                {

                    Ovz.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }


        for (int i = 0; i < Slv_p1.Width; i++)
        {

            for (int h = 0; h < Slv_p1.Height; h++)
            {

                if (Slv_p1.GetPixel(i, h) == pseudowhite)
                {

                    Slv_p1.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }

        for (int i = 0; i < Slv_p2.Width; i++)
        {

            for (int h = 0; h < Slv_p2.Height; h++)
            {

                if (Slv_p2.GetPixel(i, h) == pseudowhite)
                {

                    Slv_p2.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }



        for (int i = 0; i < Slv_p1x.Width; i++)
        {

            for (int h = 0; h < Slv_p1x.Height; h++)
            {

                if (Slv_p1x.GetPixel(i, h) == pseudowhite)
                {

                    Slv_p1x.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }

        for (int i = 0; i < Slv_p2x.Width; i++)
        {

            for (int h = 0; h < Slv_p2x.Height; h++)
            {

                if (Slv_p2x.GetPixel(i, h) == pseudowhite)
                {

                    Slv_p2x.SetPixel(i, h, Form.DefaultBackColor);

                }

            }
        }

    
    }

    public void DrawSLVState(bool sel)
    {
        Point a, b, c, d;

        a = new Point(676, 126);
        b = new Point(700, 126);
        c = new Point(1509, 135);
        d = new Point(1533, 135);

        Graphics j = Graphics.FromImage(Scheme);

        if (sel == true)
        {

            j.DrawImageUnscaled(Slv_p1, a.X, a.Y);
            j.DrawImageUnscaled(Slv_p1, b.X, b.Y);
            j.DrawImageUnscaled(Slv_p1x, c.X, c.Y);
            j.DrawImageUnscaled(Slv_p1x, d.X, d.Y);

        }
        else {

            j.DrawImageUnscaled(Slv_p2, a.X, a.Y);
            j.DrawImageUnscaled(Slv_p2, b.X, b.Y);
            j.DrawImageUnscaled(Slv_p2x, c.X, c.Y);
            j.DrawImageUnscaled(Slv_p2x, d.X, d.Y);
        
        
        }

        j.Dispose();
        SchemePaint();

    }

        public void DrawSwitchPositionMux(String WhatMUX, bool swa, bool swb, bool swc, bool swd, bool swg) { 
        
        //Prototyp Muxu
            int Dx, Dy;
            Point a, b, c, d,g;
            Point a2, b2, c2, d2, g2;
            Dx = 0;
            Dy = 0;

            a = new Point(37, 52);//Ok
            b = new Point(81,52);
            c = new Point(88, 16);
            d = new Point(51,67);
            g = new Point(21, 103);//ok

            a2 = new Point(37, 187);//Ok
            b2 = new Point(81, 187);
            c2 = new Point(88, 221);
            d2 = new Point(50, 170);
            g2 = new Point(21, 137);//ok

            Graphics j = Graphics.FromImage(Scheme);

            if (WhatMUX == "1") {

                Dx = 668;
                Dy = 459;

            }

            if (WhatMUX == "2")
            {

                Dx = 1002;
                Dy = 459;

            }

            if (WhatMUX == "3")
            {

                Dx = 1336;
                Dy = 459;

            }

            if (WhatMUX == "4")
            {

                Dx = 1671;
                Dy = 459;

            }

            if (WhatMUX == "5")
            {

                Dx = 2004;
                Dy = 459;

            }


            a.X += Dx;
            a.Y += Dy;
            b.X += Dx;
            b.Y += Dy;
            c.X += Dx;
            c.Y += Dy;
            d.X += Dx;
            d.Y += Dy;
            g.X += Dx;
            g.Y += Dy;

            a2.X += Dx;
            a2.Y += Dy;
            b2.X += Dx;
            b2.Y += Dy;
            c2.X += Dx;
            c2.Y += Dy;
            d2.X += Dx;
            d2.Y += Dy;
            g2.X += Dx;
            g2.Y += Dy;

                if (swa == true) {

                    j.DrawImageUnscaled(Svz, a.X - 1, a.Y);
                    j.DrawImageUnscaled(Svz, a2.X - 1, a2.Y);
                
                }
                else{

                    j.DrawImageUnscaled(Svo, a.X, a.Y);
                    j.DrawImageUnscaled(Svo, a2.X, a2.Y);
                
                }

                if (swb == true) {

                    j.DrawImageUnscaled(Svz, b.X - 1,b.Y);
                    j.DrawImageUnscaled(Svz, b2.X - 1, b2.Y);
                
                }
                else{
                
                j.DrawImageUnscaled(Svo,b.X,b.Y);
                j.DrawImageUnscaled(Svo, b2.X, b2.Y);
                
                }

                if (swc == true) {

                    j.DrawImageUnscaled(Shz, c.X, c.Y);
                    j.DrawImageUnscaled(Shz, c2.X, c2.Y);
                
                }
                else{
                
                j.DrawImageUnscaled(Sho,c.X,c.Y-1);
                j.DrawImageUnscaled(Sho, c2.X, c2.Y-1);
                
                }

                if (swd == true) { 
                
                j.DrawImageUnscaled(Shz,d.X,d.Y);
                j.DrawImageUnscaled(Shz, d2.X, d2.Y);
                
                }
                else{
                
                j.DrawImageUnscaled(Sho,d.X,d.Y-1);
                j.DrawImageUnscaled(Sho, d2.X, d2.Y-1);
                
                }


                if (swg == true) {

                    j.DrawImageUnscaled(Svz, g.X-1,g.Y);
                    //g'
                    j.DrawImageUnscaled(Svz, g2.X-1, g2.Y);

                }
                else
                {

                    j.DrawImageUnscaled(Svo, g.X,g.Y);

                    //g'
                    j.DrawImageUnscaled(Svo, g2.X, g2.Y);
                }

       

            SchemePaint();
        
        }

        public void ReloadGUI()
        {
        //Načetli jsme nastavení z atmela, je potřeba aktualizovat vlastnosti a podle toho nastavit Schema
        //Reload VGA1,VGA2
           // VGA1GainSetter.SelectedValue = usb.ControlRegisters.VGAGainS[usb.ControlRegisters.VGA_1GAINCode];
            VGA1GainSetter.SelectedIndex = usb.ControlRegisters.VGA_1GAINCode;
            VGA2GainSetter.SelectedIndex = usb.ControlRegisters.VGA_2GAINCode;

        //Reload MUXs

            MuxSettingsByteToSwitch m1 = usb.ControlRegisters.MuxCombToSw(usb.ControlRegisters.TstswLNA1);
            MuxSettingsByteToSwitch m2 = usb.ControlRegisters.MuxCombToSw(usb.ControlRegisters.TstswVGA1);
            MuxSettingsByteToSwitch m3 = usb.ControlRegisters.MuxCombToSw(usb.ControlRegisters.TstswVGA2);
            MuxSettingsByteToSwitch m4 = usb.ControlRegisters.MuxCombToSw(usb.ControlRegisters.TstswA2);
            MuxSettingsByteToSwitch m5 = usb.ControlRegisters.MuxCombToSw(usb.ControlRegisters.TstSDM);
            
            mx1a.Checked = m1.swa_;
            mx1b.Checked = m1.swb_;
            mx1c.Checked = m1.swc_;
            mx1d.Checked = m1.swd_;
            mx1g.Checked = m1.swg_;

            mx2a.Checked = m2.swa_;
            mx2b.Checked = m2.swb_;
            mx2c.Checked = m2.swc_;
            mx2d.Checked = m2.swd_;
            mx2g.Checked = m2.swg_;

            mx3a.Checked = m3.swa_;
            mx3b.Checked = m3.swb_;
            mx3c.Checked = m3.swc_;
            mx3d.Checked = m3.swd_;
            mx3g.Checked = m3.swg_;

            mx4a.Checked = m4.swa_;
            mx4b.Checked = m4.swb_;
            mx4c.Checked = m4.swc_;
            mx4d.Checked = m4.swd_;
            mx4g.Checked = m4.swg_;

            mx5a.Checked = m5.swa_;
            mx5b.Checked = m5.swb_;
            mx5c.Checked = m5.swc_;
            mx5d.Checked = m5.swd_;
            mx5g.Checked = m5.swg_;

            //Reload switches OUT
            Out1a.Checked = usb.ControlRegisters.SWgmTIA1_A;
            Out1s.Checked = usb.ControlRegisters.SWgmTIA1_S;
            Out2a.Checked = usb.ControlRegisters.SWLNA_VGA_A;
            Out2s.Checked = usb.ControlRegisters.SWLNA_VGA_S;
            Out3a.Checked = usb.ControlRegisters.SWVGAA2_A;
            Out3s.Checked = usb.ControlRegisters.SWVGAA2_S;

            FDCAgain1.Checked = usb.ControlRegisters.SDBUFp5dB;
            sel_lin_ver_sw.Checked = usb.ControlRegisters.SEL_LIN_ver;

            servoloops1.Checked = usb.ControlRegisters.SERVO_ENAS1;
            servoloops2.Checked = usb.ControlRegisters.SERVO_ENAS2;

            //Checked changed nezareaguje vždy :-(
            DrawSwitchPositionInOut("1", Out1a.Checked, Out1s.Checked);
            DrawSwitchPositionInOut("2", Out2a.Checked, Out2s.Checked);
            DrawSwitchPositionInOut("3", Out3a.Checked, Out3s.Checked);

            DrawSwitchPositionMux("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked);
            DrawSwitchPositionMux("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked);
            DrawSwitchPositionMux("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked);
            DrawSwitchPositionMux("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked);
            DrawSwitchPositionMux("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked);

            console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Info, DateTime.Now, "Schéma bylo překresleno podle nových hodnot.");

        }


        public void SaveConfig(int val1, int val2, int val3) {

            FileIniDataParser konfigurace = new FileIniDataParser();
            IniData inidata = new IniData();
            inidata.Sections.AddSection("nastaveni_vykreslovani");
            inidata["nastaveni_vykreslovani"].AddKey("posun_schematu", val1.ToString());
            inidata["nastaveni_vykreslovani"].AddKey("casovac_snimku", val2.ToString());
            inidata["nastaveni_vykreslovani"].AddKey("casovac_klavesnice", val3.ToString());
            konfigurace.SaveFile(RuntimeDir + "\\" + "config.ini", inidata);
        
        
        }
     
        public void LoadConfig(ref List<int> list) {


            if (File.Exists(RuntimeDir + "\\" + "config.ini"))
            {
                FileIniDataParser konfigurace = new FileIniDataParser();
                IniData inidata = konfigurace.LoadFile(RuntimeDir + "\\" + "config.ini");

                if (int.Parse(inidata["nastaveni_vykreslovani"]["posun_schematu"]) != 0)
                {
                    list.Add(int.Parse(inidata["nastaveni_vykreslovani"]["posun_schematu"]));

                }
                else {

                    list.Add(trackBar1.Minimum);
                
                }

                if (int.Parse(inidata["nastaveni_vykreslovani"]["casovac_snimku"]) != 0)
                {
                    list.Add(int.Parse(inidata["nastaveni_vykreslovani"]["casovac_snimku"]));
                }
                else {

                    list.Add(trackBar2.Minimum);
                
                }


                if (int.Parse(inidata["nastaveni_vykreslovani"]["casovac_klavesnice"]) != 0)
                {

                    list.Add(int.Parse(inidata["nastaveni_vykreslovani"]["casovac_klavesnice"]));
                }
                else {

                    list.Add(trackBar2.Minimum);
                
                }
               
            }
            else {

                list.Add(trackBar1.Minimum);
                list.Add(trackBar2.Minimum);
                list.Add(trackBar2.Minimum);
            
            }
        }

      

        public void profiler_FilesInDirectoryStatus(object sender, FilesInDirectoryArgs e) {

            listBox1.BeginUpdate();
            listBox1.Items.Clear();

            for (int i = 0; i < e.Lx.Count; i++) {

                listBox1.Items.Add(e.Lx[i]);
            
            }

            listBox1.EndUpdate();
        
        }

        public bool isShifted = false;


        public void DivideCharactersBetweenTwoLines(string str, int numberofletters)
        {
            usb.FindFTDIDevice();

            if (usb.SetActiveDeviceLoc != 999999)
            {
                SetEnabledButtons(false);
            }
            
            progressBar1.Visible = false;

            if (str.Length > numberofletters)
            {
                if (isShifted == true)
                {


                    label4.Location = defaultLoc;
                    label5.Location = new Point(label4.Location.X, label4.Location.Y + label4.Size.Height);
                    isShifted = false;
                }

                label5.Visible = label4.Visible = true;
                //25 charakterů na řádek

                string[] stra = str.Split(' ');

                int counter = 0;

                label4.Text = "";
                label5.Text = "";

                for (int i = 0; i < stra.Length; i++)
                {

                    counter += stra[i].Length + 1;

                    if (counter > numberofletters)
                    {

                        for (int y = 0; y < i; y++)
                        {

                            label4.Text += stra[y] + " ";

                        }

                        for (int z = i; z < stra.Length; z++)
                        {

                            label5.Text += stra[z] + " ";

                        }

                        if (label5.Text.Length > numberofletters)
                        {

                            char[] s = label5.Text.ToCharArray();
                            label5.Text = "";

                            for (int z = 0; z < 21; z++)
                            {

                                label5.Text += s[z];

                            }

                            label5.Text += " ...";
                        }

                        break;
                    }

                }
            }
            else
            {
                if (isShifted == false)
                {
                    label4.Visible = true;
                    label5.Visible = false;
                    label5.Text = "";
                    Point defaultLoc = label4.Location;
                    label4.Location = new Point(defaultLoc.X, defaultLoc.Y + (int)((float)label4.Size.Height / (float)2));
                    label4.Text = str;
                    isShifted = true;
                }
                else
                {
                    label4.Visible = true;
                    label5.Visible = false;
                    label5.Text = "";
                    label4.Text = str;

                }


            }

            Proftim.Enabled = true;
            Proftim.Start();

            console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Profiler, DateTime.Now, str);
        }
        private void Proftim_Tick(object sender, EventArgs e) {

            label4.Text = label5.Text = "";
            label4.Visible = label5.Visible = false;

            Proftim.Stop();
            Proftim.Enabled = false;
            progressBar1.Visible = true;

            if (usb.SetActiveDeviceLoc != 999999)
            {
                SetEnabledButtons(true);
            }

            button9.Enabled = false;
            button10.Enabled = true;
            button11.Enabled = false;
            button12.Enabled = false;

            listBox1.Enabled = true;
            listBox1.SelectedIndex = -1;

        
        
        }


        private void EnaDisableProfiler(bool type)
        {

            if (type == false)
            {
                listBox1.SelectedIndex = -1;
                listBox1.Enabled = false;
                button9.Enabled = false;
                button10.Enabled = false;
                button11.Enabled = false;
                button12.Enabled = false;

            }
            else
            {
                listBox1.SelectedIndex = -1;
                listBox1.Enabled = true;
                button9.Enabled = false;
                button10.Enabled = true;
                button11.Enabled = false;
                button12.Enabled = false;


            }

        }


        private void LoadProgressBar(object sender, ProgressBarInfoArgs e)
        {

            if (e.Res == true)
            {

                if (e.Addr == usb.ControlRegisters.enabledData.Min())
                {
                    
                    EnaDisableProfiler(false);
                    progressBar1.Style = ProgressBarStyle.Blocks;
                    progressBar1.Minimum = 10;
                    progressBar1.Maximum = usb.ControlRegisters.enabledData.Count * 10;
                    progressBar1.Step = 10;

                    
                    progressBar1.Value = 10*(usb.ControlRegisters.enabledData.IndexOf(e.Addr) + 1);
                    
                }

                else if (e.Addr == usb.ControlRegisters.enabledData.Max())
                {
                   
                    progressBar1.Value = 10 * (usb.ControlRegisters.enabledData.IndexOf(e.Addr) + 1);
                    
                    EnaDisableProfiler(true);
                    progressBar1.Minimum = 0;
                    progressBar1.Maximum = 100;
                    progressBar1.Step = 10;
                    progressBar1.Style = ProgressBarStyle.Marquee;
                    progressBar1.MarqueeAnimationSpeed = 500;

                }

                else
                {
                    
                    progressBar1.Value = 10 * (usb.ControlRegisters.enabledData.IndexOf(e.Addr) + 1);

                }
            }
            else
            {

                EnaDisableProfiler(true);
                progressBar1.Minimum = 0;
                progressBar1.Maximum = 100;
                progressBar1.Step = 10;
                progressBar1.Style = ProgressBarStyle.Marquee;
                progressBar1.MarqueeAnimationSpeed = 500;



            }

        }

        private void EnaDisaControlButtons(bool type) {

            if (type == true) { 
            
            button1.Enabled = true;
            button2.Enabled = true;
            button3.Enabled = true;
            button4.Enabled = true;
            button5.Enabled = true;
            button13.Enabled = true;
            button8.Enabled = true;
            button7.Enabled = true;
            
            
            }

            else { 
            
            
            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = false;
            button5.Enabled = false;
            button13.Enabled = false;
            button8.Enabled = false;
            button7.Enabled = true;
            
            
            }
        
        }

        public void DisableControls(bool yes) {

            if (yes == true)
            {

                button10.Enabled = false;
                button8.Enabled = false;
                listBox1.Enabled = false;

            }
            else {

                button10.Enabled = true;
                button8.Enabled = true;
                listBox1.Enabled = true;
            
            }
        
        }

        public Form1()
        {
            InitializeComponent();
            Inicializace();
            DoubleBuffered = true;

        }

        //Ovládání událostí

        public void SendingByteToRAMEventInterface(object sender, SendingByteToRAMEventArgs e)
        {
            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);
        }
        public void SendedByteToRAMEventInterface(object sender, SendedByteToRAMEventArgs e)
        {
            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);

        }
        public void SendingByteToEEPROMEventInterface(object sender, SendingByteToEEPROMEventArgs e)
        {

            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);

        }
        public void SendedByteToEEPROMEventInterface(object sender, SendedByteToEEPROMEventArgs e)
        {

            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);

        }
        public  void RecivingByteFromRAMEventInterface(object sender, RecivingByteFromRAMEventArgs e)
        {

            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);

        }
        public  void RecivedByteFromRAMEventInterface(object sender, RecivedByteFromRAMEventArgs e)
        {

            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);

        }
        public void RecivingByteFromEEPROMEventInterface(object sender, RecivingByteFromEEPROMEventArgs e)
        {

            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);

        }
        public void RecivedByteFromEEPROMEventInterface(object sender, RecivedByteFromEEPROMEventArgs e)
        {

            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);


        }
        public void ProgrammingPAOEventInterface(object sender, ProgrammingPAOEventArgs e)
        {
            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);


        }
        public void ProgrammedPAOEventInterface(object sender, ProgrammedPAOEventArgs e)
        {

         
        }
        public void CircuitEchoingEventInterface(object sender, CircuitEchoingEventArgs e)
        {
            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);
        }
        public void CircuitEchoedEventInterface(object sender, CircuitEchoedEventArgs e)
        {


            WriteStateToConsole(e.Transres.CommandType, e.Transres.EventTime, e.Transres.ad, e.Transres.val, e.Transres.res, e.Transres.TypeOfReport);

        }

        public void ErrorMessageEventInterface(object sender, ErrorMessageEventArgs e)
        {
            if (EnableBlockErrorMessage == true) {

                String BlokZpravy = "Strukturální výpis chyb u jednotlivých částí kódu (pro režim DEBUG):\n\n\n";
                BlokZpravy += "Metody se statusem FALSE:\n\n";
                for (int i = 0; i < e.Em.ErrorList.Count; i++) {
                    if (!e.Em.ErrorList[i].StatusOfFunction)
                    {
                        BlokZpravy += "Pořadí ve výpočetním algoritmu: [" + (e.Em.ErrorList[i].NumberOfFunction + 1) + "] \n";
                    BlokZpravy += "Jméno metody: " + e.Em.ErrorList[i].FunctionName + "\n";
                    BlokZpravy += "Popis chyby: " + e.Em.ErrorList[i].DescribeOfErr + "\n";
                    BlokZpravy += "\n\n";
                    }
                }

                BlokZpravy += "Metody se statusem TRUE:\n\n";
                BlokZpravy += "Pořadí ve výpočetním algoritmu: ["; 

                for (int i = 0; i < e.Em.ErrorList.Count; i++)
                {
                    if ((e.Em.ErrorList[i].StatusOfFunction)&&(i<(e.Em.ErrorList.Count-1)))
                    {

                        BlokZpravy += (e.Em.ErrorList[i].NumberOfFunction + 1) + ",";   
                        
                    }
                    if ((e.Em.ErrorList[i].StatusOfFunction) && (i == (e.Em.ErrorList.Count - 1)))
                    {

                        BlokZpravy += (e.Em.ErrorList[i].NumberOfFunction+1) + "]\n";
                    
                    }
                }

                BlokZpravy += "Jména metod: ";

                for (int i = 0; i < e.Em.ErrorList.Count; i++)
                {
                    if ((e.Em.ErrorList[i].StatusOfFunction) && (i < (e.Em.ErrorList.Count - 1)))
                    {

                        BlokZpravy += e.Em.ErrorList[i].FunctionName + ",";

                    }
                    if ((e.Em.ErrorList[i].StatusOfFunction) && (i == (e.Em.ErrorList.Count - 1)))
                    {

                        BlokZpravy += e.Em.ErrorList[i].FunctionName + "\n";

                    }
                }
            BlokZpravy += "\n\n\nŘešení všech možných chyb: ";
            BlokZpravy += "\n\nZde uvedené chyby odstraníte zpravidla tak, že zkontrolujete připojení programátoru ke sběrnici USB a jeho napájení.";

           MessageBox.Show(BlokZpravy,"Komplexní chybová zpráva",MessageBoxButtons.OK,MessageBoxIcon.Error);
            
            }
        }

        public void SetEnabledButtons(bool enabled) {

            if (enabled == true)
            {

                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                button4.Enabled = true;
                button5.Enabled = true;
                //button13.Enabled = true;

            }
            else {

                    button1.Enabled = false;
                    button2.Enabled = false;
                    button3.Enabled = false;
                    button4.Enabled = false;
                    button5.Enabled = false;
                  //  button13.Enabled = true;

                
            
            }
        
        
        }


        //Naše metody ..... potud jsou reakce na události

        public void AddGainsToSettersVGA() {

            for (int i = 0; i < usb.ControlRegisters.VGAGainS.Count; i++) {

                VGA1GainSetter.Items.Add(usb.ControlRegisters.VGAGainS[i]);
                VGA2GainSetter.Items.Add(usb.ControlRegisters.VGAGainS[i]);
            }

            VGA1GainSetter.SelectedIndex = VGA2GainSetter.SelectedIndex = 0; 
        
        }

        public void WriteStateToConsole(int CommandTypeX, DateTime EventTimeX, int adX, int valX, bool resX,int TypeOfRep)
        {
           
            if(TypeOfRep == 1){
            //int CommandTypeX, DateTime EventTimeX
            
            if(CommandTypeX == (int)UsbCom.CommandTypes.CircuitEcho){

                console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Info, EventTimeX, "Provádím test odezvy programátora.");
   
            }

            if (CommandTypeX == (int)UsbCom.CommandTypes.ProgrammPAOFromRAM)
            {

                console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Info, EventTimeX, "Programování obvodu bylo zahájeno.");

            }

        }
            if(TypeOfRep == 2){
            //int CommandTypeX, DateTime EventTimeX, int adX

                if (CommandTypeX == (int)UsbCom.CommandTypes.ReadByteFromEEPROM)
                {


                    console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Info, EventTimeX, "Získávám byte adresy " + adX.ToString() + " z EEPROM programátora.");
                   
                }

                if (CommandTypeX == (int)UsbCom.CommandTypes.ReadByteFromRAM)
                {


                    console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Info, EventTimeX, "Získávám byte adresy " + adX.ToString() + " z RAM programátora.");
                    
                }
            
            }

            if(TypeOfRep == 3){
            //int CommandTypeX, DateTime EventTimeX, int adX, int valX

                if (CommandTypeX == (int)UsbCom.CommandTypes.WriteByteToEEPROM)
                {


                    console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Info, EventTimeX, "Odesílám byte adresy " + adX.ToString() + " s hodnotou " + valX.ToString() + " (" + usb.ControlRegisters.ConvertByteToStrAndCrop(valX,7)  + ")" + " do EEPROM programátora.");
                   
                }

                if (CommandTypeX == (int)UsbCom.CommandTypes.WriteByteToRAM)
                {


                    console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Info, EventTimeX, "Odesílám byte adresy " + adX.ToString() + " s hodnotou " + valX.ToString() + " (" + usb.ControlRegisters.ConvertByteToStrAndCrop(valX, 8) + ")" + " do RAM programátora.");
                    
                }
            
            }

            if(TypeOfRep == 4){
            //int CommandTypeX, DateTime EventTimeX, int adX, int valX, bool resX

                if (CommandTypeX == (int)UsbCom.CommandTypes.CircuitEcho)
                {

                    

                  
                    if (resX == false)
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Error, EventTimeX, "Test odezvy programátora proveden jako chybný.");
                    }
                    else {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Success, EventTimeX, "Test odezvy programátora proveden jako úspěšný.");
                    }

                   

                    }

                if (CommandTypeX == (int)UsbCom.CommandTypes.ProgrammPAOFromRAM)
                {




                    if (resX == false)
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Error, EventTimeX, "Při programování se vyskytla chyba.");
                    }
                    else
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Success, EventTimeX, "Programování obvodu proběhlo úspěšně.");
                    }



                }

                if (CommandTypeX == (int)UsbCom.CommandTypes.WriteByteToEEPROM)
                {

                    
                    if (resX == false)
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Error, EventTimeX, "Byte adresy " + adX.ToString() + " a hodnoty " + valX.ToString() + " (" + usb.ControlRegisters.ConvertByteToStrAndCrop(valX, 8) + ")" + " se nepodařilo odeslat do EEPROM programátora.");
                        
                    }
                    else
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Success, EventTimeX, "Byte adresy " + adX.ToString() + " a hodnoty " + valX.ToString() + " (" + usb.ControlRegisters.ConvertByteToStrAndCrop(valX, 8) + ")" + " byl úspěšně odeslán do EEPROM programátora.");
                        
                    }

                    
                }

                if (CommandTypeX == (int)UsbCom.CommandTypes.WriteByteToRAM)
                {

                    
                    if (resX == false)
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Error, EventTimeX, "Byte adresy " + adX.ToString() + " a hodnoty " + valX.ToString() + " (" + usb.ControlRegisters.ConvertByteToStrAndCrop(valX, 8) + ")" + " se nepodařilo odeslat do RAM programátora.");
                        
                    }
                    else
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Success, EventTimeX, "Byte adresy " + adX.ToString() + " a hodnoty " + valX.ToString() + " (" + usb.ControlRegisters.ConvertByteToStrAndCrop(valX, 8) + ")" + " byl úspěšně odeslán do RAM programátora.");
                        
                    }

                   
                }

                if (CommandTypeX == (int)UsbCom.CommandTypes.ReadByteFromEEPROM)
                {

                    
                    if (resX == false)
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Error, EventTimeX, "Byte adresy " + adX.ToString() + " se nepodařilo získat z EEPROM programátora.");
                        
                    }
                    else
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Success, EventTimeX, "Byte adresy " + adX.ToString() + " a hodnoty " + valX.ToString() + " (" + usb.ControlRegisters.ConvertByteToStrAndCrop(valX, 8) + ")" + " byl úspěšně získán z EEPROM programátora.");
                        
                    }
                   
                }

                if (CommandTypeX == (int)UsbCom.CommandTypes.ReadByteFromRAM)
                {

                    
                    if (resX == false)
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Error, EventTimeX, "Byte adresy " + adX.ToString() + " se nepodařilo získat z RAM programátora.");
                        
                    }
                    else
                    {
                        console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Success, EventTimeX, "Byte adresy " + adX.ToString() + " a hodnoty " + valX.ToString() + " (" + usb.ControlRegisters.ConvertByteToStrAndCrop(valX, 8) + ")" + " byl úspěšně získán z RAM programátora.");
                        
                    }
                   
                }

            
            }

        }


        private void VGA1GainSetter_SelectedIndexChanged(object sender, EventArgs e)
        {
            usb.ControlRegisters.VGA_1GAINCode = (byte)VGA1GainSetter.SelectedIndex;
        }

        private void VGA2GainSetter_SelectedIndexChanged(object sender, EventArgs e)
        {
            usb.ControlRegisters.VGA_2GAINCode = (byte)VGA2GainSetter.SelectedIndex;
        }

        private void button7_Click(object sender, EventArgs e)
        {
          
            
        }

        public void ReloadThumbinals() {

            int list1topitem =0;
            int list2topitem = 0;

            try
            {
                list1topitem = listView1.TopItem.Index;
                list2topitem = listView2.TopItem.Index;

            }
            catch(Exception e) 
            { 
            
            
            }

            listView1.BeginUpdate();
            listView2.BeginUpdate();

            listView1.Items.Clear();
            listView2.Items.Clear();

            List<ListViewItem> itemsToViewBites = new List<ListViewItem>(45);
            List<ListViewItem> itemsToViewBytes = new List<ListViewItem>(20);

           
            for (int i = 0; i < usb.ControlRegisters.BitValNames.Length; i++) {

                ListViewItem l = new ListViewItem(usb.ControlRegisters.BitValNames[i]);
                l.SubItems.Add((usb.ControlRegisters.BitValuesByNames[i] == true) ? "1" : "0");

                itemsToViewBites.Add(l); 
            
            }

            for (int i = 0; i < usb.ControlRegisters.BitValNames.Length; i++) {

               if(listView1.Items.Contains(itemsToViewBites[i])){

                   listView1.Items[i] = itemsToViewBites[i];
               
               }
               else{

                   listView1.Items.Add(itemsToViewBites[i]);
               
               }



            }


            for (int i = 0; i < usb.ControlRegisters.ByteValNames.Length; i++)
            {

                ListViewItem l = new ListViewItem(usb.ControlRegisters.ByteValNames[i]);
                l.SubItems.Add(usb.ControlRegisters.ByteValuesByNames[i]);

                itemsToViewBytes.Add(l);

            }

            for (int i = 0; i < usb.ControlRegisters.ByteValNames.Length; i++)
            {
               if(listView2.Items.Contains(itemsToViewBytes[i])){

                   listView2.Items[i] = itemsToViewBytes[i];
               
               }
               else{  
                    listView2.Items.Add(itemsToViewBytes[i]);
               }
               
            
            }

            listView1.EndUpdate();
            listView2.EndUpdate();

            try
            {
                if ((list1topitem != 0) && (list1topitem != 1))
                {
                    listView1.TopItem = listView1.Items[list1topitem+1];
                    
                }
                else {

                    listView1.TopItem = listView1.Items[list1topitem];
                    
                
                }

                if ((list2topitem != 0) && (list2topitem != 1))
                {
                    listView2.TopItem = listView2.Items[list2topitem+1];
                }
                else
                {

                    listView2.TopItem = listView2.Items[list2topitem];

                }
            }
            catch(Exception e){
            

            
            }
      
    }



    public void SchemePaint() {

    Graphics q = RenderWin.CreateGraphics();

    q.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
    q.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
    q.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.AssumeLinear;
    q.SmoothingMode = SmoothingMode.HighQuality;
    q.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

    Rectangle destRect = new Rectangle(0, 0, RenderWin.Width, RenderWin.Height);

 
    Rectangle srcRect = new Rectangle(rohx, rohy, RenderWin.Width, RenderWin.Height);
    GraphicsUnit units = GraphicsUnit.Pixel;

    q.Clip = new Region(destRect);

    if (Err == false)
    {
     RenderWin.Update();
     q.DrawImage(Scheme, destRect, srcRect, units);

    }

 }

        private void ReloadListOfDevices(object sender, FindedDevices e) {

            bool deviceinsel = false;
            
            if ((e.operationSuccess == true)&&(e.List.Count != 0))
            {
                int list3topindex = 0;

                try
                {

                    list3topindex = listView3.TopItem.Index;

                }
                catch(Exception a) { 
                
                
                
                }

                listView3.BeginUpdate();

                listView3.Items.Clear();

                List<ListViewItem> devices = new List<ListViewItem>(3);

                for (int i = 0; i < e.List.Count; i++)
                {

                    ListViewItem l = new ListViewItem(e.List[i].index.ToString());
                    l.SubItems.Add(e.List[i].SerialNumber.ToString());
                    l.SubItems.Add(e.List[i].Description.ToString());
                    l.SubItems.Add(e.List[i].LocID.ToString());
                    l.SubItems.Add(e.List[i].ID.ToString());


                    devices.Add(l);


                }

                for (int i = 0; i < devices.Count; i++)
                {

                    if (listView3.Items.Contains(devices[i]))
                    {

                        listView3.Items[i] = devices[i];

                    }
                    else
                    {

                        listView3.Items.Add(devices[i]);

                    }

                }

                if (usb.SetActiveDeviceLoc != 999999)
                {

                    for (int i = 0; i < listView3.Items.Count; i++) {

                        if (listView3.Items[i].SubItems[3].Text == usb.SetActiveDeviceLoc.ToString()) {

                            listView3.Items[i].Checked = true;
                            deviceinsel = true;
                            break;
                            
                        }
                    
                    }
                    if (deviceinsel == false) {

                        usb.SetActiveDeviceLoc = 999999;
                        SetEnabledButtons(false);
                    }
                
                }

                listView3.EndUpdate();

                try
                {

                    listView3.TopItem = listView3.Items[list3topindex];

                }
                catch (Exception u) { 
                
                
                
                }

                

                console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Success, DateTime.Now, "Seznam připojených zařízení byl úspěšně obnoven.");

            }
            if((e.operationSuccess == true)&&(e.List.Count == 0)) {

                listView3.BeginUpdate();

                listView3.Items.Clear();

                listView3.EndUpdate();

                usb.SetActiveDeviceLoc = 999999;

                SetEnabledButtons(false);



                console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Success, DateTime.Now, "Seznam připojených zařízení byl úspěšně obnoven.");
            }

           
            
        
            if((e.errDeviceCount == true)||(e.errDeviceGetDesc == true)){

                listView3.BeginUpdate();

                listView3.Items.Clear();

                listView3.EndUpdate();

                usb.SetActiveDeviceLoc = 999999;
                SetEnabledButtons(false);

                

                console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Error, DateTime.Now, "Seznam připojených zařízení nebyl úspěšně obnoven (Metoda: " + e.functionOfProblem + ", Chyba: " + e.reasonOfErr + ").");
            
            }
            ad = e.List;
        }

        private void EmptyDeviceMessage() {

            console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Error, DateTime.Now, "Nebylo vybráno žádné zařízení pro komunikaci.");

            SetEnabledButtons(false);
            usb.FindFTDIDevice();

        
        }


        private void TopShift_MouseDown(object sender, MouseEventArgs e)
        {
            shifttop = true;

            ComponentSettingsRendering(true);
            
        }

        private void TopShift_MouseUp(object sender, MouseEventArgs e)
        {
            shifttop = false;
            ComponentSettingsRendering(false);

        }

        private void BottomShift_MouseDown(object sender, MouseEventArgs e)
        {
            shiftdown = true;

            ComponentSettingsRendering(true);
      
        }

        private void BottomShift_MouseUp(object sender, MouseEventArgs e)
        {
            shiftdown = false;
            ComponentSettingsRendering(false);
        }

        private void RightShift_MouseDown(object sender, MouseEventArgs e)
        {
            shiftright = true;
            ComponentSettingsRendering(true);
       
        }

        private void RightShift_MouseUp(object sender, MouseEventArgs e)
        {
            shiftright = false;
            ComponentSettingsRendering(false);
        }

        private void LeftShift_MouseDown(object sender, MouseEventArgs e)
        {
            shiftleft = true;

            ComponentSettingsRendering(true);

        }

        private void LeftShift_MouseUp(object sender, MouseEventArgs e)
        {
            shiftleft = false;
            ComponentSettingsRendering(false);
   
        }

        private void CenterPosWin_Click(object sender, EventArgs e)
        {
            rohx = Scheme.Width - RenderWin.Width - (int)((float)RenderWin.Width / 2.0);
            rohy = Scheme.Height - RenderWin.Height - (int)((float)RenderWin.Height / 2.0);
            ComponentSettingsRendering(true);
            ComponentSettingsRendering(false);
        }



        public void ComponentSettingsRendering(bool compShift) {

            if (compShift == false)
            {
                //Komponenta1 - VGA1

                if (((ControlSettersLoc[0].X > rohx) && (ControlSettersLoc[0].X < (RenderWin.Width+rohx))) && ((ControlSettersLoc[0].Y > rohy) && (ControlSettersLoc[0].Y < (RenderWin.Height+rohy))))
                {
                    VGA1_Setter_group_ren.Visible = true;
                    VGA1_Setter_group_ren.Location = new Point(ControlSettersLoc[0].X - rohx, ControlSettersLoc[0].Y - rohy);

                }
                else
                {

                    VGA1_Setter_group_ren.Visible = false;

                }

                //Komponenta2 - VGA2


                if (((ControlSettersLoc[1].X > rohx) && (ControlSettersLoc[1].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[1].Y > rohy) && (ControlSettersLoc[1].Y < (RenderWin.Height + rohy))))
                {
                    VGA2_Setter_group_ren.Visible = true;
                    VGA2_Setter_group_ren.Location = new Point(ControlSettersLoc[1].X - rohx, ControlSettersLoc[1].Y - rohy);

                }
                else
                {

                    VGA2_Setter_group_ren.Visible = false;

                }

                //MUX1

                if (((ControlSettersLoc[2].X > rohx) && (ControlSettersLoc[2].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[2].Y > rohy) && (ControlSettersLoc[2].Y < (RenderWin.Height + rohy))))
                {
                    mx1.Visible = true;
                    mx1.Location = new Point(ControlSettersLoc[2].X - rohx, ControlSettersLoc[2].Y - rohy);

                }
                else
                {

                    mx1.Visible = false;

                }

                //MUX2
                if (((ControlSettersLoc[3].X > rohx) && (ControlSettersLoc[3].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[3].Y > rohy) && (ControlSettersLoc[3].Y < (RenderWin.Height + rohy))))
                {
                    mx2.Visible = true;
                    mx2.Location = new Point(ControlSettersLoc[3].X - rohx, ControlSettersLoc[3].Y - rohy);

                }
                else
                {

                    mx2.Visible = false;

                }
                //MUX3

                if (((ControlSettersLoc[4].X > rohx) && (ControlSettersLoc[4].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[4].Y > rohy) && (ControlSettersLoc[4].Y < (RenderWin.Height + rohy))))
                {
                    mx3.Visible = true;
                    mx3.Location = new Point(ControlSettersLoc[4].X - rohx, ControlSettersLoc[4].Y - rohy);

                }
                else
                {

                    mx3.Visible = false;

                }

                //MUX4


                if (((ControlSettersLoc[5].X > rohx) && (ControlSettersLoc[5].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[5].Y > rohy) && (ControlSettersLoc[5].Y < (RenderWin.Height + rohy))))
                {
                    mx4.Visible = true;
                    mx4.Location = new Point(ControlSettersLoc[5].X - rohx, ControlSettersLoc[5].Y - rohy);

                }
                else
                {

                    mx4.Visible = false;

                }
                //MUX5


                if (((ControlSettersLoc[6].X > rohx) && (ControlSettersLoc[6].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[6].Y > rohy) && (ControlSettersLoc[6].Y < (RenderWin.Height + rohy))))
                {
                    mx5.Visible = true;
                    mx5.Location = new Point(ControlSettersLoc[6].X - rohx, ControlSettersLoc[6].Y - rohy);

                }
                else
                {

                    mx5.Visible = false;

                }

                //Out1


                if (((ControlSettersLoc[7].X > rohx) && (ControlSettersLoc[7].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[7].Y > rohy) && (ControlSettersLoc[7].Y < (RenderWin.Height + rohy))))
                {
                    Out1.Visible = true;
                    Out1.Location = new Point(ControlSettersLoc[7].X - rohx, ControlSettersLoc[7].Y - rohy);

                }
                else
                {

                    Out1.Visible = false;

                }
                //Out2

                if (((ControlSettersLoc[8].X > rohx) && (ControlSettersLoc[8].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[8].Y > rohy) && (ControlSettersLoc[8].Y < (RenderWin.Height + rohy))))
                {
                    Out2.Visible = true;
                    Out2.Location = new Point(ControlSettersLoc[8].X - rohx, ControlSettersLoc[8].Y - rohy);

                }
                else
                {

                    Out2.Visible = false;

                }
                //Out3

                if (((ControlSettersLoc[9].X > rohx) && (ControlSettersLoc[9].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[9].Y > rohy) && (ControlSettersLoc[9].Y < (RenderWin.Height + rohy))))
                {
                    Out3.Visible = true;
                    Out3.Location = new Point(ControlSettersLoc[9].X - rohx, ControlSettersLoc[9].Y - rohy);

                }
                else
                {

                    Out3.Visible = false;

                }

                //FDCA gain +5dB
                if (((ControlSettersLoc[10].X > rohx) && (ControlSettersLoc[10].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[10].Y > rohy) && (ControlSettersLoc[10].Y < (RenderWin.Height + rohy))))
                {
                    fdcaG.Visible = true;
                    fdcaG.Location = new Point(ControlSettersLoc[10].X - rohx, ControlSettersLoc[10].Y - rohy);

                }
                else
                {

                    fdcaG.Visible = false;

                }

                //Sellinver

                if (((ControlSettersLoc[11].X > rohx) && (ControlSettersLoc[11].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[11].Y > rohy) && (ControlSettersLoc[11].Y < (RenderWin.Height + rohy))))
                {
                    SLV_group.Visible = true;
                    SLV_group.Location = new Point(ControlSettersLoc[11].X - rohx, ControlSettersLoc[11].Y - rohy);

                }
                else
                {

                    SLV_group.Visible = false;

                }

                //ServoloopStage1

                if (((ControlSettersLoc[12].X > rohx) && (ControlSettersLoc[12].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[12].Y > rohy) && (ControlSettersLoc[12].Y < (RenderWin.Height + rohy))))
                {
                    servoloops1_group.Visible = true;
                    servoloops1_group.Location = new Point(ControlSettersLoc[12].X - rohx, ControlSettersLoc[12].Y - rohy);

                }
                else
                {

                    servoloops1_group.Visible = false;

                }

                //ServoloopStage2

                if (((ControlSettersLoc[13].X > rohx) && (ControlSettersLoc[13].X < (RenderWin.Width + rohx))) && ((ControlSettersLoc[13].Y > rohy) && (ControlSettersLoc[13].Y < (RenderWin.Height + rohy))))
                {
                    servoloops2_group.Visible = true;
                    servoloops2_group.Location = new Point(ControlSettersLoc[13].X - rohx, ControlSettersLoc[13].Y - rohy);

                }
                else
                {

                    servoloops2_group.Visible = false;

                }
            }
            else {

               

                VGA1_Setter_group_ren.Visible = false;
                VGA2_Setter_group_ren.Visible = false;
                mx1.Visible = false;
                mx2.Visible = false;
                mx3.Visible = false;
                mx4.Visible = false;
                mx5.Visible = false;
                Out1.Visible = false;
                Out2.Visible = false;
                Out3.Visible = false;
                fdcaG.Visible = false;
                SLV_group.Visible = false;
                servoloops1_group.Visible = false;
                servoloops2_group.Visible = false;

            
            }

            SchemePaint();
        }

        private void windowSchemeShifter_Tick(object sender, EventArgs e)
        {
            if (shiftdown == true) {

                waspainted = true;
                bool shiftperf = false;
                
                if (rohy >= 0)
                {
                    if ((rohy >= 2 *shiftconst)&&(shiftperf == false)) { 
                    rohy -= shiftconst;
                    shiftperf = true;
                    SchemePaint();
                    }
                    if ((rohy >= shiftconst) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohy -= trackBar1.Minimum;
                        SchemePaint();
                    }
                    if ((rohy >= 0) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohy -= 1;
                        SchemePaint();
                    
                    }
                }

                else {
           
                    ComponentSettingsRendering(false);
                
                }
            }

            if (shifttop == true)
            {
                waspainted = true;
                bool shiftperf = false;

                if ((rohy + RenderWin.Height) <= Scheme.Height) {


                    if (((rohy + RenderWin.Height + 2*shiftconst) <= Scheme.Height) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohy += shiftconst;
                        SchemePaint();

                    }


                    if (((rohy + RenderWin.Height + shiftconst) <= Scheme.Height) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohy += trackBar1.Minimum;
                        SchemePaint();

                    }

                    if (((rohy + RenderWin.Height) <= Scheme.Height) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohy += 1;
                        SchemePaint();

                    }
                    
                }
                else
                {

                    ComponentSettingsRendering(false);
                  
                }
            }
                                   
            if (shiftleft == true)
            {
                waspainted = true;
                bool shiftperf = false;

                if ((rohx + RenderWin.Width) <= Scheme.Width)
                {


                    if (((rohx + RenderWin.Width + 2 * shiftconst) <= Scheme.Width) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohx += shiftconst;
                        SchemePaint();

                    }

                    if (((rohx + RenderWin.Width + shiftconst) <= Scheme.Width) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohx += trackBar1.Minimum;
                        SchemePaint();

                    }

                    if (((rohx + RenderWin.Width) <= Scheme.Width) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohx += 1;
                        SchemePaint();

                    }


                }
                else
                {

                    ComponentSettingsRendering(false);
                 
                }

            }
                                     
            if (shiftright == true)
            {
                waspainted = true;
                bool shiftperf = false;

                if (rohx >= 0)
                {
                    if ((rohx >= 2 * shiftconst) && (shiftperf == false))
                    {
                        rohx -= shiftconst;
                        shiftperf = true;
                        SchemePaint();
                    }
                    if ((rohx >= shiftconst) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohx -= trackBar1.Minimum;
                        SchemePaint();
                    }
                    if ((rohx >= 0) && (shiftperf == false))
                    {
                        shiftperf = true;
                        rohx -= 1;
                        SchemePaint();

                    }
                }
                else
                {

                    ComponentSettingsRendering(false);
               
                }


            }

            if((shifttop == false)&&(shiftdown == false)&&(shiftleft == false)&&(shiftright == false)&&(waspainted == true)&&(isMaximalized == true)){

                EmergencyCheckerStarter(timerconst);
                waspainted = false;
            
            }

            

        }

        bool progress_ = false;

        private void trackBar1_ValueChanged(object sender, EventArgs e)
        {
            shiftconst = trackBar1.Value;
            SaveConfig(shiftconst, timerconst, KeyDrivenEvent.Interval);
        }

        private void trackBar2_ValueChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked == false)
            {
                timerconst = trackBar2.Value;
                windowSchemeShifter.Interval = timerconst;
            }
            else {

                KeyDrivenEvent.Interval = trackBar2.Value;
            }

            SaveConfig(shiftconst, timerconst, KeyDrivenEvent.Interval);
        }
        
        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked == true)
            {
                
                trackBar2.Minimum = 1;
                trackBar2.Maximum = 1500;
                if (trackBar2.Value == 0)
                {
                    trackBar2.Value = trackBar2.Minimum;
                }
                else
                {
                        trackBar2.Value = KeyDrivenEvent.Interval;
  
                }

            }
            else {

                trackBar2.Minimum = 1;
                trackBar2.Maximum = 1000;
                if (trackBar2.Value == 0)
                {
                    trackBar2.Value = trackBar2.Minimum;
                }
                else {
                    
                   trackBar2.Value = timerconst;
                    
                }
            
            }
        }


        private void RenderWin_MouseMove(object sender, MouseEventArgs e)
        {
            label3.Text = "[" + (e.X + rohx).ToString() + "," + (e.Y + rohy).ToString() + "]";
        }


        private void mx1a_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked))
            {

                FailMuxSettings = false;
                mx1L.Text = "Platná kombinace";
                mx1L.ForeColor = Color.Green;
            }
            else
            {

                mx1L.Text = "Neplatná kombinace";
                mx1L.ForeColor = Color.Red;
                FailMuxSettings = true;
 
            }

        }

        private void mx1b_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked))
            {

                FailMuxSettings = false;
                mx1L.Text = "Platná kombinace";
                mx1L.ForeColor = Color.Green;
            }
            else
            {

                mx1L.Text = "Neplatná kombinace";
                mx1L.ForeColor = Color.Red;
                FailMuxSettings = true;

            }
        }

        private void mx1c_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked))
            {

                FailMuxSettings = false;
                mx1L.Text = "Platná kombinace";
                mx1L.ForeColor = Color.Green;
            }
            else
            {

                mx1L.Text = "Neplatná kombinace";
                mx1L.ForeColor = Color.Red;
                FailMuxSettings = true;

            }
        }

        private void mx1d_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked))
            {

                FailMuxSettings = false;
                mx1L.Text = "Platná kombinace";
                mx1L.ForeColor = Color.Green;
            }
            else
            {

                mx1L.Text = "Neplatná kombinace";
                mx1L.ForeColor = Color.Red;
                FailMuxSettings = true;

            }
        }

        private void mx1g_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("1", mx1a.Checked, mx1b.Checked, mx1c.Checked, mx1d.Checked, mx1g.Checked))
            {

                FailMuxSettings = false;
                mx1L.Text = "Platná kombinace";
                mx1L.ForeColor = Color.Green;
            }
            else
            {

                mx1L.Text = "Neplatná kombinace";
                mx1L.ForeColor = Color.Red;
                FailMuxSettings = true;

            }
        }

        private void mx2a_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked);


            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked))
            {


                mx2L.Text = "Platná kombinace";
                FailMuxSettings = false;
                mx2L.ForeColor = Color.Green;
            }
            else
            {

                mx2L.Text = "Neplatná kombinace";
                mx2L.ForeColor = Color.Red;

                FailMuxSettings = true;
            }
        }

        private void mx2b_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked))
            {

                FailMuxSettings = false;
                mx2L.Text = "Platná kombinace";
                mx2L.ForeColor = Color.Green;
            }
            else
            {

                mx2L.Text = "Neplatná kombinace";
                mx2L.ForeColor = Color.Red;

                FailMuxSettings = true;

            }
        }

        private void mx2c_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked))
            {

                FailMuxSettings = false;
                mx2L.Text = "Platná kombinace";
                mx2L.ForeColor = Color.Green;
            }
            else
            {

                mx2L.Text = "Neplatná kombinace";
                mx2L.ForeColor = Color.Red;

                FailMuxSettings = true;

            }
        }

        private void mx2d_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked))
            {

                FailMuxSettings = false;
                mx2L.Text = "Platná kombinace";
                mx2L.ForeColor = Color.Green;
            }
            else
            {

                mx2L.Text = "Neplatná kombinace";
                mx2L.ForeColor = Color.Red;

                FailMuxSettings = true;


            }
        }

        private void mx2g_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("2", mx2a.Checked, mx2b.Checked, mx2c.Checked, mx2d.Checked, mx2g.Checked))
            {

                FailMuxSettings = false;
                mx2L.Text = "Platná kombinace";
                mx2L.ForeColor = Color.Green;
            }
            else
            {

                mx2L.Text = "Neplatná kombinace";
                mx2L.ForeColor = Color.Red;

                FailMuxSettings = true;
            }
        }

        private void mx3a_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked))
            {

                FailMuxSettings = false;
                mx3L.Text = "Platná kombinace";
                mx3L.ForeColor = Color.Green;
            }
            else
            {

                mx3L.Text = "Neplatná kombinace";
                mx3L.ForeColor = Color.Red;

                FailMuxSettings = true;
            }

        }

        private void mx3b_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked))
            {

                FailMuxSettings = false;
                mx3L.Text = "Platná kombinace";
                mx3L.ForeColor = Color.Green;
            }
            else
            {

                mx3L.Text = "Neplatná kombinace";
                mx3L.ForeColor = Color.Red;

                FailMuxSettings = true;
            }
        }

        private void mx3c_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked))
            {

                FailMuxSettings = false;
                mx3L.Text = "Platná kombinace";
                mx3L.ForeColor = Color.Green;
            }
            else
            {

                mx3L.Text = "Neplatná kombinace";
                mx3L.ForeColor = Color.Red;

                FailMuxSettings = true;
            }
        }

        private void mx3d_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked))
            {

                FailMuxSettings = false;
                mx3L.Text = "Platná kombinace";
                mx3L.ForeColor = Color.Green;
            }
            else
            {

                mx3L.Text = "Neplatná kombinace";
                mx3L.ForeColor = Color.Red;

                FailMuxSettings = true;
            }
        }

        private void mx3g_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("3", mx3a.Checked, mx3b.Checked, mx3c.Checked, mx3d.Checked, mx3g.Checked))
            {

                FailMuxSettings = false;
                mx3L.Text = "Platná kombinace";
                mx3L.ForeColor = Color.Green;
            }
            else
            {

                mx3L.Text = "Neplatná kombinace";
                mx3L.ForeColor = Color.Red;

                FailMuxSettings = true;

            }
        }

        private void mx4a_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked))
            {

                FailMuxSettings = false;
                mx4L.Text = "Platná kombinace";
                mx4L.ForeColor = Color.Green;
            }
            else
            {

                mx4L.Text = "Neplatná kombinace";
                mx4L.ForeColor = Color.Red;
                FailMuxSettings = true;


            }
        }

        private void mx4b_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked))
            {

                FailMuxSettings = false;
                mx4L.Text = "Platná kombinace";
                mx4L.ForeColor = Color.Green;
            }
            else
            {

                mx4L.Text = "Neplatná kombinace";
                mx4L.ForeColor = Color.Red;

                FailMuxSettings = true;


            }
        }

        private void mx4c_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked))
            {

                FailMuxSettings = false;
                mx4L.Text = "Platná kombinace";
                mx4L.ForeColor = Color.Green;
            }
            else
            {

                mx4L.Text = "Neplatná kombinace";
                mx4L.ForeColor = Color.Red;

                FailMuxSettings = true;
  

            }
        }

        private void mx4d_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked))
            {

                FailMuxSettings = false;
                mx4L.Text = "Platná kombinace";
                mx4L.ForeColor = Color.Green;
            }
            else
            {

                mx4L.Text = "Neplatná kombinace";
                mx4L.ForeColor = Color.Red;

                FailMuxSettings = true;


            }
        }

        private void mx4g_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("4", mx4a.Checked, mx4b.Checked, mx4c.Checked, mx4d.Checked, mx4g.Checked))
            {

                FailMuxSettings = false;
                mx4L.Text = "Platná kombinace";
                mx4L.ForeColor = Color.Green;
            }
            else
            {

                mx4L.Text = "Neplatná kombinace";
                mx4L.ForeColor = Color.Red;

                FailMuxSettings = true;

            }
        }

        private void mx5a_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked))
            {

                FailMuxSettings = false;
                mx5L.Text = "Platná kombinace";
                mx5L.ForeColor = Color.Green;
            }
            else
            {

                mx5L.Text = "Neplatná kombinace";
                mx5L.ForeColor = Color.Red;
                FailMuxSettings = true;

            }
        }

        private void mx5b_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked))
            {

                FailMuxSettings = false;
                mx5L.Text = "Platná kombinace";
                mx5L.ForeColor = Color.Green;
            }
            else
            {

                mx5L.Text = "Neplatná kombinace";
                mx5L.ForeColor = Color.Red;
                FailMuxSettings = true;

            }
        }

        private void mx5c_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked))
            {

                FailMuxSettings = false;
                mx5L.Text = "Platná kombinace";
                mx5L.ForeColor = Color.Green;
            }
            else
            {

                mx5L.Text = "Neplatná kombinace";
                mx5L.ForeColor = Color.Red;
                FailMuxSettings = true;

            }
        }

        private void mx5d_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked))
            {

                FailMuxSettings = false;
                mx5L.Text = "Platná kombinace";
                mx5L.ForeColor = Color.Green;
            }
            else
            {

                mx5L.Text = "Neplatná kombinace";
                mx5L.ForeColor = Color.Red;
                FailMuxSettings = true;

            }
        }

        private void mx5g_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionMux("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked);

            if (usb.ControlRegisters.MuxSwCombinationToSettingByte("5", mx5a.Checked, mx5b.Checked, mx5c.Checked, mx5d.Checked, mx5g.Checked))
            {

                FailMuxSettings = false;
                mx5L.Text = "Platná kombinace";
                mx5L.ForeColor = Color.Green;
            }
            else
            {
                FailMuxSettings = true;
                mx5L.Text = "Neplatná kombinace";
                mx5L.ForeColor = Color.Red;

            }
        }

        private void Out1a_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionInOut("1", Out1a.Checked, Out1s.Checked);
            usb.ControlRegisters.SWgmTIA1_A = Out1a.Checked;
        }

        private void Out1s_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionInOut("1", Out1a.Checked, Out1s.Checked);
            usb.ControlRegisters.SWgmTIA1_S = Out1s.Checked;
        }

        private void Out2a_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionInOut("2", Out2a.Checked, Out2s.Checked);
            usb.ControlRegisters.SWLNA_VGA_A = Out2a.Checked;
        }

        private void Out2s_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionInOut("2", Out2a.Checked, Out2s.Checked);
            usb.ControlRegisters.SWLNA_VGA_S = Out2s.Checked;
        }

        private void Out3a_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionInOut("3", Out3a.Checked, Out3s.Checked);
            usb.ControlRegisters.SWVGAA2_A = Out3a.Checked;
        }

        private void Out3s_CheckedChanged(object sender, EventArgs e)
        {
            DrawSwitchPositionInOut("3", Out3a.Checked, Out3s.Checked);
            usb.ControlRegisters.SWVGAA2_S = Out3s.Checked;
        }

        private void FDCAgain1_CheckedChanged(object sender, EventArgs e)
        {
            usb.ControlRegisters.SDBUFp5dB = FDCAgain1.Checked;
        }

        private void sel_lin_ver_sw_CheckedChanged(object sender, EventArgs e)
        {
            usb.ControlRegisters.SEL_LIN_ver = sel_lin_ver_sw.Checked;
            DrawSLVState(sel_lin_ver_sw.Checked);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            EnaDisaControlButtons(false);
            if (usb.CircuitEcho())
            {

                mbm.MakeMessage("Komunikace s programátorem otestována jako úspěšná.", "Komunikace s programátorem", SystemIcons.Asterisk);
                EnaDisaControlButtons(true);
            }
            else {


                mbm.MakeMessage("Komunikace s programátorem otestována jako chybná.", "Komunikace s programátorem", SystemIcons.Error);
                EnaDisaControlButtons(true);
                usb.FindFTDIDevice();
            
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            EnaDisaControlButtons(false);
            if (usb.CircuitEcho())
            {
                if (FailMuxSettings == false)
                {
                    if (usb.SendAllValuesToRAM())
                    {

                        mbm.MakeMessage("Nastavené hodnoty úspěšně odeslány do RAM programátora.", "Odesílání hodnot do RAM", SystemIcons.Asterisk);
             

                        if (usb.ProgrammPAOFromRAM())
                        {

                            mbm.MakeMessage("Obvod byl z hodnot v RAM programátora úspěšně naprogramován.", "Programování PAO podle hodnot z RAM", SystemIcons.Asterisk);
                            EnaDisaControlButtons(true);

                        }
                        else
                        {

                            mbm.MakeMessage("V průběhu programování se vyskytla chyba.", "Programování PAO podle hodnot z RAM", SystemIcons.Error);
                            EnaDisaControlButtons(true);
                            usb.FindFTDIDevice();
                        }


                    }
                    else
                    {

                        mbm.MakeMessage("V průběhu odesílání dat do programátora se vyskytla chyba.", "Odesílání hodnot do RAM",  SystemIcons.Error);
                        EnaDisaControlButtons(true);
                        usb.FindFTDIDevice();
                    }

                }
                else {

                    mbm.MakeMessage("Neplatná kombinace na signálovém přepínači.", "Neplatná kombinace", SystemIcons.Exclamation);
                    EnaDisaControlButtons(true);
                }
            }
            else
            {


                mbm.MakeMessage("Komunikace s programátorem otestována jako chybná.", "Komunikace s programátorem", SystemIcons.Error);
                EnaDisaControlButtons(true);
                usb.FindFTDIDevice();

            }
         
        }

        private void button3_Click(object sender, EventArgs e)
        {
            EnaDisaControlButtons(false);
            if (usb.CircuitEcho())
            {
                 if (FailMuxSettings == false)
                {
                if (usb.SendAllValuesToEEPROM())
                {

                    mbm.MakeMessage("Nastavené hodnoty úspěšně odeslány do EEPROM programátora.", "Odesílání hodnot do EEPROM", SystemIcons.Asterisk);
                    EnaDisaControlButtons(true);
                }
                else
                {

                    mbm.MakeMessage("V průběhu odesílání dat do programátora se vyskytla chyba.", "Odesílání hodnot do EEPROM", SystemIcons.Error);
                    EnaDisaControlButtons(true);
                    usb.FindFTDIDevice();
                }

            }
                 else {

                     mbm.MakeMessage("Neplatná kombinace na signálovém přepínači.", "Neplatná kombinace", SystemIcons.Exclamation);
                     EnaDisaControlButtons(true);
                 }
            }
         
            else
            {


                mbm.MakeMessage("Komunikace s programátorem otestována jako chybná.", "Komunikace s programátorem", SystemIcons.Error);
                EnaDisaControlButtons(true);
                usb.FindFTDIDevice();

            }
         
        }

        private void button4_Click(object sender, EventArgs e)
        {
            EnaDisaControlButtons(false);
            if (usb.CircuitEcho())
            {

                if (usb.GetAllValuesFromRAM())
                {

                    mbm.MakeMessage("Nastavené hodnoty úspěšně získány z RAM programátora.", "Stahování hodnot z RAM", SystemIcons.Asterisk);
                    usb.ControlRegisters.TickToReloadProperties = true;
                    EnaDisaControlButtons(true);
                }
                else
                {

                    mbm.MakeMessage("V průběhu získávání dat z programátora se vyskytla chyba.", "Stahování hodnot z RAM", SystemIcons.Error);
                    EnaDisaControlButtons(true);
                    usb.FindFTDIDevice();
                }

            }
            else
            {


                mbm.MakeMessage("Komunikace s programátorem otestována jako chybná.", "Komunikace s programátorem", SystemIcons.Error);
                EnaDisaControlButtons(true);
                usb.FindFTDIDevice();

            }
       
        }

        private void button5_Click(object sender, EventArgs e)
        {
            EnaDisaControlButtons(false);
            if (usb.CircuitEcho())
            {

                if (usb.GetAllValuesFromEEPROM())
                {

                    mbm.MakeMessage("Nastavené hodnoty úspěšně získány z EEPROM programátora.", "Stahování hodnot z EEPROM", SystemIcons.Asterisk);
                    usb.ControlRegisters.TickToReloadProperties = true;
                    EnaDisaControlButtons(true);
                }
                else
                {

                    mbm.MakeMessage("V průběhu získávání dat z programátora se vyskytla chyba.", "Stahování hodnot z EEPROM", SystemIcons.Error);
                    EnaDisaControlButtons(true);
                    usb.FindFTDIDevice();
                }

            }
            else
            {


                mbm.MakeMessage("Komunikace s programátorem otestována jako chybná.", "Komunikace s programátorem", SystemIcons.Error);
                EnaDisaControlButtons(true);
                usb.FindFTDIDevice();

            }
      
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            EnableBlockErrorMessage = checkBox1.Checked;
        }

        private void servoloops1_CheckedChanged(object sender, EventArgs e)
        {
            usb.ControlRegisters.SERVO_ENAS1 = servoloops1.Checked;
        }

        private void servoloops2_CheckedChanged(object sender, EventArgs e)
        {
            usb.ControlRegisters.SERVO_ENAS2 = servoloops2.Checked;
        }


        int groupbox1konstH = 252;

        private void Form1_Resize(object sender, EventArgs e)
        {

            int listview3w = listView3.Columns[0].Width + listView3.Columns[1].Width + listView3.Columns[2].Width + listView3.Columns[3].Width + listView3.Columns[4].Width;
            int maxlow = groupBox6.Size.Width + groupBox7.Size.Width + groupBox8.Size.Width + listview3w + 25; 

            Control control = (Control)sender;

            if (control.Size.Width < maxlow)
            {

                groupBox5.Width = control.Size.Width - groupBox5.Location.X - groupBox1.Width - 30;
                groupBox5.Height = control.Size.Height - groupBox5.Location.Y - groupBox6.Height - 50;
                RenderWin.Location = new Point(6, 19);
                RenderWin.Width = groupBox5.Width - 2 * RenderWin.Location.X;
                RenderWin.Height = groupBox5.Height - 2 * RenderWin.Location.Y + 10;
                groupBox9.Width = control.Size.Width - (groupBox6.Width + groupBox7.Width + groupBox8.Width) - 50;
                listView3.Width = groupBox9.Width - 10;

                groupBox7.Location = new Point(groupBox6.Location.X + groupBox6.Width + 5, groupBox7.Location.Y);
                groupBox8.Location = new Point(groupBox7.Location.X + groupBox7.Width + 5, groupBox8.Location.Y);
                groupBox9.Location = new Point(groupBox8.Location.X + groupBox8.Width + 5, groupBox9.Location.Y);

            }

            else {

                groupBox5.Width = control.Size.Width - groupBox5.Location.X - groupBox1.Width - 30;
                groupBox5.Height = control.Size.Height - groupBox5.Location.Y - groupBox6.Height - 50;
                RenderWin.Location = new Point(6, 19);
                RenderWin.Width = groupBox5.Width - 2 * RenderWin.Location.X;
                RenderWin.Height = groupBox5.Height - 2 * RenderWin.Location.Y + 10;

                if ((control.Size.Width - (groupBox6.Width + groupBox7.Width + groupBox8.Width) - 50) < listview3w)
                {

                    groupBox9.Width = control.Size.Width - (groupBox6.Width + groupBox7.Width + groupBox8.Width) - 50;
                    

                }
                else {

                    groupBox9.Width = listview3w + 10;

                
                }
                listView3.Width = groupBox9.Width - 10;

                int constant = (control.Size.Width - (groupBox6.Width + groupBox7.Width + groupBox8.Width + groupBox9.Width)) /3 - 5;

                groupBox7.Location = new Point(groupBox6.Location.X + groupBox6.Width + constant -5, groupBox7.Location.Y);
                groupBox8.Location = new Point(groupBox7.Location.X + groupBox7.Width + constant - 5, groupBox8.Location.Y);
                groupBox9.Location = new Point(groupBox8.Location.X + groupBox8.Width + constant - 5, groupBox9.Location.Y);
            }

            label3.Location = new Point(groupBox5.Location.X + RenderWin.Size.Width - label3.Width - 30, groupBox5.Location.Y + label3.Height);
            checkBox1.Location = new Point(groupBox5.Location.X + RenderWin.Size.Width - checkBox1.Width - 10, groupBox5.Location.Y + RenderWin.Size.Height - 2 * checkBox1.Height - 10);
            checkBox2.Location = new Point(groupBox5.Location.X + RenderWin.Size.Width - checkBox2.Width - 10, groupBox5.Location.Y + RenderWin.Size.Height - 10 - checkBox2.Height);


            groupBox1.Height = groupbox1konstH;
            groupBox2.Height = control.Size.Height - groupbox1konstH - groupBox9.Height - 50;
            groupBox2.Location = new Point(groupBox1.Location.X, groupBox1.Location.Y + groupBox1.Height + 5);
            groupBox3.Location = new Point(5, 15);

            groupBox3.Height = (groupBox2.Height - 30) / 2;

            groupBox4.Location = new Point(5, 20 + groupBox3.Height);
            groupBox4.Height = groupBox3.Height;
            listView1.Location = new Point(5, 15);
            listView1.Height = groupBox3.Height - 2 * listView1.Location.Y + 10;
            listView2.Location = new Point(5, 15);
            listView2.Height = groupBox4.Height - 2 * listView2.Location.Y + 10;
            if (WindowState == FormWindowState.Maximized)
            {

                isMaximalized = true;

            }
            else {

                isMaximalized = false;
            
            }

         }

        private void Form1_Load(object sender, EventArgs e)
        {

            if (Err == false)
            {
               // groupbox1konstH = groupBox1.Height;
                ReloadGUI();
                //shiftconst = trackBar1.Value;
            }
            else {

                Application.Exit();
            
            }
        }

        private void listView2_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (e.IsSelected) {

                e.Item.Selected = false;
            
            }
        }

        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (e.IsSelected)
            {

                e.Item.Selected = false;

            }
        }

        private void listView3_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if ((e.CurrentValue == CheckState.Unchecked) && (e.NewValue == CheckState.Checked))
            {


                if (listView3.CheckedItems.Count == 0)
                {
                    uint gool = uint.Parse(listView3.Items[e.Index].SubItems[3].Text);
                    
                    usb.SetActiveDeviceLoc = gool;
                    SetEnabledButtons(true);

                }


                if (listView3.CheckedItems.Count > 0)
                {

                    for (int i = 0; i < listView3.CheckedItems.Count; i++)
                    {

                        listView3.CheckedItems[i].Checked = false;

                    }

                    //string gool = listView1.Items[e.Index].SubItems[1].Text;
                    uint gool = uint.Parse(listView3.Items[e.Index].SubItems[3].Text);

                    usb.SetActiveDeviceLoc = gool;
                    SetEnabledButtons(true);
                }

            }

        }

        public enum WINAPI_MSG { 
        
        WM_KEYDOWN=0x100,
        WM_KEYUP=0x101,
        WM_CHAR=0x102,
        WM_SYSKEYDOWN=0x104,
        WM_SYSKEYUP=0x105
        
        }


            protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
            {

                if(EventDrivenKeyboard == false){
                if (keyData == Keys.Left)
                {
                    if (msg.Msg == (int)WINAPI_MSG.WM_KEYDOWN) {

                        EventDrivenKeyboard = true;
                        shiftright = true;
                        KeyDrivenEvent.Enabled = true;
                        KeyDrivenEvent.Start();
                        ComponentSettingsRendering(true);
                    
                        return true;
                    }
                }

                if (keyData == Keys.Right)
                {
                    if (msg.Msg == (int)WINAPI_MSG.WM_KEYDOWN)
                    {
                        
                        EventDrivenKeyboard = true;
                        shiftleft = true;
                        KeyDrivenEvent.Enabled = true;
                        KeyDrivenEvent.Start();
                        ComponentSettingsRendering(true);
                 
                        return true;
                    }
                }

                if (keyData == Keys.Up)
                {
                    if (msg.Msg == (int)WINAPI_MSG.WM_KEYDOWN)
                    {
                        
                        EventDrivenKeyboard = true;
                        shiftdown = true;
                        KeyDrivenEvent.Enabled = true;
                        KeyDrivenEvent.Start();
                        ComponentSettingsRendering(true);
                 
                        return true;
                    }
                }

                if (keyData == Keys.Down)
                {
                    if (msg.Msg == (int)WINAPI_MSG.WM_KEYDOWN)
                    {
                        
                        EventDrivenKeyboard = true;
                        shifttop = true;
                        KeyDrivenEvent.Enabled = true;
                        KeyDrivenEvent.Start();
                        ComponentSettingsRendering(true);
                 
                        return true;
                    }
                }

            }
                return base.ProcessCmdKey(ref msg, keyData);
            }



            private void button8_Click(object sender, EventArgs e)
            {
                usb.FindFTDIDevice();

            }


            private void Form1_Paint(object sender, PaintEventArgs e)
            {
                SchemePaint();
            }



            private void button7_Click_1(object sender, EventArgs e)
            {
                if (console.ConsoleShowed == false)
                {
                    
                    console.OpenConsoleWindow();
                    console.ConsoleShowed = true;
                    button7.Text = "Skrýt konzolu";

                }
                else {

                    console.CloseConsoleWindow();
                    console.ConsoleShowed = false;
                    button7.Text = "Zobrazit konzolu";
                }
            }

            int charonline = 25;
            
            private void button9_Click(object sender, EventArgs e)
            {
     
                if (listBox1.SelectedIndex != -1)
                {
                    if (usb.profiler.TestExistFile(listBox1.Items[listBox1.SelectedIndex].ToString()))
                    {
                        progressBar1.Visible = false;
                        try
                        {
                            usb.profiler.ConvertXmlToMem(usb.profiler.ReadXmlFile(listBox1.Items[listBox1.SelectedIndex].ToString()), out usb.BytesMemory);
                        }
                        catch (Exception x) {

                            mbm.MakeMessage("Chyba souborové operace profileru." + Environment.NewLine + Environment.NewLine + "Zpráva chyby: " + x.Message, "Chyba", SystemIcons.Error);
                        
                        }
                        usb.DictToProp();

                        DivideCharactersBetweenTwoLines("Nastavení načteno z \"" + listBox1.Items[listBox1.SelectedIndex].ToString() + "\".", charonline);
                   
                    }
                    else
                    {
                        progressBar1.Visible = false;
                        usb.profiler.SearchFiles();
                         DivideCharactersBetweenTwoLines("Nastavení nezměněno.", charonline);
                    }

                }
                else {
                    progressBar1.Visible = false;
                    DivideCharactersBetweenTwoLines("Nastavení nezměněno.", charonline);
                
                }
                button9.Enabled = false;
                button10.Enabled = false;
                button11.Enabled = false;
                button12.Enabled = false;
                listBox1.Enabled = false;
            }

            bool profSaving = false;
            bool profRenaming = false;
       

            private void button10_Click(object sender, EventArgs e)
            {
                if (profSaving == false)
                {
                    progressBar1.Visible = false;

                    label4.Visible = false;
                    label5.Visible = false;
                    button9.Enabled = false;
                    button11.Enabled = false;
                    button12.Enabled = false;

                    if (listBox1.SelectedIndex == -1)
                    {

                        textBox1.Visible = true;
                        textBox1.Text = DateTime.Now.ToString("d_M_yyyy HH_mm_ss");
                        textBox1.SelectAll();
                        textBox1.Focus();
                        listBox1.Enabled = false;
                    }
                    else {

                        textBox1.Visible = true;
                        textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
                        textBox1.Focus();
                        listBox1.Enabled = false;
                    
                    }
                    profSaving = true;
                }
                else {

                    if (listBox1.SelectedIndex == -1)
                    {

                        if (textBox1.Text != string.Empty)
                        {
                            try
                            {
                                usb.profiler.WriteXmlFile(textBox1.Text, usb.profiler.ConvertMemToXml(usb.BytesMemory));
                            }
                            catch (Exception x) {

                                mbm.MakeMessage("Chyba souborové operace profileru." + Environment.NewLine + Environment.NewLine + "Zpráva chyby: " + x.Message, "Chyba", SystemIcons.Error);
                            
                            }
                            textBox1.Visible = false;

                            DivideCharactersBetweenTwoLines("Nastavení uloženo pod položkou \"" + textBox1.Text + "\".", charonline);
                            textBox1.Text = "";
                            listBox1.SelectedIndex = -1;
                            usb.profiler.SearchFiles();
                            profSaving = false;
                            button9.Enabled = false;
                            button10.Enabled = false;
                            button11.Enabled = false;
                            button12.Enabled = false;

                            listBox1.Enabled = false;
                        }

                    }
                    else {

                        if (textBox1.Text != string.Empty)
                        {
                            DivideCharactersBetweenTwoLines("Nastavení \"" + listBox1.Items[listBox1.SelectedIndex].ToString() + "\" přepsáno pod položkou \"" + textBox1.Text + "\".", charonline);
                            usb.profiler.DeleteFile(listBox1.Items[listBox1.SelectedIndex].ToString());
                            try
                            {
                                usb.profiler.WriteXmlFile(textBox1.Text, usb.profiler.ConvertMemToXml(usb.BytesMemory));
                            }
                            catch (Exception x) {

                                mbm.MakeMessage("Chyba souborové operace profileru." + Environment.NewLine + Environment.NewLine + "Zpráva chyby: " + x.Message, "Chyba", SystemIcons.Error);
                            
                            }
                            textBox1.Visible = false;
                            textBox1.Text = "";
                            listBox1.SelectedIndex = -1;
                            usb.profiler.SearchFiles();
                            profSaving = false;
                            button9.Enabled = false;
                            button10.Enabled = false;
                            button11.Enabled = false;
                            button12.Enabled = false;
                            listBox1.Enabled = false;
                        }

                        
                    }
                   

                }

            }

            private void listBox1_MouseDown(object sender, MouseEventArgs e)
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Right) {

                    listBox1.SelectedIndex = -1;
                
                }
            }

            private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                if((profRenaming == false)&&(profSaving == false)){
                if (listBox1.SelectedIndex == -1)
                {
                    button10.Enabled = true;
                    button9.Enabled = false;
                    button11.Enabled = false;
                    button12.Enabled = false;

                }
                else {

                    if (usb.profiler.TestExistFile(listBox1.Items[listBox1.SelectedIndex].ToString()))
                    {

                        button10.Enabled = true;
                        button9.Enabled = true;
                        button11.Enabled = true;
                        button12.Enabled = true;
                    }
                    else {

                        usb.profiler.DeleteFile(listBox1.Items[listBox1.SelectedIndex].ToString());
                        
                        usb.profiler.SearchFiles();

                        button10.Enabled = true;
                        button9.Enabled = false;
                        button11.Enabled = false;
                        button12.Enabled = false;

                        listBox1.SelectedIndex = -1;

                    }
                
                }
                }
            }

            private void button11_Click(object sender, EventArgs e)
            {
            
                if (listBox1.SelectedIndex > -1) {
                    progressBar1.Visible = false;
                    DivideCharactersBetweenTwoLines("Nastavení \"" + listBox1.Items[listBox1.SelectedIndex].ToString() + "\" smazáno.", charonline);
                    usb.profiler.DeleteFile(listBox1.Items[listBox1.SelectedIndex].ToString());
                    usb.profiler.SearchFiles();
                    button9.Enabled = false;
                    button11.Enabled = false;
                    button12.Enabled = false;
                    button10.Enabled = false;
                    listBox1.Enabled = false;
                }
            }

            string oldnameX = string.Empty;

            private void button12_Click(object sender, EventArgs e)
            {

                if(listBox1.SelectedIndex > -1){
             

                if (profRenaming == false)
                {
                    progressBar1.Visible = false;
                oldnameX = listBox1.Items[listBox1.SelectedIndex].ToString();

                label4.Visible = false;
                label5.Visible = false;
                    button9.Enabled = false;
                    button10.Enabled = false;
                    button11.Enabled = false;

                        textBox1.Visible = true;
                        textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
                        textBox1.Focus();

                    profRenaming = true;
                    listBox1.Enabled = false;
                }
                else
                {

                    if ((textBox1.Text != string.Empty) && (textBox1.Text != oldnameX) && !usb.profiler.TestExistFile(textBox1.Text))
                        {
                            usb.profiler.RenameFile(textBox1.Text, oldnameX);
                            textBox1.Visible = false;

                            DivideCharactersBetweenTwoLines("Nastavení \"" + oldnameX + "\" přejmenováno na \"" + textBox1.Text + "\".", charonline);
                            textBox1.Text = "";
                            listBox1.SelectedIndex = -1;
                            usb.profiler.SearchFiles();
                            profRenaming = false;
                            button12.Enabled = false;
                            button9.Enabled = false;
                            button10.Enabled = false;
                            button11.Enabled = false;
                            listBox1.Enabled = false;
                        }


                }
            }
        }

            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                console.FreeConsoleX();
            }

            private void textBox1_KeyDown(object sender, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Enter) {


                    if (profSaving == true)
                    {



                        if (listBox1.SelectedIndex == -1)
                        {

                            if (textBox1.Text != string.Empty)
                            {
                                try
                                {
                                    usb.profiler.WriteXmlFile(textBox1.Text, usb.profiler.ConvertMemToXml(usb.BytesMemory));
                                }
                                catch (Exception x) {

                                    mbm.MakeMessage("Chyba souborové operace profileru." + Environment.NewLine + Environment.NewLine + "Zpráva chyby: " + x.Message, "Chyba", SystemIcons.Error);
                                
                                }
                                textBox1.Visible = false;

                                DivideCharactersBetweenTwoLines("Nastavení uloženo pod položkou \"" + textBox1.Text + "\".", charonline);
                                textBox1.Text = "";
                                listBox1.SelectedIndex = -1;
                                usb.profiler.SearchFiles();
                                profSaving = false;
                                button12.Enabled = false;
                                button9.Enabled = false;
                                button10.Enabled = false;
                                button11.Enabled = false;
                                listBox1.Enabled = false;
                            }

                        }
                        else
                        {

                            if (textBox1.Text != string.Empty)
                            {
                                DivideCharactersBetweenTwoLines("Nastavení \"" + listBox1.Items[listBox1.SelectedIndex].ToString() + "\" přepsáno pod položkou \"" + textBox1.Text + "\".", charonline);
                                usb.profiler.DeleteFile(listBox1.Items[listBox1.SelectedIndex].ToString());
                                try
                                {
                                    usb.profiler.WriteXmlFile(textBox1.Text, usb.profiler.ConvertMemToXml(usb.BytesMemory));
                                }
                                catch (Exception x) {

                                    mbm.MakeMessage("Chyba souborové operace profileru." + Environment.NewLine + Environment.NewLine + "Zpráva chyby: " + x.Message, "Chyba", SystemIcons.Error);
                                }
                                textBox1.Visible = false;
                                textBox1.Text = "";
                                listBox1.SelectedIndex = -1;
                                usb.profiler.SearchFiles();
                                profSaving = false;
                                button12.Enabled = false;
                                button9.Enabled = false;
                                button10.Enabled = false;
                                button11.Enabled = false;
                                listBox1.Enabled = false;
                            }


                        }




                    }


                    if (profRenaming == true)
                    {


                        if ((textBox1.Text != string.Empty) && (textBox1.Text != oldnameX) && !usb.profiler.TestExistFile(textBox1.Text))
                        {
                            usb.profiler.RenameFile(textBox1.Text, oldnameX);
                            textBox1.Visible = false;

                            DivideCharactersBetweenTwoLines("Nastavení \"" + oldnameX + "\" přejmenováno na \"" + textBox1.Text + "\".", charonline);
                            textBox1.Text = "";
                            listBox1.SelectedIndex = -1;
                            usb.profiler.SearchFiles();
                            profRenaming = false;
                            button12.Enabled = false;
                            button9.Enabled = false;
                            button10.Enabled = false;
                            button11.Enabled = false;
                            listBox1.Enabled = false;
                        }
                    }
                 
                
                }
            }

            private void button13_Click(object sender, EventArgs e)
            {
                if (!Directory.Exists("screenshots"))
                {
                    Directory.CreateDirectory(RuntimeDir + "\\screenshots\\");
                }

                string dt = DateTime.Now.ToString("d_M_yyyy HH_mm_ss");

                try
                {

                    Scheme.Save(RuntimeDir + "\\screenshots\\" + dt + ".png", System.Drawing.Imaging.ImageFormat.Png);

                    mbm.MakeMessage("Screenshot schématu " + dt + ".png" + " byl vytvořen.", "Screenshot", SystemIcons.Asterisk);
                    console.AdvancedCharactersInConsole(ConsoleTypeOfMessage.Screenshot, DateTime.Now, "Screenshot schématu " + dt + ".png byl úspěšně vytvořen.");

                    if (File.Exists(RuntimeDir + "\\screenshots\\" + dt + ".png"))
                    {
                        System.Diagnostics.Process.Start("explorer.exe", @"/select, " + RuntimeDir + "\\screenshots\\" + dt + ".png");
                    }

                }
                catch (Exception f) {

                    mbm.MakeMessage("Screenshot " + dt + ".png" + " se nepodařilo vytvořit.\n" + f.Message, "Chyba", SystemIcons.Error);
                
                }

            }

            private void checkBox2_CheckedChanged(object sender, EventArgs e)
            {
                usb.ControlRegisters.Alotpropertiestothumbinals = checkBox2.Checked;

                if (servoloops1.Checked == true)
                {

                    servoloops1.Checked = false;
                    servoloops1.Checked = true;

                }
                else {


                    servoloops1.Checked = true;
                    servoloops1.Checked = false;
                
                }
            }


    }
            
}
