private void button1_Click(object sender, EventArgs e)
 {
   try
   {
     if (stopped)
     {
       if (driver == null)
         driver = new DTControl(1000, new int[] { 0, 1 }, new DTControl.Logger(MessageLog), new DTControl.DoneSignalHandler(SignalsDone));
       driver.AnalogStart();
       button1.Text = "STOP";
       stopped = false;
     }
     else
     {
       driver.AnalogStop();
       //button1.Text = "Get";
       stopped = true;
     }
     
   }
   catch (Exception ex)
   {
     MessageBox.Show(ex.Message);
   }
 }
    private void Communicate(int aConn, ref NetworkStream ns)
    {
      request = new BinaryReader(ns);
      response = new BinaryWriter(ns);
      
      m_hasConnection[aConn] = true;

      try
      {
        while (!m_stopServer && m_hasConnection[aConn])
        {
          string cmd;
          string msg = "";

          while (!ns.DataAvailable) 
          {
            if (m_stopServer)
              return;
            Thread.Sleep(100); 
          }

          cmd = request.ReadString();

          switch (cmd)
          {
            case "START":
              {
                Log("Acquisition started");
                response.Write("+ACK");
                m_signals = new double[BufferSize * 2];
                byte[] bufferedSignal = new byte[BufferSize * sizeof(double)];
                m_device.PutDoutValue(1);
                signalWriter = new StreamWriter("real_signals.txt");
                stopped = false;

                try
                {
                  m_device.AnalogStart();
                  //wait for it to start (maybe not necessary)
                  while (m_device.AnalogRunning() == false) { }

                  while (m_device.AnalogRunning() && !stopped)
                  {
                    Thread.Sleep(500);
                  }
                  
                  if (!stopped)
                    m_hasConnection[aConn] = false;
                  msg = "+OK  Signals filtered.";
                  
                }
                catch (Exception ex)
                {
                  Log("Signal filtering failed: " + ex.Message);
                }
                break;
              }
            case "STOP":
              response.Write("+ACK");
              m_device.PutDoutValue(3);
              if (m_device.AnalogRunning())
                m_device.AnalogStop();
              response.Write("DONE");

              break;
              
            case "CLOSE":
              msg = "Connection Closed.";
              m_hasConnection[aConn] = false;
              break;

            case "COEF":
              msg = "+ACK  COEF";
              response.Write(msg);
              try
              {
                int length = request.ReadInt32();
                byte[] buffer = request.ReadBytes(length);
                BufferToDouble(buffer, m_coefficients);
              }
              catch (Exception ex)
              {
                msg = "-ERR  Failed to receive coefficients. " + ex.Message;
                Log(String.Format("({0}) {1}", aConn, msg));
              }
              msg = "+ACK  coefficients received.";
              response.Write(msg);
              break;

            case "TEST":
              {
                msg = "+ACK TEST command received. Filtering test signal.";
                response.Write(msg);

                //read test signals
                StreamReader testReader = new StreamReader(@"..\..\signal.txt");
                List<double> testSignals = new List<double>();
                while (testReader.EndOfStream == false)
                {
                  testSignals.Add(Double.Parse(testReader.ReadLine()));
                }
                Log("+OK Signals read successfully.");

                byte[] bufferedSignals = new byte[BufferSize * sizeof(double)];
                double[] filteredSignals;
                double average, variance, min, max;
                int bufferIndex = 0;

                // this part is weird, because the test file is 6001 signals, but we want to send 100-length buffers
                // 
                for (int signalIndex = 0; signalIndex < testSignals.Count; signalIndex += BufferSize)  //simulate 100-length buffers
                {
                  double[] buffer = new double[BufferSize];

                  // copy 100 values unless the buffer size is less than 100 (i.e. the last buffer only has 1 value)
                  testSignals.CopyTo(signalIndex, buffer, 0, ((testSignals.Count - signalIndex) < BufferSize) ? testSignals.Count - signalIndex : BufferSize);
                  if (!ProcessSignals(buffer, out filteredSignals, out average, out variance, out min, out max))
                    continue;
                  DoubleToBuffer(filteredSignals, bufferedSignals);
                  response.Write("BUF");
                  response.Write(bufferedSignals.Length);
                  response.Write(bufferedSignals);
                  DoubleToBuffer(buffer, bufferedSignals);
                  response.Write(bufferedSignals.Length);
                  response.Write(bufferedSignals);
                  response.Write(average);
                  response.Write(variance);
                  response.Write(min);
                  response.Write(max);
                  bufferIndex++;
                }
                response.Write("DONE");
                msg = "+OK: Signals filtered.";
                break;
              }

            case "INIT":
              response.Write("+ACK");
              if (m_device == null)
              {
                double frequency = request.ReadDouble();
                m_device = new DTControl(frequency, new int[] { 0, 1 }, new DTControl.Logger(Log), new DTControl.DoneSignalHandler(GetBuffer));
                m_device.PutDoutValue(0);
                msg = "+OK DT9816 Initialized.";
              }
              else
                msg = "+OK DT9816 Already initialized.";
              break;

            default:
              msg = "-ERR: Command not recognized.";
              response.Write(msg);
              break;
          }

          response.Flush();
          Log(String.Format("({0}) {1}", aConn, msg));
        }
      }
      catch (Exception ex)
      {
        Log(String.Format("[{0} {1}] -ERR  Connection {2} failed: {3}",
            DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString(), aConn, ex.Message));
      }
      finally
      {
        ns.Close();
      }

    }