public static void WaitForZTCResponse(FTDIdevice thisdevice, Parameters parameters)
        {
            byte[] readResult;
            int PLengthInt;
            int i = 1;
            bool responseA = false;
            string cache = string.Empty;
            string readOut = string.Empty;
            string packet = string.Empty;
            char[] charcache;
            byte[] PLength = new Byte[1];

            while (i <parameters.listenlooptimeout && responseA == false)
            {
                readResult = thisdevice.poll();
                readOut = ConvertByteArrayToSpacedHexString(readResult);
                cache = cache + readOut;
                charcache = cache.ToCharArray(0, cache.Length);

                if (cache.Length > 11)
                {
                    PLength = ConvertHexStringToByteArray(cache.Substring(9, 2));
                    byte[] PLengthB = new byte[2];
                    PLengthB[0] = PLength[0];
                    PLengthInt = BitConverter.ToInt16(PLengthB, 0);
                    if (cache.Length > 12 + PLengthInt * 3)
                    {
                        packet = cache.Substring(0, 14 + PLengthInt * 3);
                        cache = cache.Remove(0, 14 + PLengthInt * 3);
                        packet = packet.Remove(0, 2);
                        packet = packet.Remove(packet.Length - 2);
                        //Console.WriteLine("From Port 1: {0}", packet);
                        responseA = true;
                    }
                }

                System.Threading.Thread.Sleep(20);
                i++;
                if (i == parameters.listenlooptimeout)
                    throw new Exception_Yellow("No response received during listen.");
            }
        }
        public static bool WaitForZTCResponseAndIndication(FTDIdevice EndDevice, FTDIdevice Coordinator, string packetsent)
        {
            //StartTestingTimer3();
            //StartTestingTimer2(); string time2 = GetTestingTimestamp2();
            //string TxTime = GetTimestamp();
            //string RxTime = string.Empty;
            //int deltaT = 0;
            int success = 0;

            byte[] readResult;
            int PLengthInt;
            int i = 1;
            bool responseA = false;
            string cache = string.Empty;
            string readOut = string.Empty;
            string packet = string.Empty;
            char[] charcache;
            byte[] PLength = new Byte[1];

            byte[] readResult2;
            int PLengthInt2;
            bool responseB = false;
            string cache2 = string.Empty;
            string readOut2 = string.Empty;
            string packet2 = string.Empty;
            char[] charcache2;
            byte[] PLength2 = new Byte[1];

            while (i < 40 && (responseA == false || responseB == false))
            {
                //time2 = GetTestingTimestamp2();
                if (responseA == false)
                {
                    readResult = EndDevice.poll();                             //read from port of device A
                    readOut = ConvertByteArrayToSpacedHexString(readResult);
                    cache = cache + readOut;                                //add most recent byte from port A to cache
                    charcache = cache.ToCharArray(0, cache.Length);

                    if (cache.Length > 11)                                  //if the cache is long enough to hold a full transmission (at least 4 bytes in string format)
                    {
                        PLength = ConvertHexStringToByteArray(cache.Substring(9, 2));  // packet length = the length stored in the length byte of the transmission
                        byte[] PLengthB = new byte[2];
                        PLengthB[0] = PLength[0];
                        PLengthInt = BitConverter.ToInt16(PLengthB, 0);
                        if (cache.Length > 12 + PLengthInt * 3)             //if transmission is complete (i.e. if the number of bytes specified by the length byte have all been received)
                        {
                            packet = cache.Substring(0, 14 + PLengthInt * 3);
                            cache = cache.Remove(0, 14 + PLengthInt * 3);
                            packet = packet.Remove(0, 2);
                            packet = packet.Remove(packet.Length - 2);      //removing extraneous bytes, like parity byte?
                            //Console.WriteLine("From Port 1: {0}", packet);
                            responseA = true;                               //done listening
                        }
                    }
                }
                //time2 = GetTestingTimestamp2();

                if (responseB == false)
                {
                    readResult2 = Coordinator.poll();
                    readOut2 = ConvertByteArrayToSpacedHexString(readResult2);
                    cache2 = cache2 + readOut2;
                    charcache2 = cache2.ToCharArray(0, cache2.Length);

                    if (cache2.Length > 11)
                    {
                        PLength2 = ConvertHexStringToByteArray(cache2.Substring(9, 2));
                        byte[] PLengthC = new byte[2];
                        PLengthC[0] = PLength2[0];
                        PLengthInt2 = BitConverter.ToInt16(PLengthC, 0);
                        if (cache2.Length > 12 + PLengthInt2 * 3)
                        {
                            packet2 = cache2.Substring(0, 14 + PLengthInt2 * 3);
                            cache2 = cache2.Remove(0, 14 + PLengthInt2 * 3);
                            packet2 = packet2.Remove(0, 2);
                            packet2 = packet2.Remove(packet2.Length - 2);
                            //Console.WriteLine("From Port 2: {0}", packet2);
                            cache2 = string.Empty;

                            //Packet comparing
                            packet2 = packet2.Replace(" ", "");
                            packetsent = packetsent.Replace(" ", "");
                            if (packet2.Length == packetsent.Length + 2)
                            {
                                if (string.Compare(packet2.Substring(packet2.Length - 8, 8), packetsent.Substring(packetsent.Length - 8, 8), true) == 0)
                                {
                                    responseB = true;
                                    success = 1;
                                    //RxTime = GetTimestamp();
                                    //string RxTimeMillisec = RxTime.Substring(12, 6);
                                    //string TxTimeMillisec = TxTime.Substring(12, 6);
                                    //deltaT = int.Parse(RxTimeMillisec) - int.Parse(TxTimeMillisec);
                                }

                            }
                        }
                    }
                }
                //time2 = GetTestingTimestamp2();
                System.Threading.Thread.Sleep(1);
                i++;
                //if (i == 40) timeoutcounter++;
            }
            //if (deltaT <= 0)
            //    deltaT = 0;

            packetsent = packetsent.Replace(" ", "");

            //if (responseA == false)
            //Console.WriteLine("Port 1: No Reply");
            //if (responseB == false)
            //Console.WriteLine("Port 2: No Reply");

            //string time = GetTestingTimestamp3();

            if (responseA == true && responseB == true)
                return true;
            else return false;
        }
        public byte[] AddtoReceiveList_ListenForNewFWResponse(FTDIdevice thisdevice, Parameters parameters)
        {
            Queue<byte> incomingbytequeue = new Queue<byte>();
            byte ZTCHeader = 0x02;
            int initialqueuelen = incomingbytequeue.Count;
            int indexofZTCheaderinqueue = 0;
            byte[] incomingdata = thisdevice.poll();
            int arraylen = incomingdata.Length;
            for (int i = 0; i < arraylen; i++)
                incomingbytequeue.Enqueue(incomingdata[i]);
            int queuelen = incomingbytequeue.Count;
            byte temp;
            bool packetstarted = false;
            for (int j = 0; j < queuelen; j++)
            {
                temp = incomingbytequeue.Dequeue();
                if (temp == ZTCHeader && incomingbytequeue.Count > 3)
                {
                    packetstarted = true;
                    break;
                }
                else
                {
                    //incomingbytequeue.Enqueue(temp); //this is a problem. we should throw this out.
                    indexofZTCheaderinqueue++;
                }
            }
            if (packetstarted)
            {
                byte tempheader = incomingbytequeue.Dequeue();
                byte tempopcode = incomingbytequeue.Dequeue();
                int payloadlen = incomingbytequeue.Dequeue();
                if (incomingbytequeue.Count < payloadlen + 1)  //if the packet hasn't fully arrived yet, just put the packets we've read so far back on the queue and then exit, to come back and read again later
                {
                    int count = incomingbytequeue.Count;
                    incomingbytequeue.Enqueue(ZTCHeader);
                    incomingbytequeue.Enqueue(tempheader);
                    incomingbytequeue.Enqueue(tempopcode);
                    incomingbytequeue.Enqueue((byte)payloadlen);
                    for (int k = 0; k < count; k++)
                        incomingbytequeue.Enqueue(incomingbytequeue.Dequeue());
                    return null;
                    //throw new Exception_Yellow("incomplete packet received.");
                }
                byte[] packet = new byte[payloadlen + 5];
                packet[0] = ZTCHeader;
                packet[1] = tempheader;
                packet[2] = tempopcode;
                packet[3] = (byte)payloadlen;
                for (int k = 0; k < payloadlen; k++)
                    packet[4 + k] = incomingbytequeue.Dequeue();
                packet[payloadlen + 4] = incomingbytequeue.Dequeue(); //CRC
                //if (packet[payloadlen + 4] == 0) packet[0] = 2; //dummy just to have breakpoint to test theory that 0 is returned sometimes

                return packet;
                //RxPacket rx = new RxPacket();
                //rx.completepacket = packet;
                //RxFIFO.Enqueue(rx);
                //AllRxPacketQueueDebugging.Enqueue(rx);
                ////now figure out what to do with the rest of the packets that are hanging out there.  re-enqueue them probably
            }
            else return null;
            //if(incomingpacket!=null && incomingpacket.Length!=0)
            //RxFIFO.Enqueue(incomingpacket);
        }
        //    newtrimmer(initialcoarse, initialtrim1, initialtrim2)
        public void NewTrimmer(FTDIdevice thisUSB, int coarse, double finetrim, double backupfinetrim)
        {
            SSLInterface ssl = new SSLInterface(parameters, thisUSB);

            thisUSB.poll();  //clear out anything sitting on the port

            double fine1 = finetrim;        //should be the mode of the trimming results
            double fine2 = backupfinetrim;  //if newton's method doesn't get it on the first try we use secant method with this backupfinetrim and finetrim
            bool done = false;
            double temp;
            double freq2 = -12345;  //dummy value to avoid error
            double freq1 = FreqAtTrim(thisUSB, ssl, coarse, Convert.ToInt32(fine1));
            checkFreqValidity(fine1, ref freq1, coarse, thisUSB, FREQ_COUNTER, ssl);
            if (freqWithin8(coarse, fine1, freq1)) done = true;
            TrimSequence += (" | " + coarse.ToString() + " " + Math.Round(fine1, 3).ToString() + " " + freq1.ToString());
            if (!done) // this if statement is here just in case we got it right the first time
            {
                temp = fine1 - (freq1 - targetfrequency) / finetrimsizeinHz;    //use Newton's method to find the second point, so we finish after 2 measurements more often
                if (temp <= 31 && temp >= 0) fine2 = temp;                      //but only use it if it gives a value between 0 and 31, otherwise revert to input fine2
                freq2 = FreqAtTrim(thisUSB, ssl, coarse, Convert.ToInt32(fine2));         // in the future, could adjust this to save a step when adjusting coarse, but we expect to adjust coarse only very rarely
                checkFreqValidity(fine2, ref freq2, coarse, thisUSB, FREQ_COUNTER, ssl);
                if (freqWithin8(coarse, fine2, freq2)) done = true;
                TrimSequence += (" | " + coarse.ToString() + " " + Math.Round(fine2,3).ToString() + " " + freq2.ToString());
            }
            while (!done && Math.Abs(fine2 - fine1) > 1)  //while not done and trims are more than 1 apart
            {

                temp = fine2 - ((freq2 - targetfrequency) * (fine2 - fine1)) / (freq2 - freq1);  //use the secant method
                fine1 = fine2;
                fine2 = temp;
                freq1 = freq2;
                int intfine2 = Convert.ToInt16(fine2);
                if (intfine2 <= 31 && intfine2 >= 0)
                {
                    //temp = fine2 - ((freq2 - targetfrequency) * (fine2 - fine1)) / (freq2 - freq1);  //use the secant method
                    //fine1 = fine2;
                    //fine2 = temp;
                    //freq1 = freq2;
                    freq2 = FreqAtTrim(thisUSB, ssl, coarse, Convert.ToInt32(fine2));
                    checkFreqValidity(fine2, ref freq2, coarse, thisUSB, FREQ_COUNTER, ssl);
                    if (freqWithin8(coarse, fine2, freq2)) done = true;
                    TrimSequence += (" | " + coarse.ToString() + " " + Math.Round(fine2,3).ToString() + " " + freq2.ToString());
                }
                else if (intfine2 > 31)
                {
                    if (intfine2 > 36)
                    {
                        while (freq2 > targetfrequency && coarse < 31)
                        {
                            coarse++; //could replace this with coarse += (intfine2-31)/7 if we ever saw cases of needing to adjust by >1 coarse trim
                            if (coarse == 16) coarse = 28;  //accounting for the overlap in coarse trim values due to the 5th cap being only 4 pf
                            freq2 = FreqAtTrim(thisUSB, ssl, coarse, 31);
                            checkFreqValidity(fine2, ref freq2, coarse, thisUSB, FREQ_COUNTER, ssl);
                            if (freqWithin8(coarse, fine2, freq2)) done = true;
                            TrimSequence += (" | " + coarse.ToString() + " " + Math.Round(fine2,3).ToString() + " " + freq2.ToString());
                        }
                    }
                    else coarse++;
                    NewTrimmer(thisUSB, coarse, 31, 24);
                    done = true;
                }
                else if (intfine2 < 0)
                {
                    if (intfine2 < -5)
                    {
                        while (freq2 < targetfrequency && coarse > 0)
                        {
                            coarse--; //could replace this with coarse += (intfine2)/7 if we ever saw cases of needing to adjust by >1 coarse trim
                            freq2 = FreqAtTrim(thisUSB, ssl, coarse, 0);
                            checkFreqValidity(fine2, ref freq2, coarse, thisUSB, FREQ_COUNTER, ssl);
                            if (freqWithin8(coarse, fine2, freq2)) done = true;
                            TrimSequence += (" | " + coarse.ToString() + " " + Math.Round(fine2,3).ToString() + " " + freq2.ToString());
                        }
                    }
                    else coarse--;
                    NewTrimmer(thisUSB, coarse, 0, 7);
                    done = true;
                }
            }
            if (!done)  //(could have become done from coarse changing / recursive call; this code is only reached if we've finished trimming with fine trims 1 away from each other but freqs not within 8)
            {
                //if we've trimmed as well as possible but no frequency was within 8 Hz, choose which one was closer (and if it was fine1, re-set that trim).
                if (Math.Abs(freq1 - targetfrequency) < Math.Abs(freq2 - targetfrequency))
                {
                    //FTinti.Command(FTinti, "95 0A 02 " + FTinti.TrimPacketPrep(Convert.ToInt32(fine1)) + FTinti.TrimPacketPrep(coarse));
                    FinishTrim(coarse, fine1, freq1);
                }
                else FinishTrim(coarse, fine2, freq2);
            }
        }