// Author: Tamas Borsanyi aka Tomixworks - tomix89@centrum.sk
// Program : visual c# express 2010

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.IO;
using CyUSB;


//public enum Type_Trig { None, Edge, Pls_Width, Pattern } // triger type is determined by highlighted trig button
public enum Mode_EdgeSlope { Rising, Falling, Both }
public enum Type_PW { Pos, Neg }
public enum Mode_PW { More, Less, Between }
public enum Mode_Coupling { AC, DC }
public enum Mode_Trigger { Auto, Normal }
public enum Type_Trigger { Edge, PulseW, Pattern }

public struct Chanel
{
    //public bool active; // referenced by color of chanel labels
    public int ChanelNum;
    public bool Invert;   // active true false
    public int AmpLevel; // amp levels regarding to AmpLabels
    public int Position; // position on the screen
    public Mode_Coupling Coupling; // ac   dc
    public byte Probe; // 1 - 1:1    10 - 1:10
}


public struct Pattern_settings
{
    //public bool active; // referenced by color of chanel labels
    public byte CH1;
    public byte CH2;
    public byte CH3;
    public byte D0;
    public byte D1;
    public byte D2;
    public byte D3;
    public byte D4;
    public byte D5;
    public byte D6;
    public byte D7;
}

public struct Trigger
{
    public byte TrigOnCH; //  1 2 3  or 81 - 89 digi
    public Mode_EdgeSlope EdgeSlope;  // Rising   Falling 
    public Mode_PW PulseWMode; // < >   <>
    public Type_PW PulseWType;// pos pule     neg pulse

    public Type_Trigger TrigType;// Edge, PulseW, Pattern

    public int PWLvlLow; // time level for pulse width low
    public int PWLvlHi; // time level for pulse width high
}

public struct PwLevel_orig_struct // it changes only if manually the time is set (not if time_index is chnged)
{
    public int LowLvl; // time level for pulse width low
    public int HiLvl; // time level for pulse width high

    public int lo_deci_index;
    public int hi_deci_index;
}

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        USBDeviceList usbDevices;
        CyUSBDevice MyDevice;

        Chanel[] CH = new Chanel[4]; //chanel setting container
        Trigger TrigSettings; // trigger setting container
        PwLevel_orig_struct PwLevel_orig; // pw setiings container
        Mode_Trigger triggerMode; //the only property wich is doubled, and checked not by color
        // necessary to speed up the trigger loop

        Thread tListen;

        DateTime lastTrigTime = DateTime.Now;
        int timeout = 1200; //in milisec

        int time_index = 12;                 // 100us 1:1, no decimating or interpolating
        // 200us every 2nd sample is taken

        ushort BtnPressed_reg = 0; // used by bits -> 8 bit shiftreg
  
        int BtnCntr = 0;
        bool isLoggerRunning = false;

        int takenSampleNum = 0;

        int[] c_deci_index = { 1, 1, 1, 1, 1, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000 }; // if the time is smaller samples cannot be decimated more

        int TrigsFound = 0;

        byte digi_delayd;

        int CH1_comp = 2030;


        Pattern_settings Ptrn_set;

        int edgeHyst = 12;
        string[] TimeLabels = { "200ns", "500ns", "1us", "2us", "5us", "10us", "20us", "50us", "100us", "200us", "500us", "1ms", "2ms", "5ms", "10ms" };
        int[] deci_index = new int[15];
        double[] intp_index = { 0.02, 0.05, 0.1, 0.2, 0.5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // if the time is bigger samples cannot be interpolated more

        const byte LEDG1 = (1 << 1);
        const byte LEDR1 = (1 << 0);
        const byte LEDG2 = (1 << 3);
        const byte LEDR2 = (1 << 2);
        const byte RELE1 = (1 << 5);
        const byte RELE2 = (1 << 4);

        const byte LEDG_digi = (1 << 4);
        const byte LEDR_digi = (1 << 5);
        
        const byte RELE3 = (1 << 0);
        const byte LEDG3 = (1 << 1);
        const byte LEDR3 = (1 << 2);
        const byte Logging_LED = (1 << 7);

        Mode_EdgeSlope lastTrigWas = Mode_EdgeSlope.Rising;

        string[] AmpLabels = { " 50mV", "100mV", "200mV", "500mV", "  1V ", "  2V ", "  5V " };
        //  int[] AmpLevels = { 102, 219, 326, 480, 598, 721, 883 };
        int[] AmpLevels = { 123, 238, 335, 501, 614, 721 };

        //  int[] ShiftLevelsMax = { 2091, 2132, 2215, 2464, 2986, 3903 };
        // int[] ShiftLevelsMin = { 2005, 1964, 1881, 1632, 1110, 193 };

        static int[] levels = { 50, 100, 200, 500, 1000, 2000 };
        static double[] maxoffset = { 1.06, 1.08, 1.15, 1.08, 1.10, 1.15 };

        int[] ShiftLevelsMax = {2048 + (int)(levels[0] / maxoffset[0]), 
                                2048 +    (int)(levels[1] / maxoffset[1]),
                                 2048 +  (int)(levels[2]/maxoffset[2]),
                                  2048 +  (int)(levels[3]/maxoffset[3]),
                                   2048 + (int)(levels[4]/maxoffset[4]),
                                2048 +(int)(levels[5]/maxoffset[5])};

        int[] ShiftLevelsMin = {  2048 - (int)(levels[0] / maxoffset[0]), 
                                  2048 -  (int)(levels[1] / maxoffset[1]),
                                   2048 - (int)(levels[2]/maxoffset[2]),
                                    2048 - (int)(levels[3]/maxoffset[3]),
                                    2048 - (int)(levels[4]/maxoffset[4]),
                                2048 - (int)(levels[5]/maxoffset[5])};


        byte trigLvl = 128;
        bool trigfound_rise = false;
        bool trigfound_rise_hyst = false;

        bool trigfound_fall = false;
        bool trigfound_fall_hyst = false;


        bool trigfound = false;
        bool canDrawNow = false;

        bool trigtimeout = false;

        bool disble_event_PW_combos = false;
        bool disble_event_Pattern = false;

        //bool mutex_drawing = false; // for avoiding the untriggered screen refresh to collide with writing of the mainbuff

        long current_pos = 0;
        bool PWcountEn = false;
        int PWcount = 0;

        const long CHx_mainbuff_size = (int)(1.5 * 533); // length necessary to not overwrite the sampled data, while they being swohed -- solved
        // length necessary to have the trigger in the middle of the screen

        long CHx_mainbuff_cntr = 0;

        int oldbarPositionVal;

        byte[] CH1_mainbuff = new byte[CHx_mainbuff_size]; // ch1 buff
        byte[] CH2_mainbuff = new byte[CHx_mainbuff_size]; // ch2 buff
        byte[] CH3_mainbuff = new byte[CHx_mainbuff_size]; // ch2 buff
        byte[] CH4_mainbuff = new byte[CHx_mainbuff_size]; // ch4 buff alias digi

        byte[] CH1_logbuff = new byte[16]; // ch1 buff
        byte[] CH2_logbuff = new byte[16]; // ch2 buff
        byte[] CH3_logbuff = new byte[16]; // ch2 buff
        byte[] CH4_logbuff = new byte[16]; // ch4 buff alias digi

        bool isCh1Active = false;
        bool isCh2Active = false;
        bool isCh3Active = false;
        bool isCh4Active = false;

        int logBuffLen = 16;

        int logBuffWrPtr = 0;
        bool circBufferFilled = false;
        bool postTrigFull = true; // if not in log mode, set it to full;
        int postTrigCntr = 0;
        int postTrigNum = 0;

        //   byte[] CH1_drawbuff = new byte[533]; // 1 megasamleses buff




        Process externalproc = new Process(); // global variable for identifing the child (logger) process

        //-------------------------------------------------------------------------------------------------------------------
        public Form1()
        {
            InitializeComponent();

            // turn on double buffer
            this.SetStyle(
            ControlStyles.UserPaint |
            ControlStyles.AllPaintingInWmPaint |
            ControlStyles.OptimizedDoubleBuffer, true);


        }
        //-------------------------------------------------------------------------------------------------------------------
        /*Summary
          This is the event handler for device removal. This method resets the device count and searches for the device with 
          VID-PID 04b4-1003
       */
        void usbDevices_DeviceRemoved(object sender, EventArgs e)
        {
            MyDevice = null;
            CheckUSB_Connection();
        }



        /*Summary
           This is the event handler for device attachment. This method  searches for the device with 
           VID-PID 04b4-1003
        */
        void usbDevices_DeviceAttached(object sender, EventArgs e)
        {
            CheckUSB_Connection();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void Form1_Load(object sender, EventArgs e)
        {
            usbDevices = new USBDeviceList(CyConst.DEVICES_CYUSB); //list all devices connected to usb

            byte ChanelPresent = 0xFF;

            byte pw_mode_buff = 0;

            //Assign event handlers for device attachment and device removal.
            usbDevices.DeviceAttached += new EventHandler(usbDevices_DeviceAttached);
            usbDevices.DeviceRemoved += new EventHandler(usbDevices_DeviceRemoved);

            toolStripDeciFaktor.SelectedIndex = 0;
            toolStripPostTrig.SelectedIndex = 0;

            // if this not pass, execution ends here
            CheckUSB_Connection(); // search for the correct

            // label8.Text = "+ - X   " + (char)5167 + " X 0 1 X X " + (char)5169 + " X";

            //textBox2.Text = "ᐯ" + ((char)5167) + ((char)5169);

            comboBoxA1.Items.Add((char)5167); //  falling  "ᐯ"
            comboBoxA1.Items.Add((char)5169);//  rising
            comboBoxA2.Items.Add((char)5167);
            comboBoxA2.Items.Add((char)5169);
            comboBoxA3.Items.Add((char)5167);
            comboBoxA3.Items.Add((char)5169);

            comboBoxD0.Items.Add((char)5167);
            comboBoxD0.Items.Add((char)5169);
            comboBoxD1.Items.Add((char)5167);
            comboBoxD1.Items.Add((char)5169);
            comboBoxD2.Items.Add((char)5167);
            comboBoxD2.Items.Add((char)5169);
            comboBoxD3.Items.Add((char)5167);
            comboBoxD3.Items.Add((char)5169);
            comboBoxD4.Items.Add((char)5167);
            comboBoxD4.Items.Add((char)5169);
            comboBoxD5.Items.Add((char)5167);
            comboBoxD5.Items.Add((char)5169);
            comboBoxD6.Items.Add((char)5167);
            comboBoxD6.Items.Add((char)5169);
            comboBoxD7.Items.Add((char)5167);
            comboBoxD7.Items.Add((char)5169);


            comboBoxA1.SelectedIndex = 0;
            comboBoxA2.SelectedIndex = 0;
            comboBoxA3.SelectedIndex = 0;
            comboBoxD0.SelectedIndex = 0;
            comboBoxD1.SelectedIndex = 0;
            comboBoxD2.SelectedIndex = 0;
            comboBoxD3.SelectedIndex = 0;
            comboBoxD4.SelectedIndex = 0;
            comboBoxD5.SelectedIndex = 0;
            comboBoxD6.SelectedIndex = 0;
            comboBoxD7.SelectedIndex = 0;

            Array.Copy(c_deci_index, deci_index, c_deci_index.Length);
           

            //initialize CHanel 1
            CH[1].ChanelNum = 1; //chanel number
            CH[1].Invert = false;
            CH[1].AmpLevel = 1; // amp levels regarding to AmpLabels
            CH[1].Position = 2048; // position on the screen
            CH[1].Coupling = Mode_Coupling.DC; //  ac     dc
            CH[1].Probe = 1; // 1 - 1:1    10 - 1:10



            //initialize CHanel 2
            CH[2].ChanelNum = 2; //chanel number
            CH[2].Invert = true;
            CH[2].AmpLevel = 1; // amp levels regarding to AmpLabels
            CH[2].Position = 2048; // position on the screen
            CH[2].Coupling = Mode_Coupling.AC; //  ac     dc
            CH[2].Probe = 10; // 1 - 1:1    10 - 1:10

            //initialize CHanel 3
            CH[3].ChanelNum = 3; //chanel number
            CH[3].Invert = false;
            CH[3].AmpLevel = 4; // amp levels regarding to AmpLabels
            CH[3].Position = 2048; // position on the screen
            CH[3].Coupling = Mode_Coupling.DC; //  ac     dc
            CH[3].Probe = 1; // 1 - 1:1    10 - 1:10


            //Trigger type is determined by Color of the trig button
            TrigSettings.TrigOnCH = 1;
            TrigSettings.EdgeSlope = Mode_EdgeSlope.Rising;  // Rising   Falling 

            TrigSettings.PulseWMode = Mode_PW.More; // < >   <>
            TrigSettings.PulseWType = Type_PW.Pos;// pos pule     neg pulse

            TrigSettings.PWLvlLow = 5;
            TrigSettings.PWLvlHi = 4;

            PwLevel_orig.LowLvl = TrigSettings.PWLvlLow;
            PwLevel_orig.HiLvl = TrigSettings.PWLvlHi;
            PwLevel_orig.lo_deci_index = deci_index[time_index];
            PwLevel_orig.hi_deci_index = deci_index[time_index];

            triggerMode = Mode_Trigger.Auto;

            comboBoxChanel.SelectedIndex = 0;

            disble_event_PW_combos = true;
            generatePW_labels();
            disble_event_PW_combos = false;

        
            byte selected_ch=0;

            try
            {
                FileStream fs = new FileStream("last.set", FileMode.Open);
                BinaryReader r = new BinaryReader(fs);

                selected_ch = r.ReadByte();
                TrigSettings.TrigType = (Type_Trigger)(r.ReadByte());
                time_index = r.ReadInt32();

                CH[1].AmpLevel = r.ReadInt32();
                CH[1].Position = r.ReadInt32();
                CH[1].Coupling = (Mode_Coupling)(r.ReadByte());

                CH[2].AmpLevel = r.ReadInt32();
                CH[2].Position = r.ReadInt32();
                CH[2].Coupling = (Mode_Coupling)(r.ReadByte());

                CH[3].AmpLevel = r.ReadInt32();
                CH[3].Position = r.ReadInt32();
                CH[3].Coupling = (Mode_Coupling)(r.ReadByte());

                BarTrigLevel.Value = r.ReadInt32();
                trigLvl = (byte)(255 - BarTrigLevel.Value);

                ChanelPresent = r.ReadByte();

                TrigSettings.EdgeSlope = (Mode_EdgeSlope)(r.ReadByte());

                toolStripPostTrig.SelectedIndex = r.ReadByte();

                pw_mode_buff = r.ReadByte();
                TrigSettings.PulseWType = (Type_PW)(r.ReadByte());
                TrigSettings.PWLvlHi = r.ReadInt32();
                TrigSettings.PWLvlLow = r.ReadInt32();

                comboBoxA1.SelectedIndex = r.ReadInt32();
                comboBoxA2.SelectedIndex = r.ReadInt32();
                comboBoxA3.SelectedIndex = r.ReadInt32();

                comboBoxD0.SelectedIndex = r.ReadInt32();
                comboBoxD1.SelectedIndex = r.ReadInt32();
                comboBoxD2.SelectedIndex = r.ReadInt32();
                comboBoxD3.SelectedIndex = r.ReadInt32();
                comboBoxD4.SelectedIndex = r.ReadInt32();
                comboBoxD5.SelectedIndex = r.ReadInt32();
                comboBoxD6.SelectedIndex = r.ReadInt32();
                comboBoxD7.SelectedIndex = r.ReadInt32(); 


                // close it even if exeption was handled
                r.Close();
                fs.Close();
            }
            catch
            {
                MessageBox.Show("No previous settings found, defaults used",
                                                "Warning",
                                               MessageBoxButtons.OK,
                                               MessageBoxIcon.Exclamation,
                                               MessageBoxDefaultButton.Button2);
            }

           

            if (selected_ch >= 0xD0)
                comboBoxChanel.SelectedIndex = selected_ch + 3 - 0xD0;
            else
                comboBoxChanel.SelectedIndex = selected_ch - 1;

            if ((ChanelPresent & 0x03) > 0)
                labelCH1.BackColor = Color.Fuchsia;
            else
                labelCH1.BackColor = Color.WhiteSmoke;
            

            if ((ChanelPresent & 0x0C) > 0)
                 labelCH2.BackColor = Color.Lime;
            else
                 labelCH2.BackColor = Color.WhiteSmoke;

            if ((ChanelPresent & 0x30) > 0)
                labelCH3.BackColor = Color.Yellow;
            else 
                labelCH3.BackColor = Color.WhiteSmoke;


            if ((ChanelPresent & 0xC0) > 0)
                labelDigi.BackColor = Color.Cyan;
            else
            {
                labelDigi.BackColor = Color.WhiteSmoke;

                // if no digi present clear labels
                comboBoxChanel.Items.Remove("DIGI0");
                comboBoxChanel.Items.Remove("DIGI1");
                comboBoxChanel.Items.Remove("DIGI2");
                comboBoxChanel.Items.Remove("DIGI3");
                comboBoxChanel.Items.Remove("DIGI4");
                comboBoxChanel.Items.Remove("DIGI5");
                comboBoxChanel.Items.Remove("DIGI6");
                comboBoxChanel.Items.Remove("DIGI7");
            }
           // setActiveMenuChanel(checkForActiveChanel());


            disble_event_PW_combos = true;
            comboBigr.SelectedIndex = TrigSettings.PWLvlHi;
            comboSmallr.SelectedIndex =  TrigSettings.PWLvlLow;
            disble_event_PW_combos = false;

            //index must be one smaller, becouse click to picbox increases it
            TrigSettings.PulseWMode = (Mode_PW)((pw_mode_buff - 1) % 2);  
            pictureBox3_Click(null, null);
          





            //initialize form

            labelAmp.Text = AmpLabels[CH[1].AmpLevel];
            labelTime.Text = TimeLabels[time_index];

           

            updateChanelInfo(CH[1]); //chanel info color n text
            updateChanelInfo(CH[2]); //chanel info color n text
            updateChanelInfo(CH[3]); //chanel info color n text

            setActiveMenuChanel(checkForActiveChanel()); //menu color n text
           

            btnAuto.BackColor = (triggerMode == Mode_Trigger.Auto) ? Color.GreenYellow : Color.Transparent;
            btnNormal.BackColor = (triggerMode == Mode_Trigger.Normal) ? Color.GreenYellow : Color.Transparent;

            if (TrigSettings.TrigType == Type_Trigger.Edge)
                btnEdge_Click(null,null);

            if (TrigSettings.TrigType == Type_Trigger.PulseW)
                btnPulseW_Click(null, null);

            if (TrigSettings.TrigType == Type_Trigger.Pattern)
                btnPattern_Click(null, null);

            comboBoxChanel_IndexChanged(null, null);


            // start gathering data
            tListen = new Thread(new ThreadStart(ListenThread));
            tListen.IsBackground = true;
            tListen.Priority = ThreadPriority.Highest;
            tListen.Start();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void Form1_Closing(object sender, FormClosingEventArgs e) // when GUI is closed, the logger main will close too
        {

            btnRunStop.BackColor = Color.OrangeRed;


            byte active_are = 0;



                 if (labelCH1.BackColor == Color.Fuchsia)
                    {
                        active_are |= 0x03;
                    }
                  if (labelCH2.BackColor == Color.Lime)
                    {
                        active_are |= 0x0C;
                    }
                  if (labelCH3.BackColor == Color.Yellow)
                    {
                        active_are |= 0x30;
                    }
                  if (labelDigi.BackColor == Color.Cyan)
                    {
                       active_are |= 0xC0;
                    }


            // save settings
            FileStream fs = new FileStream("last.set", FileMode.Create);
            BinaryWriter w = new BinaryWriter(fs);

            w.Write(TrigSettings.TrigOnCH);
            w.Write(Convert.ToByte(TrigSettings.TrigType));
            w.Write(time_index);

            w.Write(CH[1].AmpLevel);
            w.Write(CH[1].Position);
            w.Write(Convert.ToByte(CH[1].Coupling));

            w.Write(CH[2].AmpLevel);
            w.Write(CH[2].Position);
            w.Write(Convert.ToByte(CH[2].Coupling));

            w.Write(CH[3].AmpLevel);
            w.Write(CH[3].Position);
            w.Write(Convert.ToByte(CH[3].Coupling));

            w.Write(BarTrigLevel.Value);

            w.Write(active_are);

            w.Write(Convert.ToByte(TrigSettings.EdgeSlope));

            w.Write((byte)toolStripPostTrig.SelectedIndex);


            w.Write(Convert.ToByte(TrigSettings.PulseWMode));
            w.Write(Convert.ToByte(TrigSettings.PulseWType));
            w.Write(TrigSettings.PWLvlHi);
            w.Write(TrigSettings.PWLvlLow);

            w.Write(comboBoxA1.SelectedIndex);
            w.Write(comboBoxA2.SelectedIndex);
            w.Write(comboBoxA3.SelectedIndex);

            w.Write(comboBoxD0.SelectedIndex);
            w.Write(comboBoxD1.SelectedIndex);
            w.Write(comboBoxD2.SelectedIndex);
            w.Write(comboBoxD3.SelectedIndex);
            w.Write(comboBoxD4.SelectedIndex);
            w.Write(comboBoxD5.SelectedIndex);
            w.Write(comboBoxD6.SelectedIndex);
            w.Write(comboBoxD7.SelectedIndex);


            w.Close();
            fs.Close();

        }
        //-------------------------------------------------------------------------------------------------------------------
        //-------------------------------------------------USBee---------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------------------------
        private void CheckUSB_Connection()
        {
            USBDevice dev = usbDevices[0x04B4, 0x1003]; // search for the device

            if (dev != null)
            {
                MyDevice = (CyUSBDevice)dev; // if the device is correct make it my device

                GetEndpointsOfNode();


            }
            else
            {
                // btnLogger.Enabled = false;

                Console.Beep(1200, 100);
                Console.Beep(1000, 100);

                // MessageBox.Show("No connection with USB device \n Program will quit", "Error",
                //             MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);


                //  this.Close();

            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void GetEndpointsOfNode()
        {


            if (MyDevice.EndPointCount == 3)
            {
                if ((MyDevice.BulkInEndPt.Address == 0x86) & (MyDevice.BulkOutEndPt.Address == 0x02))
                {
                    btnLogger.Enabled = true;
                }
                else
                {
                    MessageBox.Show("Not correct USB device found\n Program will quit", "Error",
                           MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);


                    this.Close();

                }
            }
            else
            {
                MessageBox.Show("Not correct USB device found\n Program will quit", "Error",
                           MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);


                this.Close();

            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        public unsafe void ListenThread()
        {
            if (MyDevice == null) return;

            CyBulkEndPoint InEndpt = MyDevice.BulkInEndPt;

            byte i;
            int BufSz = InEndpt.MaxPktSize * Convert.ToUInt16(8);
            int QueueSz = Convert.ToUInt16(16);
            int n, m;

            bool takeThisSample;


            int cyclecount = 0; // for flushing n filling
            int decicounter = 1;



            InEndpt.XferSize = BufSz;

            // Setup the queue buffers
            byte[][] cmdBufs = new byte[QueueSz][];
            byte[][] xferBufs = new byte[QueueSz][];
            byte[][] ovLaps = new byte[QueueSz][];



            for (i = 0; i < QueueSz; i++)
            {
                cmdBufs[i] = new byte[CyConst.SINGLE_XFER_LEN + ((InEndpt.XferMode == XMODE.BUFFERED) ? BufSz : 0)];
                xferBufs[i] = new byte[BufSz];
                ovLaps[i] = new byte[CyConst.OverlapSignalAllocSize];
                fixed (byte* tmp0 = ovLaps[i])
                {
                    OVERLAPPED* ovLapStatus = (OVERLAPPED*)tmp0;
                    ovLapStatus->hEvent = PInvoke.CreateEvent(0, 0, 0, 0);
                }
            }
            // Pre-load the queue with requests
            int len = BufSz;
            for (i = 0; i < QueueSz; i++)
                InEndpt.BeginDataXfer(ref cmdBufs[i], ref xferBufs[i], ref len, ref ovLaps[i]);
            i = 0;


            // tests the color of start button 
            // test if there was trigger found, end thread, go to drawing
            // if no trig found, and time elapsed take only 1 buffer

            takenSampleNum = 0;
        
            while (((btnRunStop.BackColor == Color.GreenYellow) || (btnSingle.BackColor == Color.Gold))
                       && ((trigfound == false) || (postTrigFull == false))
                       && (trigtimeout == false))
            {


                fixed (byte* tmp0 = ovLaps[i])
                {
                    OVERLAPPED* ovLapStatus = (OVERLAPPED*)tmp0;
                    if (!InEndpt.WaitForXfer(ovLapStatus->hEvent, 500))
                    {
                        InEndpt.Abort();
                        PInvoke.WaitForSingleObject(ovLapStatus->hEvent, CyConst.INFINITE);
                    }
                }
                if (InEndpt.FinishDataXfer(ref cmdBufs[i], ref xferBufs[i], ref len, ref ovLaps[i]))
                {
                    //XferBytes += len;
                    //Successes++;
                }
                else
                {
                    //Failures++;
                }


                // Re-submit this buffer into the queue
                len = BufSz;
                InEndpt.BeginDataXfer(ref cmdBufs[i], ref xferBufs[i], ref len, ref ovLaps[i]);

                if (cyclecount < 10000)
                {
                    cyclecount++; //count first 10 cycles to distingwish flushing and filling from real transfer
                }

                    if (cyclecount > 2) //flushing data - no need to add to ringbuffer
                    {
                        for (m = 0; m < 8; m++) // from the whole buffer 
                            for (n = 3; n < 511; n += 4) // data extracting
                            {
                                if ((trigfound == false) || (postTrigFull == false))  // if trig was found immediatley stop with filling the buffer
                                {

                                    
                                    //deci index is owerwriten when logger is started    
                                    if ((decicounter % deci_index[time_index]) == 0)
                                        takeThisSample = true;
                                    else
                                        takeThisSample = false;

                                    if (++decicounter >= 10000)
                                        decicounter = 0;


                                    if (takeThisSample)
                                    {
                                        if (isLoggerRunning) // logger mode
                                        {

                                            if (trigfound)
                                            {
                                                postTrigCntr++;
                                            }

                                            if (postTrigCntr >= postTrigNum)
                                            {
                                                postTrigFull = true;
                                            }



                                            if (isCh1Active) 
                                             CH1_logbuff[logBuffWrPtr] = xferBufs[i][512 * m + n];

                                            if (isCh2Active) 
                                                CH2_logbuff[logBuffWrPtr] = xferBufs[i][512 * m + n+1];

                                            if (isCh3Active)
                                                CH3_logbuff[logBuffWrPtr] = xferBufs[i][512 * m + n+2];

                                            if (isCh4Active) 
                                                CH4_logbuff[logBuffWrPtr] = xferBufs[i][512 * m + n+3];


                                            lookforTrigger(); // triggering
                                            if (PWcountEn) PWcount++; // pulse width checking


                                            logBuffWrPtr++;
                                            if (logBuffWrPtr >= logBuffLen)
                                            {
                                                circBufferFilled = true;
                                                logBuffWrPtr = 0;  // circbuffer modul
                                            }


                                        }
                                        else//oscilloscope mode
                                        {


                                            addItemCHx_mainbuff(xferBufs[i][512 * m + n], xferBufs[i][512 * m + n + 1], xferBufs[i][512 * m + n + 2], xferBufs[i][512 * m + n + 3]);

                                            if (cyclecount > 6 * deci_index[time_index]) //reading FPGA buffers to get to actual data, and fill the buffer
                                            {

                                                if (takenSampleNum < 15000) // stop counting
                                                    takenSampleNum++;

                                                lookforTrigger(); // triggering
                                                if (PWcountEn) PWcount++; // pulse width checking
                                            }
                                        }
                                    }
                                }
                            }
                }
        
                i++;
                if (i == QueueSz)
                {
                    i = 0;


                    BtnPressed_reg <<= 1;
                    BtnPressed_reg += (ushort)(xferBufs[15][512 * 7 + 2] & 0x0001);

                    if (BtnPressed_reg == 0x0FFF)
                    {
                     
                        BeginInvoke(new EventHandler(btnLogger_Click), null, null);
                        BtnPressed_reg = 0xFFFF;
                    }


                    //Thread.Sleep(0);
                }
            }


                canDrawNow = true; // if trig was found and thread was finished, the screen could be refreshed
                //BeginInvoke(new EventHandler(timerDraw_Tick), null, null);

           
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void lookforTrigger()
        {
            byte actual;

            //rising and falling edges are tested all the time

                if (TrigSettings.TrigOnCH < 0x04) // mens analog trigger
                {


                    if (isLoggerRunning)
                    {
                        switch (TrigSettings.TrigOnCH)
                        {
                            case 1: actual = CH1_logbuff[logBuffWrPtr]; break;
                            case 2: actual = CH2_logbuff[logBuffWrPtr]; break;
                            case 3: actual = CH3_logbuff[logBuffWrPtr]; break;

                            //case 4: actual = CH4_logbuff[logBuffWrPtr]; break;
                            default: actual = 0; break;
                        }
                    }
                    else
                    {
                        actual = getItemCHx_mainbuff(TrigSettings.TrigOnCH, CHx_mainbuff_cntr - CHx_mainbuff_size / 2);
                    }


                    //----------edge tests---------------------------------------------
                    // rising edge detection
                    if (actual > (trigLvl + edgeHyst))
                    {
                        trigfound_rise_hyst = true;
                    }

                    else if ((actual < (trigLvl)) && trigfound_rise_hyst == true)
                    {
                        current_pos = CHx_mainbuff_cntr - CHx_mainbuff_size / 2;

                        trigfound_rise = true;  // trigger can be set only if data were properly flushed and buffer filled
                        trigfound_rise_hyst = false;
                    }
                    else
                    {
                        //  trigfound_rise = false; 
                    }


                    // falling edge detection
                    if (actual < (trigLvl + edgeHyst))
                    {
                        trigfound_fall_hyst = true;
                    }

                    else if ((actual > (trigLvl)) && trigfound_fall_hyst == true)
                    {
                        current_pos = CHx_mainbuff_cntr - CHx_mainbuff_size / 2;

                        trigfound_fall = true;  // trigger can be set only if data were properly flushed and buffer filled
                        trigfound_fall_hyst = false;
                    }
                    else
                    {
                        //  trigfound_rise = false; 
                    }

                }
                else if ((TrigSettings.TrigOnCH < 0xDF) && (TrigSettings.TrigOnCH >= 0xD0))
                {
                    byte mask;
                    //-------digi triggers------

                    if (isLoggerRunning)
                    {
                        mask = (byte)(1 << (TrigSettings.TrigOnCH - 0xD0)); //mask chanel -- get only 1
                        actual = (byte)(mask & CH4_logbuff[logBuffWrPtr]);
                        //digi_delayd = (byte)(mask & getItemCHx_mainbuff(4, logBuffWrPtr - 1));
                    }
                    else
                    {
                        mask = (byte)(1 << (TrigSettings.TrigOnCH - 0xD0)); //mask chanel -- get only 1
                        actual = (byte)(mask & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - (CHx_mainbuff_size / 2)));
                        //digi_delayd = (byte)(mask & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - (CHx_mainbuff_size / 2) - 1));
                    }

                        //-------rising detect
                    if ((actual > 0) && (digi_delayd == 0))
                        {
                            current_pos = CHx_mainbuff_cntr - CHx_mainbuff_size / 2;
                            trigfound_rise = true;
                        }

                        //-------falling detect
                    if ((actual == 0) && (digi_delayd > 0))
                        {
                            current_pos = CHx_mainbuff_cntr - CHx_mainbuff_size / 2;
                            trigfound_fall = true;
                        }


                    digi_delayd = actual;

                }


            //----triggering---------------------------------------------
            // edge trigering
            if (TrigSettings.TrigType == Type_Trigger.Edge)
            {
                if ((TrigSettings.EdgeSlope == Mode_EdgeSlope.Rising) && (trigfound_rise))
                {
                    trigfound = true;
                }
                else if ((TrigSettings.EdgeSlope == Mode_EdgeSlope.Falling) && (trigfound_fall))
                {
                    trigfound = true;
                }
                else if ((TrigSettings.EdgeSlope == Mode_EdgeSlope.Both) && ((trigfound_fall) || (trigfound_rise)))
                {
                    if ((lastTrigWas == Mode_EdgeSlope.Rising) && (trigfound_fall))
                    {
                        trigfound = true;
                        lastTrigWas = Mode_EdgeSlope.Falling;
                    }
                    else if ((lastTrigWas == Mode_EdgeSlope.Falling) && (trigfound_rise))
                    {
                        trigfound = true;
                        lastTrigWas = Mode_EdgeSlope.Rising;
                    }
                    else
                    {
                        lastTrigWas = trigfound_rise ? Mode_EdgeSlope.Rising : Mode_EdgeSlope.Falling;
                    }
                }
            }
            //pulsewidth triggering
            else if (TrigSettings.TrigType == Type_Trigger.PulseW)
            {
                if (TrigSettings.PulseWType == Type_PW.Pos)
                {
                    if (trigfound_rise)
                    {
                        PWcount = 0;
                        PWcountEn = true;
                        trigfound_rise = false;
                    }

                    if (trigfound_fall)
                    {
                        PWcountEn = false;
                        trigfound_fall = false;
                        // pwcount is cleared after the result is showed on labels
                        //it is necesaary to not to fire the trigger without rising edge detection

                        testPWmode();
                    }
                }
                else // negative pulse
                {
                    if (trigfound_fall)
                    {
                        PWcount = 0;
                        PWcountEn = true;
                        trigfound_fall = false;
                    }

                    if (trigfound_rise)
                    {
                        PWcountEn = false;
                        trigfound_rise = false;
                        // pwcount is cleared after the result is showed on labels
                        //it is necesaary to not to fire the trigger without rising edge detection

                        testPWmode();
                    }
                }
            }
            else if (TrigSettings.TrigType == Type_Trigger.Pattern)
            {
                byte patterncount = 0; // if this is set to 3+8 than trigger
                byte activetrigs_num = 0; // if this is set to 3+8 than trigger

                if (isLoggerRunning)
                {
                    patterncount = testPattern_log_mode(patterncount);
                }
                else
                {
                    patterncount = testPattern_osc_mode(patterncount);
                }

                if (Ptrn_set.CH1 != 0) activetrigs_num++;
                if (Ptrn_set.CH2 != 0) activetrigs_num++;
                if (Ptrn_set.CH3 != 0) activetrigs_num++;

                if (Ptrn_set.D0 != 0) activetrigs_num++;
                if (Ptrn_set.D1 != 0) activetrigs_num++;
                if (Ptrn_set.D2 != 0) activetrigs_num++;
                if (Ptrn_set.D3 != 0) activetrigs_num++;
                if (Ptrn_set.D4 != 0) activetrigs_num++;
                if (Ptrn_set.D5 != 0) activetrigs_num++;
                if (Ptrn_set.D6 != 0) activetrigs_num++;
                if (Ptrn_set.D7 != 0) activetrigs_num++;



                if ((patterncount == activetrigs_num) && (activetrigs_num > 0)) // if all patern met triger
                {
                    trigfound = true;
                }
                else 
                { 
                trigfound_fall = false;
                trigfound_rise = false;
                }
            }

        }
        //-------------------------------------------------------------------------------------------------------------------
        private byte testPattern_log_mode(byte patterncount) // using logBuffWrPtr
        {
            byte databuff = 0;


            //CH1 
            switch (Ptrn_set.CH1)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = CH1_logbuff[logBuffWrPtr];
                    if (databuff > (trigLvl))
                        patterncount++; 
                    break;
                case 1:
                    databuff = CH1_logbuff[logBuffWrPtr];
                    if (databuff < (trigLvl))
                        patterncount++; 
                    break;
            }

            //CH2
            switch (Ptrn_set.CH2)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = CH2_logbuff[logBuffWrPtr];
                    if (databuff > (trigLvl))
                        patterncount++; 
                    break;
                case 1:
                    databuff = CH2_logbuff[logBuffWrPtr];
                    if (databuff < (trigLvl))
                        patterncount++; 
                    break;
            }

            //CH3
            switch (Ptrn_set.CH3)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = CH3_logbuff[logBuffWrPtr];
                    if (databuff > (trigLvl))
                        patterncount++; 
                    break;
                case 1:
                    databuff = CH3_logbuff[logBuffWrPtr];
                    if (databuff < (trigLvl))
                        patterncount++;
                    break;
            }

            //D0
            switch (Ptrn_set.D0)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x01 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff == 0)
                        patterncount++; 
                    break;
                case 1:
                    databuff = (byte)(0x01 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff > 0)
                        patterncount++; 
                    break;
            }


            //D1
            switch (Ptrn_set.D1)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x02 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff == 0)
                        patterncount++; 
                    break;
                case 1:
                    databuff = (byte)(0x02 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff > 0)
                        patterncount++; 
                    break;
            }
            //D2
            switch (Ptrn_set.D2)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x04 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff == 0)
                        patterncount++; 
                    break;
                case 1:
                    databuff = (byte)(0x04 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff > 0)
                        patterncount++; 
                    break;
            }
            //D3
            switch (Ptrn_set.D3)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x08 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff == 0)
                        patterncount++; 
                    break;
                case 1:
                    databuff = (byte)(0x08 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff > 0)
                        patterncount++; 
                    break;
            }
            //D4
            switch (Ptrn_set.D4)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x10 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff == 0)
                        patterncount++; 
                    break;
                case 1:
                    databuff = (byte)(0x10 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff > 0)
                        patterncount++; 
                    break;
            }
            //D5
            switch (Ptrn_set.D5)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x20 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff == 0)
                        patterncount++; 
                    break;
                case 1:
                    databuff = (byte)(0x20 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff > 0)
                        patterncount++; 
                    break;
            }
            //D6
            switch (Ptrn_set.D6)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x40 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff == 0)
                        patterncount++; 
                    break;
                case 1:
                    databuff = (byte)(0x40 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff > 0)
                        patterncount++; 
                    break;
            }
            //D7
            switch (Ptrn_set.D7)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x80 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff == 0)
                        patterncount++; 
                    break;
                case 1:
                    databuff = (byte)(0x80 & CH4_logbuff[logBuffWrPtr]);
                    if (databuff > 0)
                        patterncount++; 
                    break;
            }

            return patterncount;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private byte testPattern_osc_mode(byte patterncount)
        {
            byte databuff = 0;


            //CH1 
            switch (Ptrn_set.CH1)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = getItemCHx_mainbuff(1, CHx_mainbuff_cntr - CHx_mainbuff_size / 2);
                    if (databuff > (trigLvl))
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = getItemCHx_mainbuff(1, CHx_mainbuff_cntr - CHx_mainbuff_size / 2);
                    if (databuff < (trigLvl))
                        patterncount++; //rising
                    break;
            }

            //CH2
            switch (Ptrn_set.CH2)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = getItemCHx_mainbuff(2, CHx_mainbuff_cntr - CHx_mainbuff_size / 2);
                    if (databuff > (trigLvl))
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = getItemCHx_mainbuff(2, CHx_mainbuff_cntr - CHx_mainbuff_size / 2);
                    if (databuff < (trigLvl))
                        patterncount++; //rising
                    break;
            }

            //CH3
            switch (Ptrn_set.CH3)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = getItemCHx_mainbuff(3, CHx_mainbuff_cntr - CHx_mainbuff_size / 2);
                    if (databuff > (trigLvl))
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = getItemCHx_mainbuff(3, CHx_mainbuff_cntr - CHx_mainbuff_size / 2);
                    if (databuff < (trigLvl))
                        patterncount++; //rising
                    break;
            }

            //D0
            switch (Ptrn_set.D0)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x01 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff == 0)
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = (byte)(0x01 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff > 0)
                        patterncount++; //rising
                    break;
            }


            //D1
            switch (Ptrn_set.D1)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x02 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff == 0)
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = (byte)(0x02 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff > 0)
                        patterncount++; //rising
                    break;
            }
            //D2
            switch (Ptrn_set.D2)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x04 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff == 0)
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = (byte)(0x04 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff > 0)
                        patterncount++; //rising
                    break;
            }
            //D3
            switch (Ptrn_set.D3)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x08 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff == 0)
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = (byte)(0x08 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff > 0)
                        patterncount++; //rising
                    break;
            }
            //D4
            switch (Ptrn_set.D4)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x10 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff == 0)
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = (byte)(0x10 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff > 0)
                        patterncount++; //rising
                    break;
            }
            //D5
            switch (Ptrn_set.D5)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x20 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff == 0)
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = (byte)(0x20 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff > 0)
                        patterncount++; //rising
                    break;
            }
            //D6
            switch (Ptrn_set.D6)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x40 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff == 0)
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = (byte)(0x40 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff > 0)
                        patterncount++; //rising
                    break;
            }
            //D7
            switch (Ptrn_set.D7)
            {
                case 0: //do nothing
                    break;
                case 3:
                    if (trigfound_fall)
                        patterncount++; //falling
                    break;
                case 4:
                    if (trigfound_rise)
                        patterncount++; //rising
                    break;
                case 2:
                    databuff = (byte)(0x80 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff == 0)
                        patterncount++; //rising
                    break;
                case 1:
                    databuff = (byte)(0x80 & getItemCHx_mainbuff(4, CHx_mainbuff_cntr - CHx_mainbuff_size / 2));
                    if (databuff > 0)
                        patterncount++; //rising
                    break;
            }

            return patterncount;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void testPWmode()
        {
            switch (TrigSettings.PulseWMode)
            {
                case Mode_PW.More:

                    if (PWcount > ((TrigSettings.PWLvlHi + 1) * 48.0 / 9.0))
                    {
                        trigfound = true;
                        current_pos = CHx_mainbuff_cntr - CHx_mainbuff_size / 2;
                    }

                    break;

                case Mode_PW.Less:

                    if (PWcount < ((TrigSettings.PWLvlLow + 1) * 48.0 / 9.0))
                    {
                        trigfound = true;
                        current_pos = CHx_mainbuff_cntr - CHx_mainbuff_size / 2;
                    }
                    break;

                case Mode_PW.Between:

                    if ((PWcount > ((TrigSettings.PWLvlHi + 1) * 48.0 / 9.0)) && (PWcount < ((TrigSettings.PWLvlLow + 1) * 48.0 / 9.0)))
                    {
                        trigfound = true;
                        current_pos = CHx_mainbuff_cntr - CHx_mainbuff_size / 2;
                    }
                    break;
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void addItemCHx_mainbuff(byte CH1data, byte CH2data, byte CH3data, byte CH4data)
        {
            //if (mutex_drawing == false)
            {
                CH1_mainbuff[CHx_mainbuff_cntr] = CH1data;
                CH2_mainbuff[CHx_mainbuff_cntr] = CH2data;
                CH3_mainbuff[CHx_mainbuff_cntr] = CH3data;
                CH4_mainbuff[CHx_mainbuff_cntr] = CH4data;
                CHx_mainbuff_cntr = ++CHx_mainbuff_cntr % CHx_mainbuff_size;
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private byte getItemCHx_mainbuff(byte chanel, long adress)
        {
            // usually reading 533 points backwards
            // so it is necessary to flip the negative value

            while (adress < 0) //adress can be multiple times smaller, so repeat it until it is positive
                adress = CHx_mainbuff_size + adress;


           // adress = adress % CHx_mainbuff_size;

            switch (chanel)
            {
                case 1: return CH1_mainbuff[adress];
                case 2: return CH2_mainbuff[adress];
                case 3: return CH3_mainbuff[adress];
                case 4: return CH4_mainbuff[adress];
                default: return 0;
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        //---------------------------------------------GUI-------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------------------------
        private void wieverEnableControls()
        {
            btnRunStop.Enabled = true;
            btnSingle.Enabled = true;
            btnTimeM.Enabled = true;
            btnTimeP.Enabled = true;
            btnAmpP.Enabled = true;
            btnAmpM.Enabled = true;
            groupTrigger.Enabled = true;
            menuStrip1.Enabled = true;
            BarPosition.Enabled = true;
            BarTrigLevel.Enabled = true;
            labelCH1.Enabled = true;
            labelCH2.Enabled = true;
            labelCH3.Enabled = true;
            labelDigi.Enabled = true;

            groupBox1.Enabled = true;
            groupBox2.Enabled = true;
            groupBox3.Enabled = true;


            switch (TrigSettings.PulseWMode)
            {
                case Mode_PW.Less:  groupBox5.Enabled = true;
                                    groupBox4.Enabled = false;
                                    break;

                case Mode_PW.More:  groupBox5.Enabled = false;
                                    groupBox4.Enabled = true;
                                    break;

                case Mode_PW.Between: groupBox4.Enabled = true;
                                      groupBox5.Enabled = true;
                                      break;
            
            }



            groupPattern1.Enabled = true;
            groupPattern2.Enabled = true;

        }
        //-------------------------------------------------------------------------------------------------------------------
        private void wieverDisableControls()
        {
            btnRunStop.Enabled = false;
            btnSingle.Enabled = false;
            btnTimeM.Enabled = false;
            btnTimeP.Enabled = false;
            btnAmpP.Enabled = false;
            btnAmpM.Enabled = false;
            groupTrigger.Enabled = false;
            menuStrip1.Enabled = false;
            BarPosition.Enabled = false;
            BarTrigLevel.Enabled = false;
            labelCH1.Enabled = false;
            labelCH2.Enabled = false;
            labelCH3.Enabled = false;
            labelDigi.Enabled = false;

            groupBox1.Enabled = false;
            groupBox2.Enabled = false;
            groupBox3.Enabled = false;
            groupBox4.Enabled = false;
            groupBox5.Enabled = false;

            groupPattern1.Enabled = false;
            groupPattern2.Enabled = false;

        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnLogger_Click(object sender, EventArgs e)
        {
     
                if (panel1.BackColor == Color.Red)  // start logging
                {

                    if (((TrigSettings.TrigOnCH) == 1 && (labelCH1.BackColor != Color.Fuchsia)) ||
                        ((TrigSettings.TrigOnCH) == 2 && (labelCH2.BackColor != Color.Lime)) ||
                        ((TrigSettings.TrigOnCH) == 3 && (labelCH3.BackColor != Color.Yellow)))
                    {

                        Console.Beep(1200, 100);
                        Console.Beep(1000, 100);

                        //isBtnPressed = 0; // the button sometimes misbehaves

                        MessageBox.Show("Please select an active chanel for trigger source",
                                                  "Warning",
                                                    MessageBoxButtons.OK,
                                               MessageBoxIcon.Exclamation,
                                               MessageBoxDefaultButton.Button2);

                    }
                    else
                    {

                        // force the thread to stop
                        trigfound = true;
                        //timerDraw.Enabled = false;


                        label1.Text = "    Logging    ";
                        panel1.BackColor = Color.Lime;

                        groupBoxLOG.Visible = true;
                        picMainscreen.Visible = false;
                        picSidescreen.Visible = false;

                        groupBox1.Visible = false;
                        groupBox2.Visible = false;
                        groupBox3.Visible = false;
                        groupBox4.Visible = false;
                        groupBox5.Visible = false;

                        groupPattern1.Visible = false;
                        groupPattern2.Visible = false;

                        btnRunStop.BackColor = Color.GreenYellow;

                        wieverDisableControls();

                        if (btnPulseW.BackColor == Color.GreenYellow)
                        {
                            TrigSettings.PWLvlLow = (comboSmallr.SelectedIndex + 1) * deci_index[time_index] / (toolStripDeciFaktor.SelectedIndex + 1) - 1;
                            TrigSettings.PWLvlHi = (comboBigr.SelectedIndex + 1) * deci_index[time_index] / (toolStripDeciFaktor.SelectedIndex + 1) - 1;
                        }

                        deci_index[time_index] = toolStripDeciFaktor.SelectedIndex + 1; //owerwrite the deci index, to decimate for logger


                        labelLOG2.Text = "trying to allocate";

                        //test max available mem

                        byte allocable = 0;
                        int amount;
                        byte numOfChanels = 0;


                        if (labelCH1.BackColor == Color.Fuchsia)
                        {
                            numOfChanels++;
                            isCh1Active = true;
                        }
                        if (labelCH2.BackColor == Color.Lime)
                        {
                            numOfChanels++;
                            isCh2Active = true;
                        }
                        if (labelCH3.BackColor == Color.Yellow)
                        {
                            numOfChanels++;
                            isCh3Active = true;
                        }
                        if (labelDigi.BackColor == Color.Cyan)
                        {
                            numOfChanels++;
                            isCh4Active = true;
                        }


                        int total = 2500;
                        switch (numOfChanels)
                        {
                            case 1: amount = total; break; //suma
                            case 2: amount = total / 2; break; //suma
                            case 3: amount = total / 3; break;//suma 
                            case 4: amount = total / 4; break;//suma 
                            default: amount = 1; break;
                        }

                        while (allocable != 1)
                        {
                            try // allocate only selected chanel
                            {
                                if (isCh1Active) Array.Resize(ref CH1_logbuff, amount * 1024 * 1024);
                                if (isCh2Active) Array.Resize(ref CH2_logbuff, amount * 1024 * 1024);
                                if (isCh3Active) Array.Resize(ref CH3_logbuff, amount * 1024 * 1024);
                                if (isCh4Active) Array.Resize(ref CH4_logbuff, amount * 1024 * 1024);
                                allocable = 1;
                            }
                            catch
                            {
                                Array.Resize(ref CH1_logbuff, 16);
                                Array.Resize(ref CH2_logbuff, 16);
                                Array.Resize(ref CH3_logbuff, 16);
                                Array.Resize(ref CH4_logbuff, 16);
                                allocable = 0;
                                amount = (int)(amount * 0.93);
                            }
                        }

                        TrigsFound = 0;
                        // 1024^2 / 1e6 = 1.048576
                        labelLOG1.Text = "record time / chanel: " + (((amount * 1.048576) / (5.333333333 / (toolStripDeciFaktor.SelectedIndex + 1))) / 60.0).ToString("0.###") + " minute";
                        labelLOG2.Text = "total allocated memory:" + (amount * numOfChanels) + " MB";
                        labelLOG3.Text = "posttrig time: " + (((toolStripDeciFaktor.SelectedIndex + 1) / 5.333333333e6) * Math.Pow(10, toolStripPostTrig.SelectedIndex + 1)).ToEngineering() + " s";
                        labelLOG4.Text = "samplerate: " + (5.333333333e6 / (toolStripDeciFaktor.SelectedIndex + 1)).ToEngineering() + " Samp/s";
                        labelLOG5.Text = "Trigs found: 0";


                        logBuffLen = amount * 1024 * 1024;
                        circBufferFilled = false;
                        logBuffWrPtr = 0;  // circbuffer modul
                        postTrigFull = false;



                        //celar not to block the cycle
                        trigfound = false;
                        trigtimeout = false;
                        canDrawNow = false;

                        while (tListen.IsAlive) ;//wait for proper termination


                        isLoggerRunning = true;

                        snedLoggerSettings();

                        //and start in loggermode
                        tListen = new Thread(new ThreadStart(ListenThread));
                        tListen.IsBackground = true;
                        tListen.Priority = ThreadPriority.Highest;
                        tListen.Start();

                    }
                }
                else // stop logging
                {
                    isLoggerRunning = false;
                    label1.Text = "Logging Stopped";
                    panel1.BackColor = Color.Red;

                    snedLoggerSettings();

                    groupBoxLOG.Visible = false;
                    picMainscreen.Visible = true;
                    picSidescreen.Visible = true;

                    //enable control according to selected trigger type
                    if (btnEdge.BackColor == Color.GreenYellow)
                        btnEdge_Click(null, null);
                    if (btnPulseW.BackColor == Color.GreenYellow)
                        btnPulseW_Click(null, null);
                    if (btnPattern.BackColor == Color.GreenYellow)
                        btnPattern_Click(null, null);


                    Array.Resize(ref CH1_logbuff, 16);
                    Array.Resize(ref CH2_logbuff, 16);
                    Array.Resize(ref CH3_logbuff, 16);
                    Array.Resize(ref CH4_logbuff, 16);

                    wieverEnableControls();
                    Array.Copy(c_deci_index, deci_index, c_deci_index.Length); // write back original decimatin for oscillosope wiev

                    if (btnPulseW.BackColor == Color.GreenYellow)
                    {
                       // comboSmallr_SelectedIndexChanged(null, null);// activates buttons all time
                       //  comboBigr_SelectedIndexChanged(null, null);// activates buttons all time

                         TrigSettings.PWLvlHi = comboBigr.SelectedIndex;
                         TrigSettings.PWLvlLow = comboSmallr.SelectedIndex;

                    }


                    logBuffLen = 16;
                    circBufferFilled = false;
                    logBuffWrPtr = 0;  // circbuffer modul
                    postTrigFull = true; // to operate normally


                    timerDraw.Enabled = true;

                }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private int getActiveTrigChanel()
        {
            return TrigSettings.TrigOnCH;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private string generatePW_Timelabel(int time)
        {
            // basic res is 1us -- 100us

            if (time > 999)
                return String.Format("{0,0:f} ms", time / 1000.0);
            else
                return time + " us";

        }
        //-------------------------------------------------------------------------------------------------------------------
        private void generatePW_labels()
        {
            int n;
            int coeff = deci_index[time_index];
            int new_index;

            comboBigr.Items.Clear();
            comboSmallr.Items.Clear();

            for (n = coeff; n <= 100 * coeff; n += coeff)
            {
                comboBigr.Items.Add(generatePW_Timelabel(n));
                comboSmallr.Items.Add(generatePW_Timelabel(n));
            }

            //   comboSmallr.SelectedIndex = TrigSettings.PWLvlLow;
            // comboBigr.SelectedIndex = TrigSettings.PWLvlHi;


            new_index = (PwLevel_orig.HiLvl + 1) * PwLevel_orig.hi_deci_index / deci_index[time_index] - 1;
            if (new_index < 0)
            {
                new_index = 0;
                groupBox4.ForeColor = Color.Red;
            }
            else if (new_index > 99)
            {
                new_index = 99;
                groupBox4.ForeColor = Color.Red;
            }
            else
            {
                groupBox4.ForeColor = Color.Black;
            }
            comboBigr.SelectedIndex = new_index;
            TrigSettings.PWLvlHi = new_index;



            new_index = (PwLevel_orig.LowLvl + 1) * PwLevel_orig.lo_deci_index / deci_index[time_index] - 1;
            if (new_index < 0)
            {
                new_index = 0;
                groupBox5.ForeColor = Color.Red;
            }
            else if (new_index > 99)
            {
                new_index = 99;
                groupBox5.ForeColor = Color.Red;
            }
            else
            {
                groupBox5.ForeColor = Color.Black;
            }
            comboSmallr.SelectedIndex = new_index;
            TrigSettings.PWLvlLow = new_index;

        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnTimeM_Click(object sender, EventArgs e)
        {

          //  timeout = 10;

            if (time_index > 0)
                time_index--;

            labelTime.Text = TimeLabels[time_index];

            disble_event_PW_combos = true;
            generatePW_labels();
            disble_event_PW_combos = false;

           // lastTrigTime = DateTime.Now;
        }

        //-------------------------------------------------------------------------------------------------------------------
        private void btnTimeP_Click(object sender, EventArgs e)
        {
           // timeout = 10;

            if (time_index < 14)
                time_index++;

            labelTime.Text = TimeLabels[time_index];

            disble_event_PW_combos = true;
            generatePW_labels();
            disble_event_PW_combos = false;

          //  lastTrigTime = DateTime.Now;

        }
        //-------------------------------------------------------------------------------------------------------------------
        private void updateChanelInfo(Chanel Actualchanel)
        {
            string coupling;


            if (Actualchanel.Coupling == Mode_Coupling.AC) coupling = " AC";
            else coupling = " DC";

            switch (Actualchanel.ChanelNum)
            {
                case 1:
                    labelCH1.Text = "CH1: " + AmpLabels[CH[1].AmpLevel] + coupling;
                    break;

                case 2:
                    labelCH2.Text = "CH2: " + AmpLabels[CH[2].AmpLevel] + coupling; ;
                    break;

                case 3:
                    labelCH3.Text = "CH3: " + AmpLabels[CH[3].AmpLevel] + coupling; ;
                    break;
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnAmpP_Click(object sender, EventArgs e)
        {
            double szorzo;

            if (panel3.BackColor == Color.Fuchsia)
            {
                if (CH[1].AmpLevel < 5)
                {
                    CH[1].AmpLevel++;
                    labelAmp.Text = AmpLabels[CH[1].AmpLevel];
                    updateChanelInfo(CH[1]);

                    szorzo = ((ShiftLevelsMax[CH[1].AmpLevel] - ShiftLevelsMin[CH[1].AmpLevel]) / 333.0);

                    CH[1].Position = (int)(BarPosition.Value * szorzo + ShiftLevelsMin[CH[1].AmpLevel]);
                    label15.Text = "" + CH[1].Position;
               
                }
            }


            if (panel3.BackColor == Color.Lime)
            {
                if (CH[2].AmpLevel < 5)
                {
                    CH[2].AmpLevel++;
                    labelAmp.Text = AmpLabels[CH[2].AmpLevel];
                    updateChanelInfo(CH[2]);

                    szorzo = ((ShiftLevelsMax[CH[2].AmpLevel] - ShiftLevelsMin[CH[2].AmpLevel]) / 333.0);

                    CH[2].Position = (int)(BarPosition.Value * szorzo + ShiftLevelsMin[CH[2].AmpLevel]);
                    label15.Text = "" + CH[2].Position;
                }
            }

            if (panel3.BackColor == Color.Yellow)
            {
                if (CH[3].AmpLevel < 5)
                {
                    CH[3].AmpLevel++;
                    labelAmp.Text = AmpLabels[CH[3].AmpLevel];
                    updateChanelInfo(CH[3]);

                    szorzo = ((ShiftLevelsMax[CH[3].AmpLevel] - ShiftLevelsMin[CH[3].AmpLevel]) / 333.0);

                    CH[3].Position = (int)(BarPosition.Value * szorzo + ShiftLevelsMin[CH[3].AmpLevel]);
                    label15.Text = "" + CH[3].Position;
                }
            }

           
            snedLoggerSettings();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnAmpM_Click(object sender, EventArgs e)
        {
            double szorzo;

            if (panel3.BackColor == Color.Fuchsia)
            {

                if (CH[1].AmpLevel > 0)
                {
                    CH[1].AmpLevel--;

                    labelAmp.Text = AmpLabels[CH[1].AmpLevel];
                    updateChanelInfo(CH[1]);

                    szorzo = ((ShiftLevelsMax[CH[1].AmpLevel] - ShiftLevelsMin[CH[1].AmpLevel]) / 333.0);

                    CH[1].Position = (int)(BarPosition.Value * szorzo + ShiftLevelsMin[CH[1].AmpLevel]);
                    label15.Text = "" + CH[1].Position;
                   
                }

            }

            if (panel3.BackColor == Color.Lime)
            {

                if (CH[2].AmpLevel > 0)
                {
                    CH[2].AmpLevel--;

                    labelAmp.Text = AmpLabels[CH[2].AmpLevel];
                    updateChanelInfo(CH[2]);

                    szorzo = ((ShiftLevelsMax[CH[2].AmpLevel] - ShiftLevelsMin[CH[2].AmpLevel]) / 333.0);

                    CH[2].Position = (int)(BarPosition.Value * szorzo + ShiftLevelsMin[CH[2].AmpLevel]);
                    label15.Text = "" + CH[2].Position;
                   
                }
            }


            if (panel3.BackColor == Color.Yellow)
            {

                if (CH[3].AmpLevel > 0)
                {
                    CH[3].AmpLevel--;

                    labelAmp.Text = AmpLabels[CH[3].AmpLevel];
                    updateChanelInfo(CH[3]);

                    szorzo = ((ShiftLevelsMax[CH[3].AmpLevel] - ShiftLevelsMin[CH[3].AmpLevel]) / 333.0);

                    CH[3].Position = (int)(BarPosition.Value * szorzo + ShiftLevelsMin[CH[3].AmpLevel]);
                    label15.Text = "" + CH[3].Position;
                }
            }
            snedLoggerSettings();
          
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void comboBigr_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (disble_event_PW_combos == false)
            {

                if (TrigSettings.PulseWMode == Mode_PW.Between)
                {
                    if (comboBigr.SelectedIndex > 98)
                        comboBigr.SelectedIndex = 98;

                    if (comboBigr.SelectedIndex >= comboSmallr.SelectedIndex)
                        comboSmallr.SelectedIndex = comboBigr.SelectedIndex + 1;
                }

                TrigSettings.PWLvlHi = comboBigr.SelectedIndex;
                PwLevel_orig.HiLvl = TrigSettings.PWLvlHi;
                PwLevel_orig.hi_deci_index = deci_index[time_index];

                groupBox4.ForeColor = Color.Black;


            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void comboSmallr_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (disble_event_PW_combos == false)
            {

                if (TrigSettings.PulseWMode == Mode_PW.Between)
                {
                    if (comboBigr.SelectedIndex >= comboSmallr.SelectedIndex)
                        comboBigr.SelectedIndex = comboSmallr.SelectedIndex - 1;

                    if (comboBigr.SelectedIndex < 0)
                        comboBigr.SelectedIndex = 0;
                }
                TrigSettings.PWLvlLow = comboSmallr.SelectedIndex;
                PwLevel_orig.LowLvl = TrigSettings.PWLvlLow;
                PwLevel_orig.lo_deci_index = deci_index[time_index];

                groupBox5.ForeColor = Color.Black;
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private int checkForActiveChanel() // priorly returns chsnel with smaller number
        {
            if (labelCH1.BackColor == Color.Fuchsia)
                return 1;

            if (labelCH2.BackColor == Color.Lime)
                return 2;

            if (labelCH3.BackColor == Color.Yellow)
                return 3;


            return 0;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void setActiveMenuChanel(int chanel)
        {

            switch (chanel)
            {
                case 0: cHxToolStripMenuItem.BackColor = Color.Transparent;
                    BarPosition.Enabled = false;
                    btnAmpM.Enabled = false;
                    btnAmpP.Enabled = false;

                    break;

                case 1: cHxToolStripMenuItem.BackColor = Color.Fuchsia;
                    panel2.BackColor = Color.Fuchsia;
                    panel3.BackColor = Color.Fuchsia;
                    BarPosition.Enabled = true;
                    btnAmpM.Enabled = true;
                    btnAmpP.Enabled = true;
                    BarPosition.Value = CH[1].Position / (4096 / 333);
                    labelAmp.Text = AmpLabels[CH[1].AmpLevel];
                    break;

                case 2: cHxToolStripMenuItem.BackColor = Color.Lime;
                    panel2.BackColor = Color.Lime;
                    panel3.BackColor = Color.Lime;
                    BarPosition.Enabled = true;
                    btnAmpM.Enabled = true;
                    btnAmpP.Enabled = true;
                    BarPosition.Value = CH[2].Position / (4096 / 333);
                    labelAmp.Text = AmpLabels[CH[2].AmpLevel];
                    break;

                case 3: cHxToolStripMenuItem.BackColor = Color.Yellow;
                    panel2.BackColor = Color.Yellow;
                    panel3.BackColor = Color.Yellow;
                    BarPosition.Enabled = true;
                    btnAmpM.Enabled = true;
                    btnAmpP.Enabled = true;
                    BarPosition.Value = CH[3].Position / (4096 / 333);
                    labelAmp.Text = AmpLabels[CH[3].AmpLevel];
                    break;

            }

            setMenuChanelLabel();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void setMenuChanelLabel()
        {
            if (cHxToolStripMenuItem.BackColor == Color.Fuchsia)
            {
                cHxToolStripMenuItem.Text = "CH1 settings";
                cHxToolStripMenuItem.Enabled = true;

                aCToolStripMenuItem.Checked = (CH[1].Coupling == Mode_Coupling.DC) ? false : true;
                dCToolStripMenuItem.Checked = (CH[1].Coupling == Mode_Coupling.DC) ? true : false;

                toolStrip1_1MenuItem.Checked = (CH[1].Probe == 10) ? false : true;
                toolStrip1_10MenuItem.Checked = (CH[1].Probe == 1) ? false : true;


            }
            else if (cHxToolStripMenuItem.BackColor == Color.Lime)
            {
                cHxToolStripMenuItem.Text = "CH2 settings";
                cHxToolStripMenuItem.Enabled = true;

                aCToolStripMenuItem.Checked = (CH[2].Coupling == Mode_Coupling.DC) ? false : true;
                dCToolStripMenuItem.Checked = (CH[2].Coupling == Mode_Coupling.DC) ? true : false;

                toolStrip1_1MenuItem.Checked = (CH[2].Probe == 10) ? false : true;
                toolStrip1_10MenuItem.Checked = (CH[2].Probe == 1) ? false : true;
            }
            else if (cHxToolStripMenuItem.BackColor == Color.Yellow)
            {
                cHxToolStripMenuItem.Text = "CH3 settings";
                cHxToolStripMenuItem.Enabled = true;

                aCToolStripMenuItem.Checked = (CH[3].Coupling == Mode_Coupling.DC) ? false : true;
                dCToolStripMenuItem.Checked = (CH[3].Coupling == Mode_Coupling.DC) ? true : false;

                toolStrip1_1MenuItem.Checked = (CH[3].Probe == 10) ? false : true;
                toolStrip1_10MenuItem.Checked = (CH[3].Probe == 1) ? false : true;
            }
            else
            {
                cHxToolStripMenuItem.Text = "CHx settings";
                cHxToolStripMenuItem.Enabled = false;
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void labelCH1_DoubleClick(object sender, EventArgs e)
        {
            if (labelCH1.BackColor == Color.Fuchsia)
            {
                labelCH1.BackColor = Color.WhiteSmoke;
                panel2.BackColor = Color.WhiteSmoke;
                panel3.BackColor = Color.WhiteSmoke;
                setActiveMenuChanel(checkForActiveChanel());
            }
            else
            {
                labelCH1.BackColor = Color.Fuchsia;
                panel2.BackColor = Color.Fuchsia;
                panel3.BackColor = Color.Fuchsia;
                cHxToolStripMenuItem.BackColor = Color.Fuchsia;
                setMenuChanelLabel();


                BarPosition.Enabled = true;
                btnAmpM.Enabled = true;
                btnAmpP.Enabled = true;
                labelAmp.Text = AmpLabels[CH[1].AmpLevel];
                // BarPosition.Value = CH[1].Position;

                double szorzo = ((ShiftLevelsMax[CH[1].AmpLevel] - ShiftLevelsMin[CH[1].AmpLevel]) / 333.0);
                BarPosition.Value = (int)((CH[1].Position - ShiftLevelsMin[CH[1].AmpLevel]) / szorzo);
            }

            snedLoggerSettings(); // changing chanel update led
          
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void labelCH2_DoubleClick(object sender, EventArgs e)
        {
            if (labelCH2.BackColor == Color.Lime)
            {
                labelCH2.BackColor = Color.WhiteSmoke;
                panel2.BackColor = Color.WhiteSmoke;
                panel3.BackColor = Color.WhiteSmoke;
                setActiveMenuChanel(checkForActiveChanel());
            }
            else
            {
                labelCH2.BackColor = Color.Lime;
                panel2.BackColor = Color.Lime;
                panel3.BackColor = Color.Lime;
                cHxToolStripMenuItem.BackColor = Color.Lime;
                setMenuChanelLabel();



                BarPosition.Enabled = true;
                btnAmpM.Enabled = true;
                btnAmpP.Enabled = true;
                labelAmp.Text = AmpLabels[CH[2].AmpLevel];
                // BarPosition.Value = CH[2].Position;

                double szorzo = ((ShiftLevelsMax[CH[2].AmpLevel] - ShiftLevelsMin[CH[2].AmpLevel]) / 333.0);
                BarPosition.Value = (int)((CH[2].Position - ShiftLevelsMin[CH[2].AmpLevel]) / szorzo);
            }
      
            snedLoggerSettings(); // changing chanel update led
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void labelCH3_DoubleClick(object sender, EventArgs e)
        {
            if (labelCH3.BackColor == Color.Yellow)
            {
                labelCH3.BackColor = Color.WhiteSmoke;
                panel2.BackColor = Color.WhiteSmoke;
                panel3.BackColor = Color.WhiteSmoke;
                setActiveMenuChanel(checkForActiveChanel());


            }
            else
            {
                labelCH3.BackColor = Color.Yellow;
                panel2.BackColor = Color.Yellow;
                panel3.BackColor = Color.Yellow;
                cHxToolStripMenuItem.BackColor = Color.Yellow;
                setMenuChanelLabel();



                BarPosition.Enabled = true;
                btnAmpM.Enabled = true;
                btnAmpP.Enabled = true;
                labelAmp.Text = AmpLabels[CH[3].AmpLevel];
                // BarPosition.Value = CH[3].Position;

                double szorzo = ((ShiftLevelsMax[CH[3].AmpLevel] - ShiftLevelsMin[CH[3].AmpLevel]) / 333.0);
                BarPosition.Value = (int)((CH[3].Position - ShiftLevelsMin[CH[3].AmpLevel]) / szorzo);
            }

            snedLoggerSettings(); // changing chanel update led
         
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void labelDigi_DoubleClick(object sender, EventArgs e)
        {
            if (labelDigi.BackColor == Color.Cyan)
            {
                labelDigi.BackColor = Color.WhiteSmoke;
                panel2.BackColor = Color.WhiteSmoke;
                panel3.BackColor = Color.WhiteSmoke;
                digiSettingsToolStripMenuItem.BackColor = Color.WhiteSmoke;
                digiSettingsToolStripMenuItem.Enabled = false;

                BarPosition.Enabled = false;
                btnAmpM.Enabled = false;
                btnAmpP.Enabled = false;


                comboBoxChanel.Items.Remove("DIGI0");
                comboBoxChanel.Items.Remove("DIGI1");
                comboBoxChanel.Items.Remove("DIGI2");
                comboBoxChanel.Items.Remove("DIGI3");
                comboBoxChanel.Items.Remove("DIGI4");
                comboBoxChanel.Items.Remove("DIGI5");
                comboBoxChanel.Items.Remove("DIGI6");
                comboBoxChanel.Items.Remove("DIGI7");

                if (comboBoxChanel.SelectedIndex < 0)
                    comboBoxChanel.SelectedIndex = 0;

                setActiveMenuChanel(checkForActiveChanel());

            }
            else
            {
                labelDigi.BackColor = Color.Cyan;
                panel2.BackColor = Color.WhiteSmoke;
                panel3.BackColor = Color.WhiteSmoke;
                digiSettingsToolStripMenuItem.BackColor = Color.Cyan;
                digiSettingsToolStripMenuItem.Enabled = true;


                BarPosition.Enabled = false;
                btnAmpM.Enabled = false;
                btnAmpP.Enabled = false;

                comboBoxChanel.Items.Add("DIGI0");
                comboBoxChanel.Items.Add("DIGI1");
                comboBoxChanel.Items.Add("DIGI2");
                comboBoxChanel.Items.Add("DIGI3");
                comboBoxChanel.Items.Add("DIGI4");
                comboBoxChanel.Items.Add("DIGI5");
                comboBoxChanel.Items.Add("DIGI6");
                comboBoxChanel.Items.Add("DIGI7");


            }

            snedLoggerSettings(); // changing chanel update led
           
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void labelCH1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //normal click
            {
                if (labelCH1.BackColor == Color.Fuchsia) // if active chanel, settings enabled
                {
                    BarPosition.Enabled = true;
                    btnAmpM.Enabled = true;
                    btnAmpP.Enabled = true;

                    panel2.BackColor = Color.Fuchsia;
                    panel3.BackColor = Color.Fuchsia;
                    cHxToolStripMenuItem.BackColor = Color.Fuchsia;
                    setMenuChanelLabel();

                    labelAmp.Text = AmpLabels[CH[1].AmpLevel];
                    double szorzo = ((ShiftLevelsMax[CH[1].AmpLevel] - ShiftLevelsMin[CH[1].AmpLevel]) / 333.0);
                    BarPosition.Value = (int)((CH[1].Position - ShiftLevelsMin[CH[1].AmpLevel]) / szorzo);

                }
                else
                {
                    BarPosition.Enabled = false;
                    btnAmpM.Enabled = false;
                    btnAmpP.Enabled = false;
                    panel2.BackColor = Color.WhiteSmoke;
                    panel3.BackColor = Color.WhiteSmoke;
                    setActiveMenuChanel(checkForActiveChanel());
                }

            }
            else // right click
            {

            }

            snedLoggerSettings(); // changing chanel update led
       
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void labelCH2_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //normal click
            {
                if (labelCH2.BackColor == Color.Lime) // if active chanel, settings enabled
                {
                    BarPosition.Enabled = true;
                    btnAmpM.Enabled = true;
                    btnAmpP.Enabled = true;

                    panel2.BackColor = Color.Lime;
                    panel3.BackColor = Color.Lime;
                    cHxToolStripMenuItem.BackColor = Color.Lime;
                    setMenuChanelLabel();


                    labelAmp.Text = AmpLabels[CH[2].AmpLevel];
                    double szorzo = ((ShiftLevelsMax[CH[2].AmpLevel] - ShiftLevelsMin[CH[2].AmpLevel]) / 333.0);
                    BarPosition.Value = (int)((CH[2].Position - ShiftLevelsMin[CH[2].AmpLevel]) / szorzo);
                }
                else
                {
                    BarPosition.Enabled = false;
                    btnAmpM.Enabled = false;
                    btnAmpP.Enabled = false;
                    panel2.BackColor = Color.WhiteSmoke;
                    panel3.BackColor = Color.WhiteSmoke;
                    setActiveMenuChanel(checkForActiveChanel());
                }

            }
            else // right click
            {

            }

            snedLoggerSettings(); // changing chanel update led
          
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void labelCH3_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //normal click
            {
                if (labelCH3.BackColor == Color.Yellow) // if active chanel, settings enabled
                {
                    BarPosition.Enabled = true;
                    btnAmpM.Enabled = true;
                    btnAmpP.Enabled = true;

                    panel2.BackColor = Color.Yellow;
                    panel3.BackColor = Color.Yellow;
                    cHxToolStripMenuItem.BackColor = Color.Yellow;
                    setMenuChanelLabel();


                    labelAmp.Text = AmpLabels[CH[3].AmpLevel];
                    double szorzo = ((ShiftLevelsMax[CH[3].AmpLevel] - ShiftLevelsMin[CH[3].AmpLevel]) / 333.0);
                    BarPosition.Value = (int)((CH[3].Position - ShiftLevelsMin[CH[3].AmpLevel]) / szorzo);
                }
                else
                {
                    BarPosition.Enabled = false;
                    btnAmpM.Enabled = false;
                    btnAmpP.Enabled = false;
                    panel2.BackColor = Color.WhiteSmoke;
                    panel3.BackColor = Color.WhiteSmoke;
                    setActiveMenuChanel(checkForActiveChanel());
                }

            }
            else // right click
            {

            }

            snedLoggerSettings(); // changing chanel update led
           
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void labelDigi_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //normal click
            {
                if (labelDigi.BackColor == Color.Cyan) // if active chanel, settings enabled
                {
                    BarPosition.Enabled = false;
                    btnAmpM.Enabled = false;
                    btnAmpP.Enabled = false;

                    panel2.BackColor = Color.WhiteSmoke;
                    panel3.BackColor = Color.WhiteSmoke;

                }
                else
                {
                    BarPosition.Enabled = false;
                    btnAmpM.Enabled = false;
                    btnAmpP.Enabled = false;

                    panel2.BackColor = Color.WhiteSmoke;
                    panel3.BackColor = Color.WhiteSmoke;

                }
            }
            else // right click
            {

            }

            snedLoggerSettings(); // changing chanel update led
       
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void BarPosition_Scroll(object sender, EventArgs e)
        {
        
          //  timeout = 10; // for autotrigger

            if (panel2.BackColor == Color.Fuchsia)
            {

                double szorzo = ((ShiftLevelsMax[CH[1].AmpLevel] - ShiftLevelsMin[CH[1].AmpLevel]) / 333.0);

                CH[1].Position = (int)(BarPosition.Value * szorzo + ShiftLevelsMin[CH[1].AmpLevel]);

                label15.Text = "" + CH[1].Position;
                label16.Text = "" + BarPosition.Value;
             
                snedLoggerSettings();
           
            }

            if (panel2.BackColor == Color.Lime)
            {
                double szorzo = ((ShiftLevelsMax[CH[2].AmpLevel] - ShiftLevelsMin[CH[2].AmpLevel]) / 333.0);

                CH[2].Position = (int)(BarPosition.Value * szorzo + ShiftLevelsMin[CH[2].AmpLevel]);

                label15.Text = "" + CH[2].Position;
                label16.Text = "" + BarPosition.Value;

                snedLoggerSettings();
                
            }

            if (panel2.BackColor == Color.Yellow)
            {
                double szorzo = ((ShiftLevelsMax[CH[3].AmpLevel] - ShiftLevelsMin[CH[3].AmpLevel]) / 333.0);

                CH[3].Position = (int)(BarPosition.Value * szorzo + ShiftLevelsMin[CH[3].AmpLevel]);

                label15.Text = "" + CH[3].Position;
                label16.Text = "" + BarPosition.Value;

                snedLoggerSettings();
           
            }


           // lastTrigTime = DateTime.Now;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnEdge_Click(object sender, EventArgs e)
        {
            btnEdge.BackColor = Color.GreenYellow;
            btnPulseW.BackColor = Color.Transparent;
            btnPattern.BackColor = Color.Transparent;

            TrigSettings.TrigType = Type_Trigger.Edge;

            groupBox1.Visible = true;
            groupBox2.Visible = true;
            groupBox3.Visible = false;
            groupBox4.Visible = false;
            groupBox5.Visible = false;

            groupPattern1.Visible = false;
            groupPattern2.Visible = false;

            groupBox2.Text = "Slope";

            if (TrigSettings.EdgeSlope == Mode_EdgeSlope.Rising)
                pictureBox2.Image = Properties.Resources.rising;
            else
                pictureBox2.Image = Properties.Resources.falling;

            comboBoxChanel_IndexChanged(null, null);
            snedLoggerSettings();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnPattern_Click(object sender, EventArgs e)
        {
            btnEdge.BackColor = Color.Transparent;
            btnPulseW.BackColor = Color.Transparent;
            btnPattern.BackColor = Color.GreenYellow;

            TrigSettings.TrigType = Type_Trigger.Pattern;

            groupBox1.Visible = false;
            groupBox2.Visible = false;
            groupBox3.Visible = false;
            groupBox4.Visible = false;
            groupBox5.Visible = false;

            groupPattern1.Visible = true;
            groupPattern2.Visible = true;

            comboBoxPattern_SelectedIndexChanged(comboBoxA1, null);
            comboBoxPattern_SelectedIndexChanged(comboBoxA2, null);
            comboBoxPattern_SelectedIndexChanged(comboBoxA3, null);

            comboBoxPattern_SelectedIndexChanged(comboBoxD0, null);
            comboBoxPattern_SelectedIndexChanged(comboBoxD1, null);
            comboBoxPattern_SelectedIndexChanged(comboBoxD2, null);
            comboBoxPattern_SelectedIndexChanged(comboBoxD3, null);

            comboBoxPattern_SelectedIndexChanged(comboBoxD4, null);
            comboBoxPattern_SelectedIndexChanged(comboBoxD5, null);
            comboBoxPattern_SelectedIndexChanged(comboBoxD6, null);
            comboBoxPattern_SelectedIndexChanged(comboBoxD7, null);

            snedLoggerSettings();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnPulseW_Click(object sender, EventArgs e)
        {
            btnEdge.BackColor = Color.Transparent;
            btnPulseW.BackColor = Color.GreenYellow;
            btnPattern.BackColor = Color.Transparent;

            TrigSettings.TrigType = Type_Trigger.PulseW;

            groupBox1.Visible = true;
            groupBox2.Visible = true;
            groupBox3.Visible = true;
            groupBox4.Visible = true;
            groupBox5.Visible = true;

            groupPattern1.Visible = false;
            groupPattern2.Visible = false;

            groupBox2.Text = "Type";

            if (TrigSettings.PulseWType == Type_PW.Pos)
                pictureBox2.Image = Properties.Resources.pospulse;
            else
                pictureBox2.Image = Properties.Resources.negpulse;

            comboBoxChanel_IndexChanged(null, null);
            snedLoggerSettings();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnRunStop_Click(object sender, EventArgs e)
        {
            if (btnRunStop.BackColor == Color.GreenYellow) // stopping
            {
                btnRunStop.BackColor = Color.OrangeRed;
                // the listen thread tests the color of this button. 
                //so there is no need to explicitly end the thread.
            }
            else //starting
            {
                btnRunStop.BackColor = Color.GreenYellow;

                lastTrigTime = DateTime.Now;
                //delta = TimeSpan.Zero;

                tListen = new Thread(new ThreadStart(ListenThread));
                tListen.IsBackground = true;
                tListen.Priority = ThreadPriority.Highest;
                tListen.Start();
            }

            btnSingle.BackColor = Color.Transparent;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnSingle_Click(object sender, EventArgs e)
        {

            if (tListen.IsAlive == false) // if data gathering is stopped, start it
            {
                tListen = new Thread(new ThreadStart(ListenThread));
                tListen.IsBackground = true;
                tListen.Priority = ThreadPriority.Highest;
                tListen.Start();
            }


            btnRunStop.BackColor = Color.Transparent;
            btnSingle.BackColor = Color.Gold;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnAuto_Click(object sender, EventArgs e)
        {
            btnAuto.BackColor = Color.GreenYellow;
            btnNormal.BackColor = Color.Transparent;

            triggerMode = Mode_Trigger.Auto;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void btnNormal_Click(object sender, EventArgs e)
        {
            btnAuto.BackColor = Color.Transparent;
            btnNormal.BackColor = Color.GreenYellow;

            triggerMode = Mode_Trigger.Normal;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void BarTrigLevel_Scroll(object sender, EventArgs e)
        {
           // timeout = 10; // for autotrigger
            trigLvl = (byte)(255 - BarTrigLevel.Value);
           // lastTrigTime = DateTime.Now;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void pictureBox2_Click(object sender, EventArgs e)
        {

            if (btnEdge.BackColor == Color.GreenYellow)
            {

                if (TrigSettings.EdgeSlope == Mode_EdgeSlope.Rising)
                {
                    pictureBox2.Image = Properties.Resources.falling;
                    TrigSettings.EdgeSlope = Mode_EdgeSlope.Falling;
                }
                else if (TrigSettings.EdgeSlope == Mode_EdgeSlope.Falling)
                {
                    pictureBox2.Image = Properties.Resources.both;
                    TrigSettings.EdgeSlope = Mode_EdgeSlope.Both;
                }
                else
                {
                    pictureBox2.Image = Properties.Resources.rising;
                    TrigSettings.EdgeSlope = Mode_EdgeSlope.Rising;
                }
            }
            else if (btnPulseW.BackColor == Color.GreenYellow)
            {

                if (TrigSettings.PulseWType == Type_PW.Pos)
                {
                    pictureBox2.Image = Properties.Resources.negpulse;
                    TrigSettings.PulseWType = Type_PW.Neg;
                }
                else
                {
                    pictureBox2.Image = Properties.Resources.pospulse;
                    TrigSettings.PulseWType = Type_PW.Pos;
                }
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void comboBoxChanel_IndexChanged(object sender, EventArgs e)
        {

            if ((comboBoxChanel.SelectedIndex >= 0) && (comboBoxChanel.SelectedIndex <= 2))
            {

                TrigSettings.TrigOnCH = (byte)(comboBoxChanel.SelectedIndex + 1); // ch1 = 1 ...
            }
            else
            {
                TrigSettings.TrigOnCH = (byte)(comboBoxChanel.SelectedIndex + 1 - 4 + 0xD0); // refer to D as digi
            }                                               // D0 D1 ...D7


            snedLoggerSettings(); // changing trig update led
           
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void pictureBox3_Click(object sender, EventArgs e)
        {
            if (TrigSettings.PulseWMode == Mode_PW.More)
            {
                pictureBox3.Image = Properties.Resources.less;
                TrigSettings.PulseWMode = Mode_PW.Less;

                groupBox4.Enabled = false;
                groupBox5.Enabled = true;



            }
            else if (TrigSettings.PulseWMode == Mode_PW.Less)
            {
                pictureBox3.Image = Properties.Resources.interval;
                TrigSettings.PulseWMode = Mode_PW.Between;

                groupBox4.Enabled = true;
                groupBox5.Enabled = true;


                comboSmallr_SelectedIndexChanged(null, e);
                comboBigr_SelectedIndexChanged(null, e);



            }
            else
            {
                pictureBox3.Image = Properties.Resources.more;
                TrigSettings.PulseWMode = Mode_PW.More;

                groupBox4.Enabled = true;
                groupBox5.Enabled = false;


            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private int boolToInt(bool input)
        {
            if (input)
                return 1;
            else
                return 0;
        }
        //-------------------------------------------------------------------------------------------------------------------
        //-----------------------------------------timers--------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------------------------
        private void timerDraw_Tick(object sender, EventArgs e)
        {

       
            if (isLoggerRunning) // saving check
            {
                 if ((trigfound == true) && (canDrawNow))
                 {

                     byte activeChanels = (byte)((boolToInt(isCh4Active) << 6) +
                         (boolToInt(isCh3Active) << 4) +
                         (boolToInt(isCh2Active) << 2) +
                         boolToInt(isCh1Active));


                    int ch1_offs = (((int)(2.75 * ((CH[1].Position - 2048) *
                                   ((double)picMainscreen.Size.Height / ((double)ShiftLevelsMax[CH[1].AmpLevel] - (double)ShiftLevelsMin[CH[1].AmpLevel]))))));
                                                                         
                     
                    int ch2_offs = (((int)(2.55 * ((CH[2].Position - 2048) *
                                     ((double)picMainscreen.Size.Height / ((double)ShiftLevelsMax[CH[2].AmpLevel] - (double)ShiftLevelsMin[CH[2].AmpLevel]))))));


                    int ch3_offs = (((int)(2.53 * ((CH[3].Position - 2048) *
                                    ((double)picMainscreen.Size.Height / ((double)ShiftLevelsMax[CH[3].AmpLevel] - (double)ShiftLevelsMin[CH[3].AmpLevel]))))));



                     if (circBufferFilled)
                         FileTransactions.ToFile(activeChanels, logBuffLen, logBuffWrPtr, 
                             (int)Math.Pow(10, toolStripPostTrig.SelectedIndex + 1), "", toolStripDeciFaktor.SelectedIndex+1,
                             CH[1].AmpLevel, CH[2].AmpLevel, CH[3].AmpLevel,
                             ch1_offs, ch2_offs, ch3_offs,
                             (char)CH[1].Coupling, (char)CH[2].Coupling, (char)CH[3].Coupling,
                             CH1_logbuff, CH2_logbuff, CH3_logbuff, CH4_logbuff);


                     else
                        FileTransactions.ToFile(activeChanels, logBuffWrPtr, logBuffWrPtr,
                             (int)Math.Pow(10, toolStripPostTrig.SelectedIndex + 1), "", toolStripDeciFaktor.SelectedIndex + 1,
                             CH[1].AmpLevel, CH[2].AmpLevel, CH[3].AmpLevel,
                             ch1_offs, ch2_offs, ch3_offs,
                             (char)CH[1].Coupling, (char)CH[2].Coupling, (char)CH[3].Coupling,
                             CH1_logbuff, CH2_logbuff, CH3_logbuff, CH4_logbuff);


                     canDrawNow = false;
                     trigfound = false;
                     trigfound_fall = false;
                     trigfound_rise = false;
                     trigfound_fall_hyst = false;
                     trigfound_rise_hyst = false;

                     postTrigCntr = 0;
                     logBuffWrPtr = 0;

                     labelLOG5.Text = "" + ++TrigsFound;

                     snedLoggerSettings();
                     


                     circBufferFilled = false;
                     postTrigFull = false;
                  
            
                     tListen = new Thread(new ThreadStart(ListenThread));
                     tListen.IsBackground = true;
                     tListen.Priority = ThreadPriority.Highest;
                     tListen.Start();
                 }
            }
            else
            {
                TimeSpan delta = DateTime.Now - lastTrigTime;
                //   const int timeout = 1200; //in milisec


                // if no trig found and timeout, then draw the buff as it is
                if ((delta.TotalMilliseconds >= timeout) && (triggerMode == Mode_Trigger.Auto) && (takenSampleNum>800))
                {
                    // draw from the current position to avoid glitches by circ buffer
                    current_pos = CHx_mainbuff_cntr - CHx_mainbuff_size / 2;
                    trigtimeout = true;
                    timeout = 1200;
                }


                


                if (((trigfound == true) && (canDrawNow)) || ((trigtimeout == true) && (canDrawNow)))
                {

                    if (trigfound == true)
                    {
                        lastTrigTime = DateTime.Now;
                        // delta = TimeSpan.Zero;

                        if (btnSingle.BackColor == Color.Gold)
                        {
                            btnSingle.BackColor = Color.Transparent;
                            btnRunStop.BackColor = Color.OrangeRed;
                        }
                    }

            

                    this.picMainscreen.Refresh();
                    this.picSidescreen.Refresh();


                    trigtimeout = false;

                    canDrawNow = false;
                    trigfound = false;
                    trigfound_fall = false;
                    trigfound_rise = false;
                    trigfound_fall_hyst = false;
                    trigfound_rise_hyst = false;

                    //radioButton1.Checked = isBtnPressed;

                    if ((btnRunStop.BackColor == Color.GreenYellow) || (btnSingle.BackColor == Color.Gold))
                    {
                        tListen = new Thread(new ThreadStart(ListenThread));
                        tListen.IsBackground = true;
                        tListen.Priority = ThreadPriority.Highest;
                        tListen.Start();
                    }

                    label9.Text = "samples: " + PWcount;
                    label10.Text = "time: " + (PWcount / 5.333333333333e6).ToEngineering();
                    label11.Text = "freq: " + 1.0 / (PWcount / 5.333333333333e6);

                    PWcount = 0; // important to not to delete, to catch the first edge in PW mode
                    // not to falsly trigger only to second edge if PW count is not 0

                }
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        //----------------------------------------------graphics-------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------------------------
        private void picSidescreen_Paint(object sender, PaintEventArgs e) // sidepanel
        {

            Pen pen = new Pen(Color.Fuchsia);
            Font SignFont = new Font("Courier New", 13, FontStyle.Bold);
            Font DigiChanelNumFont = new Font("Courier New", 9, FontStyle.Regular);


            if (labelDigi.BackColor == Color.Cyan)
            {
                if (showD0D3ToolStripMenuItem.Checked == false)
                {
                    e.Graphics.DrawString("7", DigiChanelNumFont, Brushes.Cyan, new Point(-1, 42 * 1 - 20));
                    e.Graphics.DrawString("6", DigiChanelNumFont, Brushes.Cyan, new Point(-1, 42 * 2 - 20));
                    e.Graphics.DrawString("5", DigiChanelNumFont, Brushes.Cyan, new Point(-1, 42 * 3 - 20));
                    e.Graphics.DrawString("4", DigiChanelNumFont, Brushes.Cyan, new Point(-1, 42 * 4 - 20));
                }

                if (showD4D7ToolStripMenuItem.Checked == false)
                {
                    e.Graphics.DrawString("3", DigiChanelNumFont, Brushes.Cyan, new Point(-1, 42 * 5 - 20));
                    e.Graphics.DrawString("2", DigiChanelNumFont, Brushes.Cyan, new Point(-1, 42 * 6 - 20));
                    e.Graphics.DrawString("1", DigiChanelNumFont, Brushes.Cyan, new Point(-1, 42 * 7 - 20));
                    e.Graphics.DrawString("0", DigiChanelNumFont, Brushes.Cyan, new Point(-1, 42 * 8 - 20));
                }
            }


            if (labelCH1.BackColor == Color.Fuchsia)
            {

                e.Graphics.DrawString(">", SignFont, Brushes.Fuchsia, new Point(-5, 336 - 11 - ((int)(2.75 * ((CH[1].Position - 2048) *
                                                                            ((double)picMainscreen.Size.Height / ((double)ShiftLevelsMax[CH[1].AmpLevel] - (double)ShiftLevelsMin[CH[1].AmpLevel])))
                                                                             + 168))));
            }


            if (labelCH2.BackColor == Color.Lime)
            {
                e.Graphics.DrawString(">", SignFont, Brushes.Lime, new Point(-5, 336 - 11 - ((int)(2.55 * ((CH[2].Position - 2048) *
                                                                           ((double)picMainscreen.Size.Height / ((double)ShiftLevelsMax[CH[2].AmpLevel] - (double)ShiftLevelsMin[CH[2].AmpLevel])))
                                                                            + 168))));
            }

            if (labelCH3.BackColor == Color.Yellow)
            {
                e.Graphics.DrawString(">", SignFont, Brushes.Yellow, new Point(-5, 336 - 11 - ((int)(2.53 * ((CH[3].Position - 2048) *
                                                                           ((double)picMainscreen.Size.Height / ((double)ShiftLevelsMax[CH[3].AmpLevel] - (double)ShiftLevelsMin[CH[3].AmpLevel])))
                                                                            + 168))));
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void picMainscreen_Paint(object sender, PaintEventArgs e) //mainscreen
        {
            //e.DrawLShapeLine(e.Graphics, 10, 10, 20, 40);
            int n = 0;
            int k, offset;
            int from = 4, to = 4;

            Pen pen = new Pen(Color.DimGray);
            SolidBrush brush = new SolidBrush(Color.DarkBlue);



            Random rnd = new Random();

            Point[] pnts = new Point[533]; // pointst of chanels


            Point[][] digix = new Point[8][];
            digix[0] = new Point[533];
            digix[1] = new Point[533];
            digix[2] = new Point[533];
            digix[3] = new Point[533];
            digix[4] = new Point[533];
            digix[5] = new Point[533];
            digix[6] = new Point[533];
            digix[7] = new Point[533];


            byte[] Digi = new byte[8];
            byte Digibuff = 0;
            int buff1, buff2;

            // 533 point makes the screen 100us long 10*10us 
            // 48 / 9 = 5.3333333 -> 187.5ns ; 100us /  187.5ns = 533.33333 dot / screen

            double Canvas_Width_param1 = picMainscreen.Size.Width / 10.0;
            int Canvas_Height_param1 = picMainscreen.Size.Height + 1;

            int Canvas_Width_param2 = picMainscreen.Size.Width + 1;
            double Canvas_Height_param2 = picMainscreen.Size.Height / 8.0;

            double coeff = picMainscreen.Size.Width / 533.0;


            Rectangle[] grid = new Rectangle[]  
            {
                // x,y,width height   // float is needed for a better accuracy of lines
            new Rectangle(-1,                             -1, (int)Canvas_Width_param1, Canvas_Height_param1),   
            new Rectangle((int)(Canvas_Width_param1*2.0), -1, (int)Canvas_Width_param1, Canvas_Height_param1), 
            new Rectangle((int)(Canvas_Width_param1*4.0), -1, (int)Canvas_Width_param1, Canvas_Height_param1), 
            new Rectangle((int)(Canvas_Width_param1*6.0), -1, (int)Canvas_Width_param1, Canvas_Height_param1), 
            new Rectangle((int)(Canvas_Width_param1*8.0), -1, (int)Canvas_Width_param1, Canvas_Height_param1), 

            new Rectangle(-1, -1, Canvas_Width_param2, (int)Canvas_Height_param2), 
            new Rectangle(-1, (int)(Canvas_Height_param2*2.0), Canvas_Width_param2, (int)Canvas_Height_param2), 
            new Rectangle(-1, (int)(Canvas_Height_param2*4.0), Canvas_Width_param2, (int)Canvas_Height_param2), 
            new Rectangle(-1, (int)(Canvas_Height_param2*6.0), Canvas_Width_param2, (int)Canvas_Height_param2), 
            };

            e.Graphics.DrawRectangles(pen, grid);



            Rectangle[] gridcentr = new Rectangle[]  
            {
                // x,y,width height   // float is needed for a better accuracy of lines
            new Rectangle(-1,                             -1, (int)(Canvas_Width_param1*5.0), Canvas_Height_param1), 
            new Rectangle(-1, -1, Canvas_Width_param2, (int)(Canvas_Height_param2*4.0)), 
           
        
            };
            pen.Color = Color.Olive;
            e.Graphics.DrawRectangles(pen, gridcentr);



            if (labelDigi.BackColor == Color.Cyan)
            {

                for (n = 0; n < 533; n++)
                {

                    Digibuff = (byte)(~(getItemCHx_mainbuff(4, (int)(current_pos + (-532 + 266 + n * intp_index[time_index] + 266.666 * (1 - intp_index[time_index]))))));
                    Digi[0] = (byte)(Digibuff & 0x01);
                    Digi[1] = (byte)((Digibuff & 0x02) >> 1);
                    Digi[2] = (byte)((Digibuff & 0x04) >> 2);
                    Digi[3] = (byte)((Digibuff & 0x08) >> 3);
                    Digi[4] = (byte)((Digibuff & 0x10) >> 4);
                    Digi[5] = (byte)((Digibuff & 0x20) >> 5);
                    Digi[6] = (byte)((Digibuff & 0x40) >> 6);
                    Digi[7] = (byte)((Digibuff & 0x80) >> 7);


                    //creating main curve dots as separate lines to screen

                    for (k = 0; k < 8; k++)
                    {
                        digix[k][n].X = (int)((n + 1) * coeff);
                        digix[k][n].Y = (int)((picMainscreen.Size.Height / 8.0 * (7 - k + 0.15)) + // positioning to the half of the screen
                                          (picMainscreen.Size.Height / 10.0) * //  amplitude compensation of the screen
                                          (Digi[k])); // data compensated to sign
                    }
                }




                //creating fill of digichanels, and drawing
                pen.Color = Color.DarkBlue;



                if (showD4D7ToolStripMenuItem.Checked == false)
                {
                    from = 0; //else it is deafultly 4
                }

                if (showD0D3ToolStripMenuItem.Checked == false)
                {
                    to = 8; //else it is deafultly 4
                }


                for (k = from; k < to; k++)
                {
                    offset = (int)((picMainscreen.Size.Height / 8.0 * (7 - k + 0.15)) + (picMainscreen.Size.Height / 10.0));

                    buff1 = digix[k][0].Y;
                    buff2 = digix[k][532].Y;

                    digix[k][0].Y = offset;
                    digix[k][532].Y = offset;

                    e.Graphics.FillPolygon(brush, digix[k]); //draawing

                    digix[k][0].Y = buff1;
                    digix[k][532].Y = buff2;
                }




                //drawing main curve
                pen.Color = Color.Cyan;
                if (showD4D7ToolStripMenuItem.Checked == false)
                {
                    e.Graphics.DrawCurve(pen, digix[0]);
                    e.Graphics.DrawCurve(pen, digix[1]);
                    e.Graphics.DrawCurve(pen, digix[2]);
                    e.Graphics.DrawCurve(pen, digix[3]);
                }

                if (showD0D3ToolStripMenuItem.Checked == false)
                {
                    e.Graphics.DrawCurve(pen, digix[4]);
                    e.Graphics.DrawCurve(pen, digix[5]);
                    e.Graphics.DrawCurve(pen, digix[6]);
                    e.Graphics.DrawCurve(pen, digix[7]);
                }
            }


            //------------------ch1----------------------------------------------------------------------
            if (labelCH1.BackColor == Color.Fuchsia)
            {
                pen.Color = Color.Fuchsia;
                if (intp_index[time_index] < 1.0) // interpolation needed
                {
                    byte[] origdata = new byte[533];
                    byte[] intpdata = new byte[533];


                    for (n = 0; n < 533; n++) //taking samples to work with
                        origdata[n] = getItemCHx_mainbuff(1, (int)(current_pos + (-532 + 266 + n)));
                    //- flip screen + center + sweep

                    Interpolator.Interpolate((int)(1.0 / intp_index[time_index]), origdata, intpdata);


                    for (n = 0; n < 533; n++) // drawing interpolated
                    {
                        pnts[n].X = (int)((n + 1) * coeff);
                        pnts[n].Y = (int)((picMainscreen.Size.Height / 2.0) + // positioning to the half of the screen
                                          (picMainscreen.Size.Height / 256.0) * //  amplitude compensation of the screen
                                          (intpdata[n] - 128));
                        //                                                

                        //drawing to desktop is shifted by 300 points and centered. current_pos is shifted in trigger

                    }
                }
                else // no interpolation
                {

                    for (n = 0; n < 533; n++)
                    {
                        pnts[n].X = (int)((n + 1) * coeff);
                        pnts[n].Y = (int)((picMainscreen.Size.Height / 2.0) + // positioning to the half of the screen
                                          (picMainscreen.Size.Height / 256.0) * //  amplitude compensation of the screen
                                          (getItemCHx_mainbuff(1, (int)(current_pos + (-532 + 266 + n))) - 128)); // data compensated to sign
                        //                                                   - flip screen + center + sweep

                        //drawing to desktop is shifted by 300 points and centered. current_pos is shifted in trigger

                    }
                }
                e.Graphics.DrawCurve(pen, pnts);
            }

            //------------------ch2----------------------------------------------------------------------

            if (labelCH2.BackColor == Color.Lime)
            {
                pen.Color = Color.Lime;


                if (intp_index[time_index] < 1.0) // interpolation needed
                {
                    byte[] origdata = new byte[533];
                    byte[] intpdata = new byte[533];


                    for (n = 0; n < 533; n++) //taking samples to work with
                        origdata[n] = getItemCHx_mainbuff(2, (int)(current_pos + (-532 + 266 + n)));
                    //- flip screen + center + sweep

                    Interpolator.Interpolate((int)(1.0 / intp_index[time_index]), origdata, intpdata);


                    for (n = 0; n < 533; n++) // drawing interpolated
                    {
                        pnts[n].X = (int)((n + 1) * coeff);
                        pnts[n].Y = (int)((picMainscreen.Size.Height / 2.0) + // positioning to the half of the screen
                                          (picMainscreen.Size.Height / 256.0) * //  amplitude compensation of the screen
                                          (intpdata[n] - 128));
                        //                                                

                        //drawing to desktop is shifted by 300 points and centered. current_pos is shifted in trigger

                    }
                }
                else // no interpolation
                {

                    for (n = 0; n < 533; n++)
                    {
                        pnts[n].X = (int)((n + 1) * coeff);
                        pnts[n].Y = (int)((picMainscreen.Size.Height / 2.0) + // positioning to the half of the screen
                                          (picMainscreen.Size.Height / 256.0) * //  amplitude compensation of the screen
                                          (getItemCHx_mainbuff(2, (int)(current_pos + (-532 + 266 + n))) - 128)); // data compensated to sign
                        //                                                   - flip screen + center + sweep

                        //drawing to desktop is shifted by 300 points and centered. current_pos is shifted in trigger

                    }
                }
                e.Graphics.DrawCurve(pen, pnts);
            }

            //------------------ch3----------------------------------------------------------------------

            if (labelCH3.BackColor == Color.Yellow)
            {
                pen.Color = Color.Yellow;


                if (intp_index[time_index] < 1.0) // interpolation needed
                {
                    byte[] origdata = new byte[533];
                    byte[] intpdata = new byte[533];


                    for (n = 0; n < 533; n++) //taking samples to work with
                        origdata[n] = getItemCHx_mainbuff(3, (int)(current_pos + (-532 + 266 + n)));
                    //- flip screen + center + sweep

                    Interpolator.Interpolate((int)(1.0 / intp_index[time_index]), origdata, intpdata);


                    for (n = 0; n < 533; n++) // drawing interpolated
                    {
                        pnts[n].X = (int)((n + 1) * coeff);
                        pnts[n].Y = (int)((picMainscreen.Size.Height / 2.0) + // positioning to the half of the screen
                                          (picMainscreen.Size.Height / 256.0) * //  amplitude compensation of the screen
                                          (intpdata[n] - 128));
                        //                                                

                        //drawing to desktop is shifted by 300 points and centered. current_pos is shifted in trigger

                    }
                }
                else // no interpolation
                {

                    for (n = 0; n < 533; n++)
                    {
                        pnts[n].X = (int)((n + 1) * coeff);
                        pnts[n].Y = (int)((picMainscreen.Size.Height / 2.0) + // positioning to the half of the screen
                                          (picMainscreen.Size.Height / 256.0) * //  amplitude compensation of the screen
                                          (getItemCHx_mainbuff(3, (int)(current_pos + (-532 + 266 + n))) - 128)); // data compensated to sign
                        //                                                   - flip screen + center + sweep

                        //drawing to desktop is shifted by 300 points and centered. current_pos is shifted in trigger

                    }
                }
                e.Graphics.DrawCurve(pen, pnts);
            }

         
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void button1_Click(object sender, EventArgs e)
        {
            int len = 512;
            byte[] buf = new byte[len];
            Random random = new Random();


            if (MyDevice == null) return;

            buf[0x0B] = (byte)textBox1.Text.ElementAt(0);
            buf[0x0C] = (byte)textBox1.Text.ElementAt(1);

            buf[0x10] = (byte)((AmpLevels[CH[1].AmpLevel] & 0xFF00) >> 8); // amplitudo ch1
            buf[0x11] = (byte)(AmpLevels[CH[1].AmpLevel] & 0x00FF);

            buf[0x0E] = (byte)((AmpLevels[CH[2].AmpLevel] & 0xFF00) >> 8); // amplitudo ch2
            buf[0x0F] = (byte)(AmpLevels[CH[2].AmpLevel] & 0x00FF);

            buf[0x12] = (byte)((AmpLevels[CH[3].AmpLevel] & 0xFF00) >> 8); // amplitudo ch3
            buf[0x13] = (byte)(AmpLevels[CH[3].AmpLevel] & 0x00FF);

            // chanels are compensated to offset 
            buf[0x16] = (byte)(((2037) & 0xFF00) >> 8); //offset ch2
            buf[0x17] = (byte)((2037) & 0x00FF);

            buf[0x18] = (byte)(((CH1_comp) & 0xFF00) >> 8);//offset ch1
            buf[0x19] = (byte)((CH1_comp) & 0x00FF);

            buf[0x14] = (byte)(((2039) & 0xFF00) >> 8);//offset ch3
            buf[0x15] = (byte)((2039) & 0x00FF);
         


            MyDevice.BulkOutEndPt.XferData(ref buf, ref len);

            textBox1.Text = Convert.ToString(random.Next(10, 99));
       

        }
        //-------------------------------------------------------------------------------------------------------------------
        private void snedLoggerSettings()
        {
            int len = 512;
            byte[] buf = new byte[len];

            byte control1=0, control2 = 0;

            if (MyDevice == null) return;

          //  buf[0x0B] = (byte)textBox1.Text.ElementAt(0); // display
          //  buf[0x0C] = (byte)textBox1.Text.ElementAt(1);

            if (TrigsFound < 100)
            {
                buf[0x0B] = (byte)((TrigsFound / 10) + 0x30);
                buf[0x0C] = (byte)((TrigsFound - ((TrigsFound / 10) * 10)) + 0x30); // display
            }
            else if (TrigsFound < 1000)
            {
                buf[0x0C] = (byte)(((TrigsFound / 100)) + 0x30);
                buf[0x0B] = 0x55; // display
            }
            else 
            {
                buf[0x0C] = 0x3A;
                buf[0x0B] = 0x3A; // display
            }


            if (btnPattern.BackColor != Color.GreenYellow)
            {
                if (labelCH1.BackColor == Color.Fuchsia)
                {
                    if (TrigSettings.TrigOnCH == 1)
                    {
                        control1 |= LEDR1;
                    }
                    else
                    {
                        control1 |= LEDG1;
                    }
                }

                if (labelCH2.BackColor == Color.Lime)
                {
                    if (TrigSettings.TrigOnCH == 2)
                    {
                        control1 |= LEDR2;
                    }
                    else
                    {
                        control1 |= LEDG2;
                    }
                }


                if (labelCH3.BackColor == Color.Yellow)
                {
                    if (TrigSettings.TrigOnCH == 3)
                    {
                        control2 |= LEDR3;
                    }
                    else
                    {
                        control2 |= LEDG3;
                    }
                }

                if (labelDigi.BackColor == Color.Cyan)
                {
                    if (TrigSettings.TrigOnCH >= 0xD0)
                    {
                        control2 |= LEDR_digi;
                    }
                    else
                    {
                        control2 |= LEDG_digi;
                    }
                }
            }
            else 
            {
                if (labelCH1.BackColor == Color.Fuchsia)
                {
                    if (Ptrn_set.CH1 != 0)
                    {
                        control1 |= LEDR1;
                    }
                    else
                    {
                        control1 |= LEDG1;
                    }
                }
                if (labelCH2.BackColor == Color.Lime)
                {
                    if (Ptrn_set.CH2 != 0)
                    {
                        control1 |= LEDR2;
                    }
                    else
                    {
                        control1 |= LEDG2;
                    }
                }


                if (labelCH3.BackColor == Color.Yellow)
                {
                    if (Ptrn_set.CH3 != 0)
                    {
                        control2 |= LEDR3;
                    }
                    else
                    {
                        control2 |= LEDG3;
                    }
                }

                if (labelDigi.BackColor == Color.Cyan)
                {
                    if ((Ptrn_set.D0 != 0) || (Ptrn_set.D1 != 0) || (Ptrn_set.D2 != 0) || (Ptrn_set.D3 != 0) ||
                        (Ptrn_set.D4 != 0) || (Ptrn_set.D5 != 0) || (Ptrn_set.D6 != 0) || (Ptrn_set.D7 != 0))
                    {
                        control2 |= LEDR_digi;
                    }
                    else
                    {
                        control2 |= LEDG_digi;
                    }
                }



            }



            if (CH[1].Coupling == Mode_Coupling.DC) control1 |= RELE1;
            if (CH[2].Coupling == Mode_Coupling.DC) control1 |= RELE2;
            if (CH[3].Coupling == Mode_Coupling.DC) control2 |= RELE3;

            if (isLoggerRunning == true) control2 |= Logging_LED;


            buf[0x09] = control2;
            buf[0x0A] = control1;

            //ch1 and 2 offsets are on one physical DAC
            //ch1 and 2 amplitudo are on one physical DAC 
            //ch 3 offset and amp are on separate physical DAC
          

            buf[0x10] = (byte)((AmpLevels[CH[1].AmpLevel] & 0xFF00) >> 8); // amplitudo ch1
            buf[0x11] = (byte)(AmpLevels[CH[1].AmpLevel] & 0x00FF);

            buf[0x0E] = (byte)((AmpLevels[CH[2].AmpLevel] & 0xFF00) >> 8); // amplitudo ch2
            buf[0x0F] = (byte)(AmpLevels[CH[2].AmpLevel] & 0x00FF);

            buf[0x12] = (byte)((AmpLevels[CH[3].AmpLevel] & 0xFF00) >> 8); // amplitudo ch3
            buf[0x13] = (byte)(AmpLevels[CH[3].AmpLevel] & 0x00FF);

            // chanels are compensated to offset 
            buf[0x16] = (byte)(((4085 - CH[2].Position) & 0xFF00) >> 8); //offset ch2
            buf[0x17] = (byte)((4085 - CH[2].Position) & 0x00FF);

            buf[0x18] = (byte)((((4096 - (2048 - CH1_comp)) - CH[1].Position) & 0xFF00) >> 8);//offset ch1
            buf[0x19] = (byte)(((4096 - (2048 - CH1_comp)) - CH[1].Position) & 0x00FF);

            buf[0x14] = (byte)(((4087 - CH[3].Position) & 0xFF00) >> 8);//offset ch3
            buf[0x15] = (byte)((4087 - CH[3].Position) & 0x00FF);



            MyDevice.BulkOutEndPt.XferData(ref buf, ref len);


        }
        //-------------------------------------------------------------------------------------------------------------------
        private void showD0D7ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showD0D7ToolStripMenuItem.Checked = true;
            showD0D3ToolStripMenuItem.Checked = false;
            showD4D7ToolStripMenuItem.Checked = false;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void showD0D3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showD0D7ToolStripMenuItem.Checked = false;
            showD0D3ToolStripMenuItem.Checked = true;
            showD4D7ToolStripMenuItem.Checked = false;
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void showD4D7ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showD0D7ToolStripMenuItem.Checked = false;
            showD0D3ToolStripMenuItem.Checked = false;
            showD4D7ToolStripMenuItem.Checked = true;
        }
        //-------------------------------------------------------------------------------------------------------------------
        //------------------------------------pattern trig control------------------------------------------------------
        //------------------------------------------------------------------------------------------------------------------- 
        private void buttonPattern_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            string BtnName = button.Name;


            switch (BtnName)
            {
                case "buttonA1": this.comboBoxA1.DroppedDown = true;
                    break;
                case "buttonA2": this.comboBoxA2.DroppedDown = true;
                    break;
                case "buttonA3": this.comboBoxA3.DroppedDown = true;
                    break;

                case "buttonD0": this.comboBoxD0.DroppedDown = true;
                    break;
                case "buttonD1": this.comboBoxD1.DroppedDown = true;
                    break;
                case "buttonD2": this.comboBoxD2.DroppedDown = true;
                    break;
                case "buttonD3": this.comboBoxD3.DroppedDown = true;
                    break;
                case "buttonD4": this.comboBoxD4.DroppedDown = true;
                    break;
                case "buttonD5": this.comboBoxD5.DroppedDown = true;
                    break;
                case "buttonD6": this.comboBoxD6.DroppedDown = true;
                    break;
                case "buttonD7": this.comboBoxD7.DroppedDown = true;
                    break;
            }

        }
        //---------------------------
        private void comboBoxPattern_SelectedIndexChanged(object sender, EventArgs e)
        {

            ComboBox comboBox = (ComboBox)sender;
            string CBname = comboBox.Name;


            if (disble_event_Pattern == false) // becouse event triggers when clearing other edges
            {

                disble_event_Pattern = true;

                // slect wich tipe of edge to search for // ana - digi - nothing
                switch (CBname)
                {
                    case "comboBoxA1": buttonA1.Text = comboBoxA1.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 1; // if edge is selected
                        }
                        break;
                    case "comboBoxA2": buttonA2.Text = comboBoxA2.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 2; // if edge is selected
                        }
                        break;
                    case "comboBoxA3": buttonA3.Text = comboBoxA3.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 3; // if edge is selected
                        }
                        break;

                    case "comboBoxD0": buttonD0.Text = comboBoxD0.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 0xD0; // if edge is selected
                        }
                        break;
                    case "comboBoxD1": buttonD1.Text = comboBoxD1.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 0xD1; // if edge is selected
                        }
                        break;
                    case "comboBoxD2": buttonD2.Text = comboBoxD2.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 0xD2; // if edge is selected
                        }
                        break;
                    case "comboBoxD3": buttonD3.Text = comboBoxD3.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 0xD3; // if edge is selected
                        }
                        break;
                    case "comboBoxD4": buttonD4.Text = comboBoxD4.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 0xD4; // if edge is selected
                        }
                        break;
                    case "comboBoxD5": buttonD5.Text = comboBoxD5.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 0xD5; // if edge is selected
                        }
                        break;
                    case "comboBoxD6": buttonD6.Text = comboBoxD6.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 0xD6; // if edge is selected
                        }
                        break;
                    case "comboBoxD7": buttonD7.Text = comboBoxD7.Text;
                        if (comboBox.SelectedIndex >= 3)
                        {
                            TrigSettings.TrigOnCH = 0xD7; // if edge is selected
                        }
                        break;
                }


                if (comboBox.SelectedIndex == 3)
                {
                    TrigSettings.EdgeSlope = Mode_EdgeSlope.Falling;
                }
                if (comboBox.SelectedIndex == 4)
                {
                    TrigSettings.EdgeSlope = Mode_EdgeSlope.Rising;
                }


                //if current chanel is set to trigger to edge
                // clear other edge triggers

                if (comboBox.SelectedIndex >= 3) // means triggering to edge
                {
                    if ((comboBoxA1.Name != CBname) && (comboBoxA1.SelectedIndex >= 3))
                    {
                        comboBoxA1.SelectedIndex = 0;
                        buttonA1.Text = "X";
                    }
                    if ((comboBoxA2.Name != CBname) && (comboBoxA2.SelectedIndex >= 3))
                    {
                        comboBoxA2.SelectedIndex = 0;
                        buttonA2.Text = "X";
                    }
                    if ((comboBoxA3.Name != CBname) && (comboBoxA3.SelectedIndex >= 3))
                    {
                        comboBoxA3.SelectedIndex = 0;
                        buttonA3.Text = "X";
                    }

                    if ((comboBoxD0.Name != CBname) && (comboBoxD0.SelectedIndex >= 3))
                    {
                        comboBoxD0.SelectedIndex = 0;
                        buttonD0.Text = "X";
                    }
                    if ((comboBoxD1.Name != CBname) && (comboBoxD1.SelectedIndex >= 3))
                    {
                        comboBoxD1.SelectedIndex = 0;
                        buttonD1.Text = "X";
                    }
                    if ((comboBoxD2.Name != CBname) && (comboBoxD2.SelectedIndex >= 3))
                    {
                        comboBoxD2.SelectedIndex = 0;
                        buttonD2.Text = "X";
                    }
                    if ((comboBoxD3.Name != CBname) && (comboBoxD3.SelectedIndex >= 3))
                    {
                        comboBoxD3.SelectedIndex = 0;
                        buttonD3.Text = "X";
                    }
                    if ((comboBoxD4.Name != CBname) && (comboBoxD4.SelectedIndex >= 3))
                    {
                        comboBoxD4.SelectedIndex = 0;
                        buttonD4.Text = "X";
                    }
                    if ((comboBoxD5.Name != CBname) && (comboBoxD5.SelectedIndex >= 3))
                    {
                        comboBoxD5.SelectedIndex = 0;
                        buttonD5.Text = "X";
                    }
                    if ((comboBoxD6.Name != CBname) && (comboBoxD6.SelectedIndex >= 3))
                    {
                        comboBoxD6.SelectedIndex = 0;
                        buttonD6.Text = "X";
                    }
                    if ((comboBoxD7.Name != CBname) && (comboBoxD7.SelectedIndex >= 3))
                    {
                        comboBoxD7.SelectedIndex = 0;
                        buttonD7.Text = "X";
                    }
                }
                // if changed, copy settings to fasten triggering after
                Ptrn_set.CH1 = (byte)comboBoxA1.SelectedIndex;
                Ptrn_set.CH2 = (byte)comboBoxA2.SelectedIndex;
                Ptrn_set.CH3 = (byte)comboBoxA3.SelectedIndex;
                Ptrn_set.D0 = (byte)comboBoxD0.SelectedIndex;
                Ptrn_set.D1 = (byte)comboBoxD1.SelectedIndex;
                Ptrn_set.D2 = (byte)comboBoxD2.SelectedIndex;
                Ptrn_set.D3 = (byte)comboBoxD3.SelectedIndex;
                Ptrn_set.D4 = (byte)comboBoxD4.SelectedIndex;
                Ptrn_set.D5 = (byte)comboBoxD5.SelectedIndex;
                Ptrn_set.D6 = (byte)comboBoxD6.SelectedIndex;
                Ptrn_set.D7 = (byte)comboBoxD7.SelectedIndex;

                snedLoggerSettings(); //LEDS

                disble_event_Pattern = false;
            }
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void toolStripPostTrig_SelectedIndexChanged(object sender, EventArgs e)
        {
            postTrigNum = (int)Math.Pow(10, toolStripPostTrig.SelectedIndex + 1);
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void aCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            aCToolStripMenuItem.Checked = true;
            dCToolStripMenuItem.Checked = false;

            if (cHxToolStripMenuItem.BackColor == Color.Fuchsia)
            {
                CH[1].Coupling = Mode_Coupling.AC;
                updateChanelInfo(CH[1]);
            }
            if (cHxToolStripMenuItem.BackColor == Color.Lime)
            {
                CH[2].Coupling = Mode_Coupling.AC;
                updateChanelInfo(CH[2]);
            }
            if (cHxToolStripMenuItem.BackColor == Color.Yellow)
            {
                CH[3].Coupling = Mode_Coupling.AC;
                updateChanelInfo(CH[3]);
            }
            

            snedLoggerSettings();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void dCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dCToolStripMenuItem.Checked = true;
            aCToolStripMenuItem.Checked = false;

            if (cHxToolStripMenuItem.BackColor == Color.Fuchsia)
            {
                CH[1].Coupling = Mode_Coupling.DC;
                updateChanelInfo(CH[1]);
            }
            if (cHxToolStripMenuItem.BackColor == Color.Lime)
            {
                CH[2].Coupling = Mode_Coupling.DC;
                updateChanelInfo(CH[2]);
            }
            if (cHxToolStripMenuItem.BackColor == Color.Yellow)
            {
                CH[3].Coupling = Mode_Coupling.DC;
                updateChanelInfo(CH[3]);
            }

            snedLoggerSettings();
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void BarPosition_MouseDown(object sender, MouseEventArgs e)
        {
            label17.Text = BarPosition.Value.ToString();
            oldbarPositionVal = BarPosition.Value; 
        }
        //-------------------------------------------------------------------------------------------------------------------
        private void BarPosition_MouseUp(object sender, MouseEventArgs e)
        {
            int activechan=0;

            label18.Text = BarPosition.Value.ToString();

            if (panel2.BackColor == Color.Fuchsia)
                activechan = 1;
            else if (panel2.BackColor == Color.Lime)
                activechan = 2;
            else if (panel2.BackColor == Color.Yellow)
                activechan = 3;


            if (activechan == TrigSettings.TrigOnCH)
            {
                double buff = BarTrigLevel.Value - ((oldbarPositionVal - BarPosition.Value) * 1.8);

                if (buff < 0)
                    buff = 0;

                        if (buff > 255)
                            buff = 255;

                BarTrigLevel.Value = (int)buff;
                trigLvl = (byte)(255 - BarTrigLevel.Value); // save new triglevel
            }
        }

  
        //-------------------------------------------------------------------------------------------------------------------
    }


    public static class FormatExtensions
    {
        public static string ToEngineering(this double value)
        {
            if (value == 0)
            {
                return "0";
            }
            else
            {
                int exp = (int)(Math.Floor(Math.Log10(value) / 3.0) * 3.0);
                double newValue = value * Math.Pow(10.0, -exp);
                if (newValue >= 1000.0)
                {
                    newValue = newValue / 1000.0;
                    exp = exp + 3;
                }
                if (exp == 0)
                    return string.Format("{0:0.###}", newValue);
                else
                    return string.Format("{0:0.###}e{1}", newValue, exp);
            }
        }
    }

}
