//-------------------------------------------------------------------------
#include <stdio.h>
#include <vcl.h>
#pragma hdrstop
#include "Data.h"
#include "Main.h"
#include "Fit.h"
#include "Sim.h"
#include "ExpRun.h"
#include "Protocol.h"
#include <stdio.h>
#include <math.h>
#include <dir.h>
#include <time.h>
#include <sys\timeb.h>



//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TDataForm *DataForm;
//---------------------------------------------------------------------------
__fastcall TDataForm::TDataForm(TComponent* Owner)
  : TForm(Owner)
{
  getcwd(CurrentDir, 256);
  refname = "C:\\FRR\\Lift_data\\Ref.d00";
  StoreFileName = CurrentDir;
  StoreFileName += "\\Data\\Default_FRR_Data.d00";
  ResultsFileName = CurrentDir;
  ResultsFileName += "\\Results\\Default_FRR_Data.res";
  StoreFileNameLabel->Caption = StoreFileName;
  exfactor = 1.e-6;
  fo =    20;
  fm =    60;
  sig = 800;
  CStep = 0.1;
  p =     0.2;
  Delta = (fm - fo)/fm;
  alp[0] = 0.5;
  alp[1] = 0.5;
  alp[2] = 0.2;
  alp[3] = 0.1;
  tau[0] = 400;
  tau[1] = 450;
  tau[2] = 600;
  tau[3] = 30000;
  stau = 1000;
  for(int ic = 0; ic < 101; ic++)
  {
    CycleTau[ic] = 1000;
  }
  NoTaus = 4;
  NoIter = 100;
  NoRuns = 10;
  iter   = 0;
  Cycle = 100;
  UpdateCycle();
  weighted = false;
  ChiSq = 1.0;
  fofree = true;
  fmfree = true;
  sigfree = true;
  CSfree  = false;
  pfree = false;
  SingleExp = true;
  FixedGain = true;
  ExecuteON = false;
  taufree[0] = true;
  taufree[1] = true;
  taufree[2] = true;
  taufree[3] = true;
  PlotPoint = 0;

  RegressOrder = 4;
  ExPower = 300;
  ExPowerLast = 200;
  Irrad   = 0;
  CStart  = 0;
  Sampling = 250;
  Fnormalized = false;
  ReferDisplay = true;
  sprintf(text, "%d",NoTaus);        NoTausEd->SetTextBuf(text);
  ResetDel(0.2);
  StepFitOn = false;
  FitStart = 1;
  FitEnd = 1086;
  Step = 1.0;
  Noise = 0.2;
  weighted = true;
  delfactor = 0.9;
  DerValue = 0.001;
  cfactor = 0.0;
  Status();
  SaveParamBtnClick(NULL);
  FirstPassDone = false;
  chifact = 1.0;
  for(int ip = 0; ip < 2000; ip++) exlen[ip] = 4;
  AllSamples = false;
  ExecuteON  = false;
  Samples = 400;
  TimeBase = false;
  FGain = 50;
  FGainBtnClick(this);
  XGain = 10;
  ExLenParsed = false;
  FitDone = false;
  FileStoreAutoMode = false;
  MagicNumber = 1.6180339;
  ResultsMemo->Clear();
  RawDataMemo->Clear();
  DateTimeRecord = "";
  BlueLight = 0;
  IRRLight = 0;
  CycleStart[0] = 5;
  int i = CycleStart[0];
  TimeInterval = 0.5;
  SeqInterval  = 1;
  NoSeq        = 1;

//------- Simulation ----

//-------  PLOTS  -------
  ProfileChart->BackColor = clWhite;                  //Raw fluorescence chart
  ProfileChart->LeftAxis  ->Grid->Color = clSilver;   //Grid Color
  ProfileChart->BottomAxis->Grid->Color = clSilver;
  ProfileChart->LeftAxis->LabelStyle = talValue;      //Value in the Label
  ProfileChart->BottomAxis->LabelStyle = talValue;

  Profile = new TFastLineSeries(this);                //Raw fluorescence profile
  Profile->SeriesColor = clBlack;
  Profile->ParentChart = ProfileChart;
  CORR = new TFastLineSeries(this);
  CORR->SeriesColor = clBlue;
  CORR->ParentChart = ProfileChart;

  CORR1 = new TFastLineSeries(this);
  CORR1->SeriesColor = clGreen;
  CORR1->ParentChart = ProfileChart;
  FitChart->BackColor = clWhite;                  //Fit Page chart
  FitChart->LeftAxis  ->Grid->Color = clSilver;
  FitChart->BottomAxis->Grid->Color = clSilver;
  FitChart->LeftAxis->LabelStyle = talValue;      //Value in the Label
  FitChart->BottomAxis->LabelStyle = talValue;

  CC = new TLineSeries(this);
  CC->ParentChart = FitChart;
  CC->SeriesColor = clBlue;
  CC->Pen->Width = 1;

  CHSEP = new TFastLineSeries(this);
  CHSEP->ParentChart = FitChart;
  CHSEP->SeriesColor = clGreen;

  F = new TPointSeries(this);
  F->ParentChart = FitChart;
  F->Pointer->Style = psCircle;
  F->Pointer->VertSize = 2;
  F->Pointer->HorizSize = 2;
  F->Pointer->Brush->Color = clRed;
  F->Pointer->Pen->Color = clRed;
  F->SeriesColor = clRed;

  FIT = new TLineSeries(this);
  FIT->ParentChart = FitChart;
  FIT->SeriesColor = clBlack;
  FIT->Pen->Width = 2;

  REF = new TPointSeries(this);
  REF->SeriesColor = clBlue;
  REF->ParentChart = FitChart;
  REF->Pointer->VertSize = 2;
  REF->Pointer->HorizSize = 2;
  REF->Pointer->Style = psCircle;

//------  DATA Chart ---------

  DataChart->BackColor = clWhite;
  DataChart->LeftAxis  ->Grid->Color = clSilver;
  DataChart->BottomAxis->Grid->Color = clSilver;
  DataChart->LeftAxis->LabelStyle = talValue;         //Value in the Label
  //DataChart->LeftAxis->Increment = 20;
  DataChart->BottomAxis->LabelStyle = talValue;
  DataChart->LeftAxis->SetMinMax(0, 100);
  DataChart->BottomAxis->SetMinMax(0, 100);

  for(int i = 0; i < 40; i++)
  {
      plots[i].pos = i * 20 + 12;
      plots[i].symbol = 0;
      plots[i].on = false;
      plots[i].color = clSilver;
  }
  plots[0].on = true; plots[0].color = clLime;
  plots[1].on = true; plots[1].color = clGreen;
  plots[2].on = false; plots[2].color = clFuchsia;
  plots[3].on = true; plots[3].color = clRed;
  plots[4].on = true; plots[4].color = clBlue;

  plots[0].var = 0;        plots[0].range = 2000;     //Fo
  plots[1].var = 1;        plots[1].range = 2000;     //Fm
  plots[2].var = 2;        plots[2].range = 2000;     //Fv
  plots[3].var = 3;        plots[3].range = 1;        //Del
  plots[4].var = 5;        plots[4].range = 1000;     //Sig
  plots[5].var = 6;        plots[5].range = 1;        //p
  plots[6].var = 7;        plots[6].range = 10000;    //Tau0
  plots[7].var = 8;        plots[7].range = 10000;    //Tau1
  plots[8].var = 9;        plots[8].range = 10000;    //Tau2
  plots[9].var = 10;       plots[9].range = 10000;    //Tau5
  plots[10].var = 11;      plots[10].range = 10000;   //Tau10
  plots[11].var = 12;      plots[11].range = 10000;   //Tau15
  plots[12].var = 15;      plots[12].range = 10000;   //Tau20
  plots[13].var = 16;      plots[13].range = 10000;   //Tau30
  plots[14].var = 17;      plots[14].range = 10000;   //Tau50
  plots[16].var = 19;      plots[16].range = 10000;   //Tau60
  plots[17].var = 20;      plots[17].range = 10000;   //TauLast
  plots[18].var = 24;      plots[18].range = 100;     //Irrad
  plots[19].var = 25;      plots[19].range = 100;     //Temp


  for(int iplot = 0; iplot < 25; iplot++)
  {
      PLOTS[iplot] = new TLineSeries(this);
      PLOTS[iplot]->ParentChart = DataChart;
      PLOTS[iplot]->SeriesColor = plots[iplot].color;
      PLOTS[iplot]->Pen->Width = 1;
  }
  PlotStart = 0;
  PlotEnd   = 100;
  PlotWindow = 100;
  PlotUpdate = 20;
  PlotCurrent = 1;
  //====  DEFAULT CALIBRATION CONSTANTS =====
  for (int igain = 0; igain < 20; igain ++)
  {
      Gain[igain] = 1.0;
      Scat[igain] = 0.1;
  }
  GainIndex    = 9;
  GainIndexSet = 9;
  Gain[0] = 1.0;
  Gain[1] = 1.9584;
  Gain[2] = 5.1172;
  Gain[3] = 9.9891;
  Gain[4] = 20.3079;
  Gain[5] = 50.4384;
  Gain[6] = 98.5256;
  Gain[7] = 202.6260;
  Gain[8] = 481.5652;
  Gain[9] = 992.2462;
  Gain[10] = 2000;
  Gain[11] = 5000;
  Gain[12] = 10000;
  /*
  Scat[0] = 0.556;
  Scat[1] = 1.283;
  Scat[2] = 3.558;
  Scat[3] = 7.050;
  Scat[4] = 14.790;
  Scat[5] = 36.793;
  Scat[6] = 72.502;
  Scat[7] = 147.462;
  Scat[8] = 333.099;
  Scat[9] = 757.521;
  Scat[10] = 0.0;
  Scat[11] = 0.0;
  Scat[12] = 0.0;
  */
  GainValue = Gain[GainIndex];
  ScatValue = Scat[GainIndex];
  GainDone = false;


//----- PROTOCOL INIT --------
  Protocol->Lines->Delete(0);

  FlashChart->BackColor = clWhite;                  //Raw fluorescence chart
  FlashChart->LeftAxis  ->Grid->Color = clSilver;   //Grid Color
  FlashChart->BackColor = clWhite;                  //Raw fluorescence chart
  FlashChart->BackColor = clWhite;                  //Raw fluorescence chart
  FlashChart->BottomAxis->Grid->Color = clSilver;
  FlashChart->LeftAxis->LabelStyle = talValue;      //Value in the Label
  FlashChart->BottomAxis->LabelStyle = talValue;
  FLASH = new TFastLineSeries(this);                //Raw fluorescence profile
  FLASH->SeriesColor = clBlack;
  FLASH->ParentChart = FlashChart;

  IrrChart->BackColor = clWhite;
  IrrChart->LeftAxis  ->Grid->Color = clSilver;
  IrrChart->BackColor = clWhite;
  IrrChart->BackColor = clWhite;
  IrrChart->BottomAxis->Grid->Color = clSilver;
  IrrChart->LeftAxis->LabelStyle = talValue;
  IrrChart->BottomAxis->LabelStyle = talValue;

  IRR = new TFastLineSeries(this);
  IRR->SeriesColor = clRed;
  IRR->ParentChart = IrrChart;

  EV = new TFastLineSeries(this);
  EV->SeriesColor = clBlue;
  EV->ParentChart = IrrChart;

  SimChart->BackColor = clWhite;
  SimChart->LeftAxis  ->Grid->Color = clSilver;
  SimChart->BackColor = clWhite;
  SimChart->BackColor = clWhite;
  SimChart->BottomAxis->Grid->Color = clSilver;
  SimChart->LeftAxis->LabelStyle = talValue;
  SimChart->BottomAxis->LabelStyle = talValue;

  EXS = new TFastLineSeries(this);
  EXS->SeriesColor = clBlue;
  EXS->ParentChart = SimChart;

  FIF = new TFastLineSeries(this);
  FIF->SeriesColor = clRed;
  FIF->ParentChart = SimChart;

  FIP = new TFastLineSeries(this);
  FIP->SeriesColor = clBlack;
  FIP->ParentChart = SimChart;

  RED = new TFastLineSeries(this);
  RED->SeriesColor = clBlue;
  RED->ParentChart = SimChart;

  PQRED = new TFastLineSeries(this);
  PQRED->SeriesColor = clGreen;
  PQRED->ParentChart = SimChart;
  LaserON = false;
  ExCalValue = 3.271 * 0.66 * (1/1600.0) * 1.e-8;
}
//--------------------------------------------------------------------------



void __fastcall TDataForm::SaveRefButtonClick(TObject *Sender)
{
  if (MessageDlg("Overwrite the REF file? ", mtConfirmation,
  TMsgDlgButtons() << mbYes << mbNo << mbCancel, 0) == mrYes)
  {
    FILE* reffile;
    reffile = fopen(refname, "w+b");
    fwrite(&f[0],   nodata, 4, reffile);
    fwrite(&tim[0], nodata, 4, reffile);
    fclose(reffile);
  }
}
//---------------------------------------------------------------------------
void __fastcall TDataForm::GetRefButtonClick(TObject *Sender)
{
  FILE* reffile;
  reffile = fopen(refname, "rb");
  long filesize;
  fseek(reffile, 0L, SEEK_END);
  filesize = ftell(reffile);
  nodata = filesize/8;          //Ref file stored as ref +tim, floats
  fseek(reffile, 0L, SEEK_SET);
  //---- Read nodata data points, each 4 bytes long
  fread(ref, nodata, 4, reffile);
  fread(tim, nodata, 4, reffile);
  fclose(reffile);
  refAver = 0;
  for(int i = 1; i < nodata; i++) refAver += ref[i];
  refAver /= nodata;
  for(int i = 1; i < nodata; i++)
  {
    ref[i] /= refAver;
    excal[i] *= ref[i];
    //ex[i] = ref[i] * ExPower * exlen[i];
    //excal[i] = ex[i] * 3.3e-8;
  }
  REF->Clear();
  for(int i = 1; i < nodata; i++)
  REF->AddXY(tim[i], ref[i] * fAver, "", clTeeColor);
  ReferPresent = true;
  NormalizeBox->Enabled = true;

}
//---------------------------------------------------------------------------

void __fastcall TDataForm::ShowRefCheckClick(TObject *Sender)
{
  ReferDisplay = ShowRefCheck->Checked;
  REF->Clear();
  if ((ReferDisplay) && (ReferPresent))
  {
    for(int i = 1; i < nodata; i++)
    REF->AddXY(tim[i], ref[i]*fAver, "", clTeeColor);
  }
}
//---------------------------------------------------------------------------


void __fastcall TDataForm::NormalizeBoxClick(TObject *Sender)
{
  if(NormalizeBox->Checked)
  {
    F->Clear();
    for(int i = 1; i < nodata ; i++)
    {
      f[i] = f[i]/ref[i];
      F->AddXY(tim[i], f[i], "", clTeeColor);
    }
    Fnormalized = true;
  }
  else
  {
    F->Clear();
    for(int i = 1; i < nodata ; i++)
    {
      f[i] = f[i] * ref[i];
      F->AddXY(tim[i], f[i], "", clTeeColor);
    }
    Fnormalized = false;
  }
  Regress(CycleStart[0],CyclePump[0], 2);
  foreg = fit[0];
  Regress(CycleStart[NoCycles -1], CyclePump[NoCycles - 1], 2);
  fmreg = fit[CyclePump[NoCycles - 1]];
  sprintf(text, "%10.2f",foreg);
  FoEd->SetTextBuf(text);
  sprintf(text, "%10.2f",fmreg);
  FmEd->SetTextBuf(text);
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::Status()
{
  sprintf(text, "%8.2f",fo);
  FoEd->SetTextBuf(text);
  FoEd->Update();
  sprintf(text, "%8.2f",fm);
  FmEd->SetTextBuf(text);
  FmEd->Update();
  sprintf(text, "%8.2f",sig);
  SigEd->SetTextBuf(text);
  SigEd->Update();
  sprintf(text, "%6.4f",p);
  pEd->SetTextBuf(text);
  pEd->Update();
  sprintf(text, "%6.4f",cfactor);

  if ((fm > fo) && (fm > 1.e-5)) Delta = (fm - fo)/fm;
  else Delta = 0;
  sprintf(text, "%6.4f",Delta);
  DeltaEd->SetTextBuf(text);
  DeltaEd->Update();

  float alpsum = 0;
  for(int i = 0; i < NoTaus; i++) alpsum += alp[i];
  for(int i = 0; i < NoTaus; i++) alp[i] /= alpsum;
  sprintf(text, "%8.0f",tau[0]);
  Tau0Ed->SetTextBuf(text);
  Tau0Ed->Update();
  sprintf(text, "%6.3f",alp[0]);
  Alp0Ed->SetTextBuf(text);    Alp0Ed->Update();
  if(NoTaus > 1)
  {
    Tau1Ed->Visible = true;
    Alp1Ed->Visible = true;
    Tau1Ed->Update();
    sprintf(text, "%8.0f",tau[1]);
    Tau1Ed->SetTextBuf(text);
    Alp1Ed->Update();
    sprintf(text, "%6.3f",alp[1]);
    Alp1Ed->SetTextBuf(text);
  }
  else
  {
    Tau1Ed->Visible = false;
    Alp1Ed->Visible = false;
  }
  if(NoTaus > 2)
  {
    Tau2Ed->Visible = true;
    Alp2Ed->Visible = true;
    Alp2Ed->Update();
    sprintf(text, "%8.0f",tau[2]);
    Tau2Ed->SetTextBuf(text);
    Tau2Ed->Update();
    sprintf(text, "%6.3f",alp[2]);
    Alp2Ed->SetTextBuf(text);
  }
  else
  {
    Tau2Ed->Visible = false;
    Alp2Ed->Visible = false;
  }
  if(NoTaus > 3)
  {
    Tau3Ed->Visible = true;
    Alp3Ed->Visible = true;
    sprintf(text, "%8.0f",tau[3]);
    Tau3Ed->SetTextBuf(text);
    Tau3Ed->Update();
    sprintf(text, "%6.3f",alp[3]);
    Alp3Ed->SetTextBuf(text);
    Alp3Ed->Update();
  }
  else
  {
    Tau3Ed->Visible = false;
    Alp3Ed->Visible = false;
  }
  sprintf(text, "%6.4f",CStart);
  CStartEd->SetTextBuf(text);
  CStartEd->Update();
  sprintf(text, "%f",ChiSq * 1000);
  ChisqEd->SetTextBuf(text);
  ChisqEd->Update();
  //sprintf(text, "%8.2f",ExPower);
  //ExPowerEd->SetTextBuf(text);
  //ExPowerEd->Update();
  sprintf(text, "%d",iter);
  IterEd->SetTextBuf(text);
  IterEd->Update();
  sprintf(text, "%6.4f",delfactor);
  DelFactorEd->SetTextBuf(text);
  sprintf(text, "%6.4f",Noise);
  NoiseEd->SetTextBuf(text);
  DelFactorEd->Update();
  sprintf(text, "%6.4f",DerValue);
  DerValueEd->SetTextBuf(text);
  Weighted->Checked = weighted;

  //if(DebugFit)
  //if (MessageDlg("Proceed? ", mtConfirmation,
  //TMsgDlgButtons() << mbYes <<mbNo, 0) == mrNo) DebugFit = false;
}

void __fastcall TDataForm::Status_B2C()
{
   sprintf(text, "%8.2f",fo);
  FoEd->SetTextBuf(text);
  FoEd->Update();
  sprintf(text, "%8.2f",fm);
  FmEd->SetTextBuf(text);
  FmEd->Update();
  sprintf(text, "%8.2f",sig);
  SigEd->SetTextBuf(text);
  SigEd->Update();
  sprintf(text, "%6.4f",p);
  pEd->SetTextBuf(text);
  pEd->Update();
  sprintf(text, "%6.4f",cfactor);

  if ((fm > fo) && (fm > 1.e-5)) Delta = (fm - fo)/fm;
  else Delta = 0;
  sprintf(text, "%6.4f",Delta);
  DeltaEd->SetTextBuf(text);
  DeltaEd->Update();
  /*
  sprintf(text, "%8.0f",CycleTauMin[0]);
  Alp0Ed->SetTextBuf(text);
  Alp0Ed->Update();
  sprintf(text, "%8.0f",CycleTauMin[1]);
  Alp1Ed->SetTextBuf(text);
  Alp1Ed->Update();
  sprintf(text, "%8.0f",CycleTauMin[2]);
  Alp2Ed->SetTextBuf(text);
  Alp2Ed->Update();
  sprintf(text, "%8.0f",CycleTauMin[5]);
  Alp3Ed->SetTextBuf(text);
  Alp3Ed->Update();
  sprintf(text, "%8.0f",CycleTauMin[10]);
  Tau0Ed->SetTextBuf(text);
  Tau0Ed->Update();
  sprintf(text, "%8.0f",CycleTauMin[15]);
  Tau1Ed->SetTextBuf(text);
  Tau1Ed->Update();
  sprintf(text, "%8.0f",CycleTauMin[20]);
  Tau2Ed->SetTextBuf(text);
  Tau2Ed->Update();
  sprintf(text, "%8.0f",CycleTauMin[30]);
  Tau3Ed->SetTextBuf(text);
  Tau3Ed->Update();
  */
  sprintf(text, "%6.4f",CStart);
  CStartEd->SetTextBuf(text);
  CStartEd->Update();
  sprintf(text, "%f",ChiSq * 1000);
  ChisqEd->SetTextBuf(text);
  ChisqEd->Update();
  //sprintf(text, "%8.2f",ExPower);
  //ExPowerEd->SetTextBuf(text);
  //ExPowerEd->Update();
  sprintf(text, "%d",iter);
  IterEd->SetTextBuf(text);
  IterEd->Update();
  sprintf(text, "%6.4f",delfactor);
  DelFactorEd->SetTextBuf(text);
  sprintf(text, "%6.4f",Noise);
  NoiseEd->SetTextBuf(text);
  DelFactorEd->Update();
  sprintf(text, "%6.4f",DerValue);
  DerValueEd->SetTextBuf(text);
  Weighted->Checked = weighted;

  //if(DebugFit)
  //if (MessageDlg("Proceed? ", mtConfirmation,
  //TMsgDlgButtons() << mbYes <<mbNo, 0) == mrNo) DebugFit = false;
}

void __fastcall TDataForm::StoreData(AnsiString filename)
{
   AnsiString cc = "";
   char vv[10];
   f[0]   = fo;
   tim[0] = 0;
   ex[0]  = 0;
   FILE* ascfile;
   ascfile = fopen(filename.c_str(), "at");
   fputs("----\n", ascfile);
   fputs(DateTimeRecord.c_str(), ascfile);
   fputs("\n", ascfile);
   fputs("DataPt    Time(us)  EX        EM        Fit  \n", ascfile);
   fputs("=============================================\n", ascfile);
   for(int id = 0; id < nodata + 1; id++)
   {
      cc = "";
      sprintf(vv, "%5i", id);                   cc += vv;
      sprintf(vv, "%10.0f", tim[id]);            cc += vv;
      sprintf(vv, "%10.3f", excal[id] * 1.e6);  cc += vv;   //in quanta/A square
      sprintf(vv, "%10.3f", f[id]);             cc += vv;
      sprintf(vv, "%10.3f", fit[id]);           cc += vv;
      cc += "\n";
      fputs(cc.c_str(), ascfile);
   }
   fclose(ascfile);
}

void __fastcall TDataForm::Save_Data_DlgClick(TObject *Sender)
{
   //SaveFileDlg->FileName = NULL;
   SaveFileDlg->FileName = StoreFileName;
   SaveFileDlg->InitialDir = CurrentDir;
   SaveFileDlg->InitialDir += "\\Data";
   SaveFileDlg->Filter = "FRR Data Files (*.*)|*.*";
   if(SaveFileDlg->Execute())
   {
      StoreFileName = SaveFileDlg->FileName;
      StoreData(StoreFileName);
      ResultsFileName = StoreFileName;
      StoreFileNameLabel->Caption = StoreFileName;
      if(ResultsFileName.Pos(".") == 0) ResultsFileName  += ".res";
      else
      {
         int p = ResultsFileName.Pos(".");
         ResultsFileName.Delete(p, 100);
         ResultsFileName  += ".res";
      }
   }
}
//---------------------------------------------------------------------------
//==============================================================================
//    FIT part
//==============================================================================

void __fastcall TDataForm::StepFitBtnClick(TObject *Sender)
{
  foreg = DoReg(10);
  fo = foreg;
  fm = fo * 3;
  FitForm->Show();
  StepFitOn = true;
}

void __fastcall TDataForm::FitBtnClick(TObject *Sender)
{
  MemoPtr->Lines->Add("Fitting data");
  MemoPtr->Lines->Add("    ChiSq       Fo        Fm        Fv      Fv/Fm   Fv/Fo   Sig       p     Tau[0]  Tau[1]  Tau[5] Tau[10]     ");
  MemoPtr->Lines->Add("=============================================================================================================");
  StepFitOn = false;
  FitBtn->Enabled = false;
  MakeFitLift();                                //LIFT
  //MakeFitFRR(CyclePumpStart[0], CyclePumpEnd[0], CycleDecStart[0], CycleDecEnd[0], true);        //FRR
  FitBtn->Enabled = true;
}

void __fastcall TDataForm::ShowStatusFRR()
{
   AnsiString cc = "";
   char vv[32];
   FIT->Clear();
   CC->Clear();
   CHSEP->Clear();
   //int last_point = FitEnd;
   //if(last_point < nodata) last_point ++;
   //for(int i = FitStart; i < FitEnd; i++)
   FIT->Active = false;
   for (int i = FitStart - 1; i < FitEnd; i++)
   {
      if(TimeBase) FIT->AddXY(tim[i], fit[i], "", clTeeColor);
      else FIT->AddXY(i, fit[i], "", clTeeColor);
   }
   FIT->Active = true;
   FitChart->Update();
   Status();
   float del, del1;
   sprintf(vv, "%10.4f", ChiSq * 1000);   cc += vv;
   sprintf(vv, "%10.3f", fo);             cc += vv;
   sprintf(vv, "%10.3f", fm);             cc += vv;
   sprintf(vv, "%10.3f", fm - fo);        cc += vv;
   del = (fm - fo)/(fm + 0.000001);
   sprintf(vv, "%8.4f", del);             cc += vv;
   del1 = (fm - fo)/(fo + 0.000001);
   sprintf(vv, "%8.4f", del1);            cc += vv;
   sprintf(vv, "%8.2f", sig);             cc += vv;
   sprintf(vv, "%8.4f", p);               cc += vv;
    cc += " | ";
   if(NoTaus < 4) {alp[3] = 0; tau[3] = 0;}
   if(NoTaus < 3) {alp[2] = 0; tau[2] = 0;}
   if(NoTaus < 2) {alp[1] = 0; tau[1] = 0;}
   for(int i = 0; i < 4; i++)
   {
      sprintf(vv, "%8.4f",  alp[i]);      cc += vv;
      sprintf(vv, "%10.0f",  tau[i]);     cc += vv;
   }
   //cc += "\n";
   StoreRecord = cc;
   MemoPtr->Lines->Add(cc);
   if(FitDone) ResultsMemo->Lines->Add(cc);
}

void __fastcall TDataForm::ShowProgress(int ipstart, int ipend, float res, float tau)
{
  AnsiString cc = "";
  float del1;
  char vv[32];
  FIT->Clear();
  CC->Clear();
  CHSEP->Clear();
  FIT->Active = false;
  for(int i = ipstart; i < ipend; i++)
  {
     if(TimeBase) FIT->AddXY(tim[i], fit[i], "", clTeeColor);
     else FIT->AddXY(i, fit[i], "", clTeeColor);
  }
  FIT->Active = true;
  FitChart->Update();

  sprintf(text, "%f",res * 1000);
  ChisqEd->SetTextBuf(text);
  ChisqEd->Update();

  sprintf(text, "%8.2f",fm);
  FmEd->SetTextBuf(text);
  FmEd->Update();
  sprintf(text, "%8.2f",sig);
  SigEd->SetTextBuf(text);
  SigEd->Update();
  sprintf(text, "%6.4f",p);
  pEd->SetTextBuf(text);
  pEd->Update();


  sprintf(text, "%8.0f", tau);
  Alp0Ed->SetTextBuf(text);
  Alp0Ed->Update();
}

//---------------------------------------------------------------------------
void __fastcall TDataForm::ShowStatus()
{
  AnsiString cc = "";
  float del1;
  char vv[32];
  FIT->Clear();
  CC->Clear();
  CHSEP->Clear();
  FIT->Active = false;
  for(int i = 1; i < FitEnd; i++)
  {
     if(TimeBase) FIT->AddXY(tim[i], fit[i], "", clTeeColor);
     else FIT->AddXY(i, fit[i], "", clTeeColor);
  }
  FIT->Active = true;
  FitChart->Update();
  Status_B2C();
  float del;
  if (fm > fo) del = (fm - fo)/(fm + 0.00001);
  if (fm > fo) del1 = (fm - fo)/(fo + 0.00001);
  else del = 0;
  sprintf(vv, "%12.6f", ChiSq * 1000); cc += vv;
  sprintf(vv, "%10.2f",  fo);          cc += vv;
  sprintf(vv, "%10.2f",  fm);          cc += vv;
  sprintf(vv, "%10.2f",  (fm - fo));   cc += vv;
  sprintf(vv, "%8.4f",  del);          cc += vv;
  sprintf(vv, "%8.4f",  del1);         cc += vv;
  sprintf(vv, "%8.2f",  sig);          cc += vv;
  sprintf(vv, "%8.4f",  p);            cc += vv;
  //if(!fittingtau)
  {
    sprintf(vv, "%8.0f",  CycleTauReg[0]);        cc += vv;
    sprintf(vv, "%8.0f",  CycleTauReg[1]);        cc += vv;
    sprintf(vv, "%8.0f",  CycleTauReg[2]);        cc += vv;
    sprintf(vv, "%8.0f",  CycleTauReg[5]);        cc += vv;
    if(NoCycles > 10)   {sprintf(vv, "%8.0f",  CycleTauReg[10]);       cc += vv;}
    if(NoCycles > 15)   {sprintf(vv, "%8.0f",  CycleTauReg[15]);       cc += vv;}
    if(NoCycles > 20)   {sprintf(vv, "%8.0f",  CycleTauReg[20]);       cc += vv;}
    if(NoCycles > 30)   {sprintf(vv, "%8.0f",  CycleTauReg[30]);       cc += vv;}
    if(NoCycles > 40)   {sprintf(vv, "%8.0f",  CycleTauReg[40]);       cc += vv;}
    if(NoCycles > 50)   {sprintf(vv, "%8.0f",  CycleTauReg[50]);       cc += vv;}
    if(NoCycles > 60)   {sprintf(vv, "%8.0f",  CycleTauReg[60]);       cc += vv;}
  } if(NoCycles > 60)   {sprintf(vv, "%8.0f",  CycleTauReg[NoCycles]); cc += vv;}
  MemoPtr->Lines->Add(cc);
  if(FitDone) ResultsMemo->Lines->Add(cc);
  StoreRecord = cc;
}

void __fastcall TDataForm::ResetDel(float dd)
{
  //delfactor = 0.683;
  delfo   = dd * fo;
  delfm   = dd * fm;
  delsig  = dd * sig;
  delp    = dd;
  delC    = dd;
  for(int i = 0; i < NoTaus; i++)
  {
      deltau = tau[i] * dd;
      deltauFRR[i] = tau[i] * dd;
      deltauLift[i] = tau[i] * dd;
      delalp[i] = dd;
  }
  sprintf(text, "%10.4f",delfactor);   DelFactorEd->SetTextBuf(text);
}

void __fastcall TDataForm::ResetDelBtnClick(TObject *Sender)
{
  ResetDel(0.2);
}

void __fastcall TDataForm::ShowFitBtnClick(TObject *Sender)
{
  ChiSq = GetCRes(FitStart, FitEnd);
  fit[0] = fo;
  FIT->Clear();
  for(int i = FitStart; i < FitEnd ; i++)
  FIT->AddXY(tim[i], fit[i], "", clTeeColor);
  Status();
}
//---------------------------------------------------------------------------

float __fastcall TDataForm::FindMin(float x1, float x2, float x3, float y1, float y2, float y3)
{
  double a1, a2, a3, dder, r1, x0, lim, dleft, dright;
  lim =1e-20;
  dleft   = x2 - x1;
  dright  = x3 - x2;
  a1 = (x1-x2)*(x1-x3);
  a2 = (x2-x1)*(x2-x3);
  a3 = (x3-x1)*(x3-x2);
  float aa1 = fabs(a1);
  float aa2 = fabs(a2);
  float aa3 = fabs(a3);
  if ((aa1 <lim) || (aa2 <lim) || (aa3 <lim)) x0 = x2;
  else
  {
    dder = y1/a1 + y2/a2 + y3/a3;
    if (dder > 0)               //we have a minimum
    {
      if(dder == 0) dder = 1;
      x0 = 0.5*(y1*(x2+x3)/a1+y2*(x1+x3)/a2+y3*(x1+x2)/a3)/dder;
    }
    else
    {
      if((y3 < y2) && (y3 < y1)) x0 = x3;
      if((y1 < y2) && (y1 < y3)) x0 = x1;
      if((y2 < y1) && (y2 < y3)) x0 = x2;
    }
  }
  return x0;
}
//----------------------------------------------------------------------------



float __fastcall TDataForm::GetFoResFRR(float ffo, int i1, int i2)
{
  float ffv, np, cs, res, resid;
  int   nop;
  np = 1-p;
  nop = i2 - i1;
  if (nop == 0) nop = 1;
  ffv = fm - ffo;
  resid = 0;
  for(int ip = i1; ip < i2; ip++)
  {
    cs = c[ip];
    fit[ip] = ffo + ffv * cs * np/(1 - cs*p);
    res = fit[ip]-f[ip];
    if(weighted) resid += res*res/f[ip];
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}
//---------------------------------------------------------------------------

float __fastcall TDataForm::GetFmResFRR(float ffm, int i1, int i2)
{
  float cc, np, res, resid, ffv, dccc, alpsum, efactor, cs, texp;
  int nop, id, ip, dtlast, ic;
  nop = i2-i1;
  if (nop == 0) nop = 1;
  cs = c[i1 - 1];;
  np = 1 - p;
  resid = 0;
  ffv = ffm - fo;
  dtlast = 1.e10;
  for(ip = i1; ip < i2; ip++)
  {
    cs = c[ip];
    fit[ip] = fo + ffv * cs *np/(1 - cs * p);
    res = fit[ip] - f[ip];
    if(weighted) resid += res*res/f[ip];
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetSigResFRR(float ssig, float ccstart, int i1, int i2)
{
  float cc, np, res, resid, ffv, dccc, alpsum, efactor, cs;
  int nop, id, ip, dtlast, ic;
  nop = i2-i1;
  ccstart = c[i1 - 1];
  if (nop == 0) nop = 1;
  np = 1 - p;
  resid = 0;
  ffv = fm - fo;
  alpsum = 0;
  f[0] = fo;
  chsep[0] = 0;
  for(id = 0; id < NoTaus; id++) alpsum += alp[id];
  for(id = 0; id < NoTaus; id++)
  {
    alp[id] /= alpsum;
    als[id] = ccstart * alp[id];
  }
  dtlast = 1.e10;
  for(ip = i1; ip < i2; ip++)
  {
    cs = 0;
    for(id = 0; id < NoTaus; id++)
    {
      if(!(dt[ip] == dtlast))
      {
        efactor = dt[ip]/tau[id];
        if (efactor < 1.e-10) texp[id] = 0;
        else texp[id] = exp(-efactor);
      }
      als[id] = als[id] * texp[id];
      cs += als[id];
    }
    dtlast = dt[ip];
    dccc = ssig * excal[ip] * (1-cs)/(1-cs * p);
    chsep[ip] = chsep[ip-1] + dccc;
    cs += dccc;
    c[ip] = cs;
    fit[ip] = fo + ffv * cs *np/(1 - cs * p);
    for(id = 0; id < NoTaus; id++) als[id] += dccc*alp[id];
    res = fit[ip] - f[ip];
    if(weighted) resid += res*res/f[ip];
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetFmResLift(float ffm, float ccstart, int i1, int i2)
{
   float cc, np, res, resid, ffv, dccc, efactor, cs, dtlast, texp;
   int nop, id, ip, ip1, ip2, ic;
   nop = 0;
   np = 1 - p;
   resid = 0;
   ffv = ffm - fo;
   cs = 0;
   c[0] = ccstart;
   for(int icycle = i1; icycle < i2 + 1; icycle++)
   {
      ip1 = CycleStart[icycle] + 1;
      if(icycle == 0) ip1 = 1;
      cs = c[ip1 - 1];
      ip2 = CycleEnd[icycle + 1];
      float taus = CycleTau[icycle];
      for(ip = ip1; ip < ip2 + 1; ip++)
      {
         if(!(dt[ip] == dtlast))
         {
            efactor = dt[ip]/taus;
            if(efactor < 1.e-10) texp = 0;
            else texp = exp(-efactor);
         }
         if(ip > ip1) cs *= texp;
         dtlast = dt[ip];
         dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
         cs += dccc;
         c[ip] = cs;
         fit[ip] = fo + ffv * cs *np/(1 - cs * p);
         res = fit[ip] - f[ip];
         if(weighted) resid += res*res/f[ip];
         else resid += res*res/fAver;
         nop ++;
      }
   }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetfoResLift(float ffo, float ccstart, int i1, int i2)
{
   float cc, np, res, resid, ffv, dccc, efactor, cs, dtlast, texp;
   int nop, id, ip, ip1, ip2, ic;
   nop = 0;
   np = 1 - p;
   resid = 0;
   ffv = fm - ffo;
   cs = 0;
   c[0] = ccstart;
   for(int icycle = i1; icycle < i2 + 1; icycle++)
   {
      ip1 = CycleStart[icycle] + 1;
      if(icycle == 0) ip1 = 1;
      cs = c[ip1 - 1];
      ip2 = CycleEnd[icycle + 1];
      float taus = CycleTau[icycle];
      for(ip = ip1; ip < ip2 + 1; ip++)
      {
         if(!(dt[ip] == dtlast))
         {
            efactor = dt[ip]/taus;
            if(efactor < 1.e-10) texp = 0;
            else texp = exp(-efactor);
         }
         if(ip > ip1) cs *= texp;
         dtlast = dt[ip];
         dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
         cs += dccc;
         c[ip] = cs;
         fit[ip] = ffo + ffv * cs *np/(1 - cs * p);
         res = fit[ip] - f[ip];
         if(weighted) resid += res*res/f[ip];
         else resid += res*res/fAver;
         nop ++;
      }
   }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetSigResLift(float ssig, float ccstart, int i1, int i2)
{
   float cc, np, res, resid, ffv, dccc, efactor, cs, dtlast, texp;
   int nop, id, ip, ip1, ip2, ic;
   nop = 0;
   np = 1 - p;
   resid = 0;
   ffv = fm - fo;
   cs = 0;
   c[0] = ccstart;
   for(int icycle = i1; icycle < i2 + 1; icycle++)
   {
      ip1 = CycleStart[icycle] + 1;
      if(icycle == 0) ip1 = 1;
      cs = c[ip1 - 1];
      ip2 = CycleEnd[icycle + 1];
      float taus = CycleTau[icycle];
      for(ip = ip1; ip < ip2 + 1; ip++)
      {
         if(!(dt[ip] == dtlast))
         {
            efactor = dt[ip]/taus;
            if(efactor < 1.e-10) texp = 0;
            else texp = exp(-efactor);
         }
         if(ip > ip1) cs *= texp;
         dtlast = dt[ip];
         dccc = ssig * excal[ip] * (1-cs)/(1-cs * p);
         cs += dccc;
         c[ip] = cs;
         fit[ip] = fo + ffv * cs *np/(1 - cs * p);
         res = fit[ip] - f[ip];
         if(weighted) resid += res*res/f[ip];
         else resid += res*res/fAver;
         nop ++;
      }
   }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetCStartResFRR(float ccstart, int i1, int i2)
{
  float cc, np, res, resid, ffv, dccc, alpsum, efactor, cs;
  int nop, id, ip, dtlast;
  nop = i2-i1;
  if (nop == 0) nop = 1;
  c[i1-1] = ccstart;
  np = 1 - p;
  resid = 0;
  ffv = fm - fo;
  alpsum = 0;
  f[0] = fo;
  for(id = 0; id < NoTaus; id++) alpsum += alp[id];
  for(id = 0; id < NoTaus; id++)
  {
    alp[id] /= alpsum;
    als[id] = ccstart * alp[id];
  }
  dtlast = 1.e10;
  for(ip = i1; ip < i2; ip++)
  {
    cs = 0;
    for(id = 0; id < NoTaus; id++)
    {
      if(!(dt[ip] == dtlast))
      {
        efactor = dt[ip]/tau[id];
        if (efactor < 1.e-10) texp[id] = 0;
        else texp[id] = exp(-efactor);
      }
      als[id] = als[id] * texp[id];
      cs += als[id];
    }
    dtlast = dt[ip];
    dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
    cs += dccc;
    c[ip] = cs;
    fit[ip] = fo + ffv * cs *np/(1 - cs * p);
    for(id = 0; id < NoTaus; id++) als[id] += dccc*alp[id];
    res = fit[ip] - f[ip];
    if(weighted) resid += res*res/(f[ip] + 0.01);
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetpResFRR(float pp, float ccstart, int i1, int i2)
{
  float cc, np, res, resid, ffv, dccc, alpsum, efactor, cs;
  int nop, id, ip, dtlast, ic;
  nop = i2-i1;
  if (nop == 0) nop = 1;
  ccstart = c[i1 - 1];
  np = 1 - pp;
  resid = 0;
  ffv = fm - fo;
  alpsum = 0;
  for(id = 0; id < NoTaus; id++) alpsum += alp[id];
  for(id = 0; id < NoTaus; id++)
  {
    alp[id] /= alpsum;
    als[id] = ccstart * alp[id];
  }
  dtlast = 1.e10;
  for(ip = i1; ip < i2; ip++)
  {
    cs = 0;
    for(id = 0; id < NoTaus; id++)
    {
      if(!(dt[ip] == dtlast))
      {
        efactor = dt[ip]/tau[id];
        if (efactor < 1.e-10) texp[id] = 0;
        else texp[id] = exp(-efactor);
      }
      als[id] = als[id] * texp[id];
      cs += als[id];
    }
    dtlast = dt[ip];
    dccc = sig * excal[ip] * (1-cs)/(1-cs * pp);
    cs += dccc;
    c[ip] = cs;
    fit[ip] = fo + ffv * cs *np/(1 - cs * pp);
    for(id = 0; id < NoTaus; id++) als[id] += dccc*alp[id];
    res = fit[ip] - f[ip];
    if(weighted) resid += res*res/f[ip];
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}


float __fastcall TDataForm::GetpResLift(float p, float ccstart, int i1, int i2)
{
   float cc, np, res, resid, ffv, dccc, efactor, cs, dtlast, texp;
   int nop, id, ip, ip1, ip2, ic;
   nop = 0;
   np = 1 - p;
   resid = 0;
   ffv = fm - fo;
   cs = 0;
   c[0] = ccstart;
   for(int icycle = i1; icycle < i2 + 1; icycle++)
   {
      ip1 = CycleStart[icycle] + 1;
      if(icycle == 0) ip1 = 1;
      cs = c[ip1 - 1];
      ip2 = CycleEnd[icycle + 1];
      float taus = CycleTau[icycle];
      for(ip = ip1; ip < ip2 + 1; ip++)
      {
         if(!(dt[ip] == dtlast))
         {
            efactor = dt[ip]/taus;
            if(efactor < 1.e-10) texp = 0;
            else texp = exp(-efactor);
         }
         if(ip > ip1) cs *= texp;
         dtlast = dt[ip];
         dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
         cs += dccc;
         c[ip] = cs;
         fit[ip] = fo + ffv * cs *np/(1 - cs * p);
         res = fit[ip] - f[ip];
         if(weighted) resid += res*res/f[ip];
         else resid += res*res/fAver;
         nop ++;
      }
   }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetCResFRR(float ccstart, int i1, int i2)
{
  float cc, np, res, resid, ffv, dccc, alpsum, efactor, cs;
  int nop, id, ip, dtlast, ic;
  nop = i2-i1;
  if (nop == 0) nop = 1;
  np = 1 - p;
  resid = 0;
  ffv = fm - fo;
  alpsum = 0;
  ic = 0;
  for(id = 0; id < NoTaus; id++) alpsum += alp[id];
  for(id = 0; id < NoTaus; id++)
  {
    alp[id] /= alpsum;
    als[id] = ccstart * alp[id];
  }
  dtlast = 1.e10;
  der[0] = 0;
  for(ip = i1; ip < i2; ip++)
  {
    cs = 0;
    for(id = 0; id < NoTaus; id++)
    {
      if(!(dt[ip] == dtlast))
      {
        efactor = dt[ip]/tau[id];
        if (efactor < 1.e-10) texp[id] = 0;
        else texp[id] = exp(-efactor);
      }
      als[id] = als[id] * texp[id];
      cs += als[id];
    }
    dtlast = dt[ip];
    dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
    cs += dccc;
    c[ip] = cs;
    fit[ip] = fo + ffv * cs *np/(1 - cs * p);
    for(id = 0; id < NoTaus; id++) als[id] += dccc*alp[id];
    res = fit[ip] - f[ip];
    if(weighted) resid += res*res/f[ip];
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}


float __fastcall TDataForm::GetCRes(int i1, int i2)
{
  float cc, np, res, resid, ffv, dccc, efactor, texp, cs;
  int nop, ip, dtlast;
  nop = i2-i1;
  cs = c[i1];
  if(i1 == 1) cs = 0;
  if (nop == 0) nop = 1;
  np = 1 - p;
  resid = 0;
  ffv = fm - fo;
  dtlast = 1.e5;
  for(ip = i1; ip < i2 + 1; ip++)
  {
    if(!(dt[ip] == dtlast))
    {
      efactor = dt[ip]/(stau+ 1);
      if (efactor < 1.e-10) texp = 1;
      else texp = exp(-efactor);
    }
    if(ip > i1) cs *= texp;
    dtlast = dt[ip];
    dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
    cs += dccc;
    c[ip] = cs;
    fit[ip] = fo + ffv * cs *np/(1 - cs * p);
    res = fit[ip] - f[ip];
    if(ip == i1) res = 0;
    if(weighted) resid += res*res/(f[ip] + 0.01);
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetCResLift(float ccstart, int i1, int i2)
{
   float cc, np, res, resid, ffv, dccc, efactor, cs, dtlast, texp;
   int nop, id, ip, ip1, ip2, ic;
   nop = 0;
   np = 1 - p;
   resid = 0;
   ffv = fm - fo;
   cs = 0;
   c[0] = ccstart;
   for(int icycle = i1; icycle < i2 + 1; icycle++)
   {
      ip1 = CycleStart[icycle] + 1;
      if(icycle == 0) ip1 = 1;
      cs = c[ip1 - 1];
      ip2 = CycleEnd[icycle + 1];
      float taus = CycleTau[icycle];
      for(ip = ip1; ip < ip2 + 1; ip++)
      {
         if(!(dt[ip] == dtlast))
         {
            efactor = dt[ip]/taus;
            if(efactor < 1.e-10) texp = 0;
            else texp = exp(-efactor);
         }
         if(ip > ip1) cs *= texp;
         dtlast = dt[ip];
         dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
         cs += dccc;
         c[ip] = cs;
         fit[ip] = fo + ffv * cs *np/(1 - cs * p);
         res = fit[ip] - f[ip];
         if(weighted) resid += res*res/f[ip];
         else resid += res*res/fAver;
         nop ++;
      }
   }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetTauResLift(int ntau, float xtau, float ccstart)
{
   //Calculate trial distribution CycleTau[ ] based on selected  ntau,
   //Call GetCResLift
   int i1, i2, i3;
   float y1, y2, y3, a1, a2, a3, x0, y0, dder;
   bool ShapeOK;
   i1 = 0;
   i2 = int(AnalCycles/2);
   i3 = AnalCycles;
   a1 = (i1-i2)*(i1-i3);
   a2 = (i2-i1)*(i2-i3);
   a3 = (i3-i1)*(i3-i2);
   if(ntau == 0) y1 = xtau; else y1 = tau[0];
   if(ntau == 1) y2 = xtau; else y2 = tau[1];
   if(ntau == 2) y3 = xtau; else y3 = tau[2];
   for(int ic = 0; ic < AnalCycles + 1; ic ++)
      CycleTau[ic] = y1*(ic-i2)*(ic-i3)/a1+y2*(ic-i1)*(ic-i3)/a2+y3*(ic-i1)*(ic-i2)/a3;
   float aa1 = fabs(a1);
   float aa2 = fabs(a2);
   float aa3 = fabs(a3);
   dder = y1/a1 + y2/a2 + y3/a3;
   {
      if(dder == 0) dder = 1;
      x0 = 0.5*(y1*(i2+i3)/a1+y2*(i1+i3)/a2+y3*(i1+i2)/a3)/dder;
      y0 = y1*(x0-i2)*(x0-i3)/a1+y2*(x0-i1)*(x0-i3)/a2+y3*(x0-i1)*(x0-i2)/a3;
   }
   if((dder < 0) && (x0 > y3)) ShapeOK = true;
      else ShapeOK = false;
   return GetCResLift(ccstart, 0, AnalCycles);
}

float __fastcall TDataForm::GetTauResFRR(int ntau, float xtau, float ccstart, int i1, int i2)
{
  float cc, np, res, resid, ffv, dccc, alpsum, efactor, cs;
  int nop, id, ip, dtlast;
  nop = i2-i1;
  ccstart = c[i1 - 1];
  if (nop == 0) nop = 1;
  np = 1 - p;
  resid = 0;
  ffv = fm - fo;
  alpsum = 0;
  for(id = 0; id < NoTaus; id++) alpsum += alp[id];
  for(id = 0; id < NoTaus; id++)
  {
    alp[id] /= alpsum;
    als[id] = ccstart * alp[id];
  }
  dtlast = 1.e10;
  for(ip = i1; ip < i2; ip++)
  {
    cs = 0;
    for(id = 0; id < NoTaus; id++)
    {
      if(!(dt[ip] == dtlast))
      {
        if (id == ntau) efactor = dt[ip]/xtau;
          else efactor = dt[ip]/tau[id];
        if (efactor < 1.e-10) texp[id] = 1;
        else texp[id] = exp(-efactor);
      }
      als[id] = als[id] * texp[id];
      cs += als[id];
    }
    dtlast = dt[ip];
    dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
    cs += dccc;
    c[ip] = cs;
    fit[ip] = fo + ffv * cs *np/(1 - cs * p);
    for(id = 0; id < NoTaus; id++) als[id] += dccc*alp[id];
    res = fit[ip] - f[ip];
    if(weighted) resid += res*res/f[ip];
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetTauRes(float xtau, float ccstart, int i1, int i2)
{
  float cc, np, res, resid, ffv, dccc, efactor, texp, cs;
  int nop, ip, dtlast;
  nop = i2-i1;
  cs = ccstart;
  if(i1 == 1) cs = 0;
  if (nop == 0) nop = 1;
  np = 1 - p;
  resid = 0;
  ffv = fm - fo;
  dtlast = 1.e5;
  for(ip = i1; ip < i2 + 1; ip++)
  {
    if(!(dt[ip] == dtlast))
    {
      efactor = dt[ip]/(xtau+ 1);
      if (efactor < 1.e-10) texp = 1;
      else texp = exp(-efactor);
    }
    if(ip > i1) cs *= texp;
    dtlast = dt[ip];
    dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
    cs += dccc;
    c[ip] = cs;
    fit[ip] = fo + ffv * cs *np/(1 - cs * p);
    res = fit[ip] - f[ip];
    if(ip == i1) res = 0;
    if(weighted) resid += res*res/(f[ip] + 0.01);
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}

float __fastcall TDataForm::GetAlpResFRR(int nalp, float xalp, float ccstart, int i1, int i2)
{
  float cc, np, res, resid, ffv, dccc, alpsum, efactor, cs;
  int nop, id, ip, dtlast;
  float valp[4];
  nop = i2-i1;
  ccstart = c[i1 - 1];
  if (nop == 0) nop = 1;
  np = 1 - p;
  resid = 0;
  ffv = fm - fo;
  alpsum = 0;
  for(id = 0; id < NoTaus; id++)
  {
    if (id == nalp) valp[id] = xalp;
    else valp[id] = alp[id];
    alpsum += valp[id];
  }
  for(id = 0; id < NoTaus; id++)
  {
    valp[id] /= alpsum;
    als[id] = ccstart * valp[id];
  }
  dtlast = 1.e10;
  for(ip = i1; ip < i2; ip++)
  {
    cs = 0;
    for(id = 0; id < NoTaus; id++)
    {
      if(!(dt[ip] == dtlast))
      {
        efactor = dt[ip]/tau[id];
        if (efactor < 1.e-10) texp[id] = 1;
        else texp[id] = exp(-efactor);
      }
      als[id] = als[id] * texp[id];
      cs += als[id];
    }
    dtlast = dt[ip];
    dccc = sig * excal[ip] * (1-cs)/(1-cs * p);
    cs += dccc;
    c[ip] = cs;
    fit[ip] = fo + ffv * cs *np/(1 - cs * p);
    for(id = 0; id < NoTaus; id++) als[id] += dccc*valp[id];
    res = fit[ip] - f[ip];
    if(weighted) resid += res*res/(f[ip] + 0.01);
    else resid += res*res/fAver;
  }
  resid /= nop;
  return resid;
}

void __fastcall TDataForm::FitfoFRR()
{
  float xmin, xmax, xo, dx, delx, xc;
  float varr[100];
  float x[4], y[4];
  xo = fo;
  delx = delfo;
  if(StepFitOn)
  {
    xmin = xo - 2*delx;
    xmax = xo + 2*delx;
    if(xmin < 0.6 * foreg) xmin = 0.6 * foreg;
    if(xmax > 1.3 * foreg) xmax = 1.3 * foreg;
    dx = 0.01*(xmax - xmin);
    FitForm->VAR->Clear();
    FitForm->PTS->Clear();
    FitForm->CEN->Clear();
    for(int i = 0; i < 100; i++)
    {
      xc = xmin + i * dx;
      varr[i] = GetFoResFRR(xc, FitStart, FitEnd);
      FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
    }
  }
  x[1] = xo - delx;
  if(x[1] < 0.0001) x[1] = 0.0001;
  x[2] = xo;
  x[3] = xo + delx;
  FitForm->PTS->Clear();
  for(int i = 1; i < 4; i++)
  {
    y[i] = GetFoResFRR(x[i], FitStart, FitEnd);
    if (StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
  }
  while((y[1] < y[2]) && (x[1] > 0.1 * fm))
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      delfo *= MagicNumber;
      x[1] = x[1] - delfo;
      if(x[1] < 0.00001)
      {
         x[1] = 0.00001;
         break;
      }
      if (x[1] < 0.09 * fm) x[1] = 0.09 * fm;
      y[1] = GetFoResFRR(x[1], FitStart, FitEnd);
   }
   while((y[3] < y[2]) && (x[1] < 0.999 * fm))
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      delfo *= MagicNumber;
      x[3] = x[3] + delfo;
      if(x[3] > 0.9999 * fm) x[3] = 0.9999 * fm;
      y[3] = GetFoResFRR(x[3], FitStart, FitEnd);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if (x[0] < 0.1 * fm)   x[0] = 0.1 * fm;
   if (x[0] > 0.999 * fm ) x[0] = 0.999 * fm;
   y[0] = GetFoResFRR(x[0], FitStart, FitEnd);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   delfo /= MagicNumber;
   if (y[0] < ChiSq)
   {
      fo = x[0];
      ChiSq = y[0];
   }
   fit[0] = fo;
  if (delfo < DerValue * fo) delfo = DerValue* fo;
}



void __fastcall TDataForm::FitfmFRR()
{
  float xmin, xmax, xo, dx, delx, xc;
  float varr[100];
  float x[4], y[4];
  xo = fm;
  delx = delfm;
  if(StepFitOn)
  {
    xmin = xo - delx;
    xmax = xo + delx;
    //if(xmax > 5 * fo) xmax = 5 * fo;
    dx = 0.01*(xmax - xmin);
    FitForm->VAR->Clear();
    FitForm->PTS->Clear();
    FitForm->CEN->Clear();
    for(int i = 0; i < 100; i++)
    {
      xc = xmin + i * dx;
      varr[i] = GetFmResFRR(xc, FitStart, FitEnd);
      FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
    }
  }
  x[1] = xo - delx;
  if(x[1] < 0.00001) x[1] = 0.00001;
  x[2] = xo;
  x[3] = xo + delx;
  for(int i = 1; i < 4; i++)
  {
    y[i] = GetFmResFRR(x[i], FitStart, FitEnd);
    if(StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
  }
  while((y[1] < y[2]) && (x[1] > fo * 1.001))
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      delfm *= MagicNumber;
      x[1] = x[1] - delfm;
      if(x[1] < 0.00001)
      {
         x[1] = 0.00001;
         break;
      }
      if (x[1] < fo * 1.0001) x[1] = fo * 1.0001;
      y[1] = GetFmResFRR(x[1], FitStart, FitEnd);
   }
   while((y[3] < y[2]) && (x[1] < 10 * fo))
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      delfm *= MagicNumber;
      x[3] = x[3] + delfm;
      if(x[3] > 11 * fo) x[3] = 11 * fo;
      y[3] = GetFmResFRR(x[3], FitStart, FitEnd);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if (x[0] < 1.0001 * fo )   x[0] = 1.0001 * fo;
   if (x[0] > 10 * fo ) x[0] = 10 * fo;
   y[0] = GetFmResFRR(x[0], FitStart, FitEnd);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   delfm /= MagicNumber;
   if (y[0] < y[2])
   {
      fm = x[0];
      ChiSq = y[0];
   }
  if (delfm < DerValue * fm) delfm = DerValue * fm;
}

void __fastcall TDataForm::FitpLift()
{
   float xmin, xmax, xo, dx, delx, xc;
   float varr[100];
   float x[4], y[4];
   xo = p;
   delx = delp;
   if(StepFitOn)
   {
      xmin = xo - 2*delx;
      xmax = xo + 2*delx;
      if (xmin < 0)   xmin = 0;
      if (xmax > 0.9) xmax = 0.9;
      dx = 0.01*(xmax - xmin);
      FitForm->VAR->Clear();
      FitForm->PTS->Clear();
      FitForm->CEN->Clear();
      for(int i = 0; i < 100; i++)
      {
         xc = xmin + i * dx;
         varr[i] = GetpResLift(xc, CStart, 0, AnalCycles);
         FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
      }
   }
   x[1] = xo - delx;
   if (x[1] < 0) x[1] = 0;
   x[2] = xo;
   x[3] = xo + delx;
   for(int i = 1; i < 4; i++)
   {
      y[i] = GetpResLift(x[i], CStart, 0, AnalCycles);
      if(StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
   }
   while(y[1] < y[2])
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      delp *= MagicNumber;
      x[1] = x[1] - delp;
      if (x[1] < 0.00001)
      {
         x[1] = 0.00001;
         break;
      }
      y[1] = GetpResLift(x[1], CStart, 0, AnalCycles);
   }
   while((y[3] < y[2]) && (x[1] < 0.8))
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      delp *= MagicNumber;
      x[3] = x[3] + delp;
      if(x[3] > 0.8)
      {
         x[3] = 0.9;
         break;
      }
      y[3] = GetpResLift(x[3], CStart, 0, AnalCycles);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if (x[0] < 0.00001)   x[0] = 0.00001;
   if (x[0] > 0.8) x[0] = 0.8;
   y[0] = GetpResLift(x[0], CStart, 0, AnalCycles);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   delp /= MagicNumber;
   if (y[0] < ChiSq)
   {
      p = x[0];
      ChiSq = y[0];
   }
   if (delp < DerValue) delp = DerValue;
}

void __fastcall TDataForm::FitpFRR()
{
  float xmin, xmax, xo, dx, delx, xc;
  float varr[100];
  float x[4], y[4];
  xo = p;
  delx = delp;
  if(StepFitOn)
  {
    xmin = xo - 2*delx;
    xmax = xo + 2*delx;
    if (xmin < 0)   xmin = 0;
    if (xmax > 0.9) xmax = 0.9;
    dx = 0.01*(xmax - xmin);
    FitForm->VAR->Clear();
    FitForm->PTS->Clear();
    FitForm->CEN->Clear();
    for(int i = 0; i < 100; i++)
    {
      xc = xmin + i * dx;
      varr[i] = GetpResFRR(xc, CStart, FitStart, FitEnd);
      FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
    }
  }
  x[1] = xo - delx;
  if (x[1] < 0) x[1] = 0;
  x[2] = xo;
  x[3] = xo + delx;
  for(int i = 1; i < 4; i++)
  {
    y[i] = GetpResFRR(x[i], CStart, FitStart, FitEnd);
    if(StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
  }
  while(y[1] < y[2])
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      delp *= MagicNumber;
      x[1] = x[1] - delp;
      if (x[1] < 0.00001)
      {
         x[1] = 0.00001;
         break;
      }
      y[1] = GetpResFRR(x[1], CStart, FitStart, FitEnd);
   }
   while((y[3] < y[2]) && (x[1] < 0.8))
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      delp *= MagicNumber;
      x[3] = x[3] + delp;
      if(x[3] > 0.8)
      {
         x[3] = 0.9;
         break;
      }
      y[3] = GetpResFRR(x[3], CStart, FitStart, FitEnd);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if (x[0] < 0.00001)   x[0] = 0.00001;
   if (x[0] > 0.8) x[0] = 0.8;
   y[0] = GetpResFRR(x[0], CStart, FitStart, FitEnd);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   delp /= MagicNumber;
   if (y[0] < ChiSq)
   {
      p = x[0];
      ChiSq = y[0];
   }
   if (delp < DerValue) delp = DerValue;
}

void __fastcall TDataForm::FitfoLift()
{
   float xmin, xmax, xo, dx, delx, xc;
   float varr[100];
   float x[4], y[4];
   xo = fm;
   delx = delfm;
   if(StepFitOn)
   {
      xmin = xo - delx;
      xmax = xo + delx;
      //if(xmax > 5 * fo) xmax = 5 * fo;
      dx = 0.01*(xmax - xmin);
      FitForm->VAR->Clear();
      FitForm->PTS->Clear();
      FitForm->CEN->Clear();
      for(int i = 0; i < 100; i++)
      {
         xc = xmin + i * dx;
         varr[i] = GetfoResLift(xc, CStart, 0, AnalCycles);
         FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
      }
   }
   x[1] = xo - delx;
   if(x[1] < 0.00001) x[1] = 0.00001;
   x[2] = xo;
   x[3] = xo + delx;
   for(int i = 1; i < 4; i++)
   {
      y[i] = GetfoResLift(x[i], CStart, 0, AnalCycles);
      if(StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
   }
   while((y[1] < y[2]) && (x[1] > fo * 1.001))
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      delfm *= MagicNumber;
      x[1] = x[1] - delfm;
      if(x[1] < 0.00001)
      {
         x[1] = 0.00001;
         break;
      }
      if (x[1] < fo * 1.0001) x[1] = fo * 1.0001;
      y[1] = GetfoResLift(x[1], CStart, 0, AnalCycles);
   }
   while((y[3] < y[2]) && (x[1] < 10 * fo))
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      delfm *= MagicNumber;
      x[3] = x[3] + delfm;
      if(x[3] > 11 * fo) x[3] = 11 * fo;
      y[3] = GetfoResLift(x[3], CStart, 0, AnalCycles);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if (x[0] < 1.0001 * fo )   x[0] = 1.0001 * fo;
   if (x[0] > 10 * fo ) x[0] = 10 * fo;
   y[0] = GetfoResLift(x[0], CStart, 0, AnalCycles);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   delfm /= MagicNumber;
   if (y[0] < ChiSq)
   {
      fm = x[0];
      ChiSq = y[0];
   }
  if (delfm < DerValue * fm) delfm = DerValue * fm;
}

void __fastcall TDataForm::FitfmLift()
{
   float xmin, xmax, xo, dx, delx, xc;
   float varr[100];
   float x[4], y[4];
   xo = fm;
   delx = delfm;
   if(StepFitOn)
   {
      xmin = xo - delx;
      xmax = xo + delx;
      //if(xmax > 5 * fo) xmax = 5 * fo;
      dx = 0.01*(xmax - xmin);
      FitForm->VAR->Clear();
      FitForm->PTS->Clear();
      FitForm->CEN->Clear();
      for(int i = 0; i < 100; i++)
      {
         xc = xmin + i * dx;
         varr[i] = GetFmResLift(xc, CStart, 0, AnalCycles);
         FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
      }
   }
   x[1] = xo - delx;
   if(x[1] < 0.00001) x[1] = 0.00001;
   x[2] = xo;
   x[3] = xo + delx;
   for(int i = 1; i < 4; i++)
   {
      y[i] = GetFmResLift(x[i], CStart, 0, AnalCycles);
      if(StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
   }
   while((y[1] < y[2]) && (x[1] > fo * 1.001))
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      delfm *= MagicNumber;
      x[1] = x[1] - delfm;
      if(x[1] < 0.00001)
      {
         x[1] = 0.00001;
         break;
      }
      if (x[1] < fo * 1.0001) x[1] = fo * 1.0001;
      y[1] = GetFmResLift(x[1], CStart, 0, AnalCycles);
   }
   while((y[3] < y[2]) && (x[1] < 10 * fo))
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      delfm *= MagicNumber;
      x[3] = x[3] + delfm;
      if(x[3] > 11 * fo) x[3] = 11 * fo;
      y[3] = GetFmResLift(x[3], CStart, 0, AnalCycles);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if (x[0] < 1.0001 * fo )   x[0] = 1.0001 * fo;
   if (x[0] > 10 * fo ) x[0] = 10 * fo;
   y[0] = GetFmResLift(x[0], CStart, 0, AnalCycles);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   delfm /= MagicNumber;
   if (y[0] < ChiSq)
   {
      fm = x[0];
      ChiSq = y[0];
   }
  if (delfm < DerValue * fm) delfm = DerValue * fm;
}

void __fastcall TDataForm::FitSigLift()
{
   float xmin, xmax, xo, dx, delx, xc;
   float varr[100];
   float x[4], y[4];
   xo = sig;
   delx = delsig;
   if(StepFitOn)
   {
      xmin = xo - 2*delx;
      xmax = xo + 2*delx;
      dx = 0.01*(xmax - xmin);
      FitForm->VAR->Clear();
      FitForm->PTS->Clear();
      FitForm->CEN->Clear();
      for(int i = 0; i < 100; i++)
      {
         xc = xmin + i * dx;
         varr[i] = GetSigResLift(xc, CStart, 0, AnalCycles);
         FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
      }
   }
   x[1] = xo - delx;
   x[2] = xo;
   x[3] = xo + delx;
   if (x[1] < 20) x[1] = 20;
   for(int i = 1; i < 4; i++)
   {
      y[i] = GetSigResLift(x[i], CStart, 0, AnalCycles);
      if(StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
   }
   while(y[1] < y[2])
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      delsig *= MagicNumber;
      x[1] = x[1] - delsig;
      if (x[1] < 20)
      {
         x[1] = 20;
         break;
      }
      y[1] = GetSigResLift(x[1], CStart, 0, AnalCycles);
   }
   while(y[3] < y[2])
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      delsig *= MagicNumber;
      x[3] = x[3] + delsig;
      if(x[3] > 4000)
      {
         x[3] = 4000;
         break;
      }
      y[3] = GetSigResLift(x[3], CStart, 0, AnalCycles);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if (x[0] < 20)   x[0] = 20;
   if (x[0] > 4000) x[0] = 4000;
   y[0] = GetSigResLift(x[0], CStart, 0, AnalCycles);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   delsig /= MagicNumber;
   if (y[0] < ChiSq)
   {
      sig = x[0];
      ChiSq = y[0];
   }
   if (delsig < DerValue * sig) delsig = DerValue * sig;
}

void __fastcall TDataForm::FitsigFRR()
{
  float xmin, xmax, xo, dx, delx, xc;
  float varr[100];
  float x[4], y[4];
  xo = sig;
  delx = delsig;
  if(StepFitOn)
  {
    xmin = xo - 2*delx;
    xmax = xo + 2*delx;
    dx = 0.01*(xmax - xmin);
    FitForm->VAR->Clear();
    FitForm->PTS->Clear();
    FitForm->CEN->Clear();
    for(int i = 0; i < 100; i++)
    {
      xc = xmin + i * dx;
      varr[i] = GetSigResFRR(xc, CStart, FitStart, FitEnd);
      FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
    }
  }
  x[1] = xo - delx;
  x[2] = xo;
  x[3] = xo + delx;
  if (x[1] < 20) x[1] = 20;
  for(int i = 1; i < 4; i++)
  {
    y[i] = GetSigResFRR(x[i], CStart, FitStart, FitEnd);
    if(StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
  }
  while(y[1] < y[2])
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      delsig *= MagicNumber;
      x[1] = x[1] - delsig;
      if (x[1] < 20)
      {
         x[1] = 20;
         break;
      }
      y[1] = GetSigResFRR(x[1], CStart, FitStart, FitEnd);
   }
   while(y[3] < y[2])
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      delsig *= MagicNumber;
      x[3] = x[3] + delsig;
      if(x[3] > 4000)
      {
         x[3] = 4000;
         break;
      }
      y[3] = GetSigResFRR(x[3], CStart, FitStart, FitEnd);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if (x[0] < 20)   x[0] = 20;
   if (x[0] > 4000) x[0] = 4000;
   y[0] = GetSigResFRR(x[0], CStart, FitStart, FitEnd);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   delsig /= MagicNumber;
   if (y[0] < ChiSq)
   {
      sig = x[0];
      ChiSq = y[0];
   }
  if (delsig < DerValue * sig) delsig = DerValue * sig;
}

void __fastcall TDataForm::FitC()
{
  float xmin, xmax, xo, dx, delx, xc;
  float varr[100];
  float x[4], y[4];
  xo = CStart;
  delx = delC;
  if(StepFitOn)
  {
    xmin = xo - 2*delx;
    xmax = xo + 2*delx;
    dx = 0.01*(xmax - xmin);
    FitForm->VAR->Clear();
    FitForm->PTS->Clear();
    FitForm->CEN->Clear();
    for(int i = 0; i < 100; i++)
    {
      xc = xmin + i * dx;
      varr[i] = GetCStartResFRR(xc, FitStart, FitEnd);
      FitForm->VAR->AddXY(xc, varr[i],"", clTeeColor);
    }
  }
  x[1] = xo - delx;
  x[2] = xo;
  x[3] = xo + delx;
  if (x[1] < -0.01) x[1] = -0.01;
  if (x[3] > 1.0) x[3] = 1.0;
  for(int i = 1; i < 4; i++)
  {
    y[i] = GetCStartResFRR(x[i], FitStart, FitEnd);
    if(StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
  }
  x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
  x[0] = x[2] + Step * (x[0] - x[2]);
  if (x[0] < 0)   x[0] = 0;
  if (x[0] > 0.99) x[0] = 0.99;
  y[0] = GetCStartResFRR(x[0], FitStart, FitEnd);
  if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
  if (y[0] < chifact * ChiSq)
  {
    CStart = x[0];
    ChiSq = y[0];
    if ((x[0] > x[1]) && (x[0] < x[3])) delC *= delfactor;
    else
    {
      if(delC < 0.05) delC *= 2;
    }
  }
  else delC *= 0.5;
  if (delC < DerValue) delC = DerValue;
}

void __fastcall TDataForm::FitTauLift(int ntau)
{
   float xmin, xmax, xo, dx, delx, xc;
   float varr[100];
   float x[4], y[4];
   delx = deltauLift[ntau];
   xo = tau[ntau];
   if(StepFitOn)
   {
      xmin = xo - 2 * deltauLift[ntau];
      xmax = xo + 2 * deltauLift[ntau];
      if (xmin < 100)   xmin = 100;
      if (xmax > 9.0e8) xmax = 9.0e8;
      dx = 0.01*(xmax - xmin);
      FitForm->VAR->Clear();
      FitForm->PTS->Clear();
      FitForm->CEN->Clear();
      for(int i = 0; i < 100; i++)
      {
         xc = xmin + i * dx;
         varr[i] = GetTauResLift(ntau, xc, CStart);
         FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
      }
   }
   x[1] = xo - deltauLift[ntau];  y[1] = GetTauResLift(ntau, x[1], CStart);
   x[2] = xo;                     y[2] = GetTauResLift(ntau, x[2], CStart);
   x[3] = xo + deltauLift[ntau];  y[3] = GetTauResLift(ntau, x[3], CStart);
   while(y[1] < y[2])
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      deltauLift[ntau] *= MagicNumber;
      x[1] = x[1] - deltauLift[ntau];
      if (x[1] < 50)
      {
         x[1] = 50;
         break;
      }
      y[1] = GetTauResLift(ntau, x[1], CStart);
   }
   while(y[3] < y[2])
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      deltauLift[ntau] *= MagicNumber;
      x[3] = x[3] + deltauLift[ntau];
      if(x[3] > 9.0e8)
      {
         x[3] = 9.0e8;
         break;
      }
      y[3] = GetTauResLift(ntau, x[3], CStart);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if(x[0] < 60)    x[0] = 60;
   if(x[3] > 9.0e8) x[3] = 9.0e8;
   y[0] = GetTauResLift(ntau, x[0], CStart);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   deltauLift[ntau] /= MagicNumber;
   if (y[0] < ChiSq)
   {
      tau[ntau] = x[0];
      ChiSq = y[0];
   }
   if (deltauLift[ntau] < DerValue*tau[ntau]) deltauLift[ntau] = DerValue*tau[ntau];

}

void __fastcall TDataForm::FittauFRR(int ntau)
{
  float xmin, xmax, xo, dx, delx, xc;
  float varr[100];
  float x[4], y[4];
  delx = deltauFRR[ntau];
  xo = tau[ntau];
  if(StepFitOn)
  {
    xmin = xo - 2 * deltauFRR[ntau];
    xmax = xo + 2 * deltauFRR[ntau];
    if (xmin < 100)   xmin = 100;
    if (xmax > 9.0e8) xmax = 9.0e8;
    dx = 0.01*(xmax - xmin);
    FitForm->VAR->Clear();
    FitForm->PTS->Clear();
    FitForm->CEN->Clear();
    for(int i = 0; i < 100; i++)
    {
      xc = xmin + i * dx;
      varr[i] = GetTauResFRR(ntau, xc, CStart, FitStart, FitEnd);
      FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
    }
  }
   x[1] = xo - deltauFRR[ntau];  y[1] = GetTauResFRR(ntau, x[1], CStart, FitStart, FitEnd);
   x[2] = xo;                    y[2] = GetTauResFRR(ntau, x[2], CStart, FitStart, FitEnd);
   x[3] = xo + deltauFRR[ntau];  y[3] = GetTauResFRR(ntau, x[3], CStart, FitStart, FitEnd);
   while(y[1] < y[2])
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      deltauFRR[ntau] *= MagicNumber;
      x[1] = x[1] - deltauFRR[ntau];
      if (x[1] < 50)
      {
         x[1] = 50;
         break;
      }
      y[1] = GetTauResFRR(ntau, x[1], CStart, FitStart, FitEnd);
   }
   while(y[3] < y[2])
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      deltauFRR[ntau] *= MagicNumber;
      x[3] = x[3] + deltauFRR[ntau];
      if(x[3] > 9.0e8)
      {
         x[3] = 9.0e8;
         break;
      }
      y[3] = GetTauResFRR(ntau, x[3], CStart, FitStart, FitEnd);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if(x[0] < 60)    x[0] = 60;
   if(x[3] > 9.0e8) x[3] = 9.0e8;
   y[0] = GetTauResFRR(ntau, x[0], CStart, FitStart, FitEnd);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   deltauFRR[ntau] /= MagicNumber;
   if (y[0] < ChiSq)
   {
      tau[ntau] = x[0];
      ChiSq = y[0];
   }
   if (deltauFRR[ntau] < DerValue*tau[ntau]) deltauFRR[ntau] = DerValue*tau[ntau];
}

void __fastcall TDataForm::Fittau(int iterations)
{
  float delta, x, xnext, y, ynext, xx, yy;
  int dir, dirnext, steps;
  float eee;
  bool done = false;
  eee = 0.6180339 * 0.5;
  delta = deltau;
  x = stau;
  if(x < staulimit) x = staulimit;
  xnext = x + delta;
  dir = 1;  // try going right
  steps = 0;
  iter = 0;
  CStart = c[FitStart];
  y = GetTauRes(x, CStart, FitStart, FitEnd);
  while (delta > 0.001 * xnext)
  {
    xnext = x + dir * delta;
    if(xnext < staulimit) xnext = staulimit;
    if(xnext > 30000) xnext = 30000;
    ynext = GetTauRes(xnext, CStart, FitStart, FitEnd);
    iter ++;
    if (ynext < y)
    {
      x = xnext;
      y = ynext;
      ChiSq = ynext;
      delta *= 1.3333;
      //d /= eee;
    }
    else
    {
      dir *= -1;
      delta *= 0.3333;
      steps ++;
    }
  }
  ChiSq = y;
  stau = x;
  //ShowProgress(FitStart, FitEnd, y, x);
}



void __fastcall TDataForm::FitalpFRR(int nalp)
{
  float xmin, xmax, xo, dx, delx, xc;
  float varr[100];
  float x[4], y[4];
  delx = delalp[nalp];
  xo = alp[nalp];
  if(StepFitOn)
  {
    xmin = xo - 2*delx;
    xmax = xo + 2*delx;
    if (xmin < 0.0001)  xmin = 0.0001;
    if (xmax > 1.0)     xmax = 1.0;
    dx = 0.01*(xmax - xmin);
    FitForm->VAR->Clear();
    FitForm->PTS->Clear();
    FitForm->CEN->Clear();
    for(int i = 0; i < 100; i++)
    {
      xc = xmin + i * dx;
      varr[i] = GetAlpResFRR(nalp, xc, CStart, FitStart, FitEnd);
      FitForm->VAR->AddXY(xc, varr[i], "", clTeeColor);
    }
  }
  x[1] = xo - delx;
  x[2] = xo;
  x[3] = xo + delx;
  if (x[1] < 0.00001)   x[1] = 0.00001;
  if (x[2] > 1.0)       x[2] = 1.0;
  for(int i = 1; i < 4; i++)
  {
    y[i] = GetAlpResFRR(nalp, x[i], CStart, FitStart, FitEnd);
    if(StepFitOn) FitForm->PTS->AddXY(x[i], y[i], "", clTeeColor);
  }
  while(y[1] < y[2])
   {
      x[3] = x[2]; y[3] = y[2];
      x[2] = x[1]; y[2] = y[1];
      delalp[nalp] *= MagicNumber;
      x[1] = x[1] - delalp[nalp];
      if (x[1] < 0.00001)
      {
         x[1] = 0.00001;
         break;
      }
      y[1] = GetAlpResFRR(nalp, x[1], CStart, FitStart, FitEnd);
   }
   while(y[3] < y[2])
   {
      x[1] = x[2]; y[1] = y[2];
      x[2] = x[3]; y[2] = y[3];
      delalp[nalp] *= MagicNumber;
      x[3] = x[3] + delalp[nalp];
      if(x[3] > 0.99999)
      {
         x[3] = 0.99999;
         break;
      }
      y[3] = GetAlpResFRR(nalp, x[3], CStart, FitStart, FitEnd);
   }
   x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
   if (x[0] < 0.00001)   x[0] = 0.00001;
   if (x[0] > 1.0) x[0] = 1.0;
   y[0] = GetAlpResFRR(nalp, x[0], CStart, FitStart, FitEnd);
   if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
   delalp[nalp] /= MagicNumber;
   if (y[0] < ChiSq)
   {
      alp[nalp] = x[0];
      ChiSq = y[0];
   }
   if (delalp[nalp] < DerValue) delalp[nalp] = DerValue;
}

void __fastcall TDataForm::CalculateETR()
{
  float fv, np, cs, res, resid;
  int   nop;
  np = 1-p;
  fv = fm - fo;
  resid = 0;
  for(int ip = FitStart; ip < FitEnd; ip++)
  {
    cs = c[ip];
    fit[ip] = fo + fv * cs * np/(1 - cs*p);
    fit[ip] *= (cs * cfactor + 1);
    res = fit[ip]-f[ip];
    if(weighted) resid += res*res/f[ip];
    else resid += res*res/fAver;
  }
}



void __fastcall TDataForm::MakeFitFRR(int ippstart, int ippend, int idecstart, int idecend, bool QA)
{
   double fv;
   bool show = false;
   int ip;
   float ResetDelVal    = 0.2;
   float ResetDelFactor = 0.5;
   for(ip = idecend + 1; ip < idecend + 10; ip++) f[ip] = 1.0;
   if(delfactor < 0.1) delfactor = 0.1;
   MagicNumber = 1/delfactor;
   ResetDel(ResetDelVal);
   FitDone = false;
   Regress(ippstart,ippstart + 16, 2);
   foreg = fit[0];
   Regress(ippend - 16, ippend, 2);
   fmreg = fit[ippend];
   if(fofree) fo = foreg;
   if(fmfree) fm = fmreg;
   if(sigfree)
   {
      sig = 0;
      for(ip = 0; ip < ippend; ip++)
      {
         fv = fm - fo;
         if (fv > 0.001) sig += (fm - f[ip]) * excal[ip]/(fm - fo);
      }
      if (sig > 0) sig = 1/sig;
      else sig = 400;
   }
   sprintf(text, "%8.2f",foreg);
   FoEd->SetTextBuf(text);
   sprintf(text, "%8.2f",fmreg);
   FmEd->SetTextBuf(text);
   if (pfree) p = 0.2;
   ChiSq = 1.e10;
   if(FitStart == 1)CStart = 0;
   ChiSq = 1.e10;
   FitStart = ippstart;
   FitEnd   = ippend + 1;
   stau = 3000;
   for(iter = 1; iter < 10; iter ++)
   {
      GetCResFRR(0, FitStart, FitEnd);
      if (fmfree)  FitfmFRR();         if(show) ShowStatusFRR(); //Use single stau value
      if (sigfree) FitsigFRR();        if(show) ShowStatusFRR(); //Use single stau value
      if(fmod(iter,10) == 0)
      {
         //ShowStatusFRR();
         //GetCRes(FitStart, FitEnd);
      }
   }
   ChiSq = 1.e10;
   ResetDel(ResetDelVal);
   FitEnd = idecend + 1;
   for(iter = 1; iter < NoIter+1; iter ++)
   {
      //if(CSfree)  FitC();
      if(iter > 10)
      {
         GetCResFRR(0, FitStart, FitEnd);    if(show) ShowStatusFRR();
         if(fofree)  FitfoFRR();             if(show) ShowStatusFRR();
         if(fmfree)  FitfmFRR();             if(show) ShowStatusFRR();
         if(sigfree) FitsigFRR();            if(show) ShowStatusFRR();
         if(pfree)   FitpFRR();              if(show) ShowStatusFRR();
      }
      for(int id = 0; id < NoTaus; id++)
      {
         int ik = NoTaus - id - 1;
         if (taufree[ik])
         {
            FitalpFRR(ik);       if(show) ShowStatusFRR();
            FittauFRR(ik);       if(show) ShowStatusFRR();
         }
      }
      if(fmod(iter,20) == 0)
      {
         ResetDelVal *= ResetDelFactor;
         ShowStatusFRR();
         GetCResFRR(0, FitStart, FitEnd);
         ResetDel(ResetDelVal);
      }
   }
   iter = iter -1;
   FitDone = true;
   if(FileStoreAutoMode)
   {
      SaveResFRR(ResultsFileName);
      StoreData(StoreFileName);
   }
   ShowStatusFRR();
   PlotVars[PlotPoint][0] = fo;
   PlotVars[PlotPoint][1] = fm;
   PlotVars[PlotPoint][2] = fm - fo;
   PlotVars[PlotPoint][3] = (fm - fo)/fm;
   PlotVars[PlotPoint][5] = sig;
   PlotVars[PlotPoint][6] = p;
   PlotVars[PlotPoint][7] = alp[0];
   PlotVars[PlotPoint][8] = tau[0];
   PlotVars[PlotPoint][9] = alp[1];
   PlotVars[PlotPoint][10] = tau[1];
   PlotVars[PlotPoint][11] = alp[2];
   PlotVars[PlotPoint][12] = tau[2];
   PlotVars[PlotPoint][13] = alp[3];
   PlotVars[PlotPoint][14] = tau[3];

   for(int iplot = 0; iplot < 25; iplot ++)
   {
      if(plots[iplot].on)
      PLOTS[iplot]->AddXY(PlotPoint, PlotVars[PlotPoint][plots[iplot].var] * 100/plots[iplot].range, "", plots[iplot].color);
   }
   PlotPoints ++;
   PlotPoint ++;
   if(PlotPoint > PlotEnd)
   {
      PlotStart += PlotUpdate;
      PlotEnd   += PlotUpdate;
      DataChart->BottomAxis->SetMinMax(PlotStart, PlotEnd);
   }
}

float __fastcall TDataForm::GetArrayMin(float sigcent, float siggrid, float fmcent, float fmgrid, float pcent, float pgrid, int iterations)
{
  int isig, ifm, ip;
  int isigmin, ifmmin, ipmin;
  float pmin, sigmin, fmmin, staumin, staustart;
  for(isig = -3; isig < 4; isig ++)
      arrsig[3 + isig] = sigcent + isig * siggrid;
  for(ifm = -3; ifm < 4; ifm ++)
      arrfm[3 + ifm] = fmcent + ifm * fmgrid;
  for(ip = -3; ip < 4; ip ++)
      arrp[3 + ip] = pcent + ip * pgrid;

  minvalue = 1.e10;
  int isigleft = -3;
  int isigright = 3;
  if(!sigfree)        //just select a single sig
  {
    isigleft  = 0;
    isigright = 0;
  }
  int ifmleft = -3;
  int ifmright = 3;
  if(!fmfree)        //just select a single fm
  {
    ifmleft  = 0;
    ifmright = 0;
  }
  int ipleft = -3;
  int ipright = 3;
  if(!pfree)        //just select a single p
  {
    ipleft =  0;
    ipright = 0;
  }
  for(isig = isigleft; isig < isigright + 1; isig ++)
  for(ifm =  ifmleft;  ifm  < ifmright  + 1; ifm ++)
  for(ip =   ipleft;   ip < ipright     + 1; ip ++)
  {
    sig = arrsig[3 + isig];
    fm =  arrfm[3  + ifm];
    if(fm < 1.01 * fo) fm = 1.01 * fo;
    p  =  arrp[3   + ip];
    //sig = sigcent;
    //fm = fmcent;
    //p = pcent;
    if(p < 0) p = 0;
    ChisTot = 0;
    c[0] = 0;
    for(Cycle = 0; Cycle < AnalCycles; Cycle ++)
    {
      FitStart = CycleStart[Cycle];
      if(Cycle < AnalCycles) FitEnd   = CycleEnd[Cycle + 1];
         else FitEnd = CycleEnd[AnalCycles - 1];
      ChiSq = 1.e10;
      //if(norep < 4) stau = CycleTau[Cycle];
      //  else stau = CycleTauMin[Cycle];
      //stau = CycleTauMin[Cycle];
      //stau = CycleTauMin[Cycle];
      stau = CycleTau[Cycle];
      staustart = stau;
      deltau = deltatau * stau;
      ChiSq = 1.e10;
      Fittau(iterations);
      CycleTau_ToRegress[Cycle] = stau;
      //ShowProgress(FitStart, FitEnd, ChiSq, stau);
      stau = stau;
      //CycleTau_ToRegress[Cycle] = CycleTau[Cycle];
    }
// --------------- with regressed taus

    RegressTau(2);
    ChisTot = 0;
    //CycleTau_ToRegress[0]= 800;
    for(Cycle = 0; Cycle < AnalCycles; Cycle ++)
    {
      FitStart = CycleStart[Cycle];
      if(Cycle < AnalCycles) FitEnd   = CycleEnd[Cycle + 1];
         else FitEnd = CycleEnd[AnalCycles - 1];
      //stau = CycleTauReg[Cycle];
      stau = CycleTau_ToRegress[Cycle];
      ChiSq = GetCRes(FitStart, FitEnd);
      ChisTot += ChiSq;
      }

// --------------- end regressed tau section
    FitStart = 1;
    sprintf(text, "%8.2f",fm);
    FmEd->SetTextBuf(text);
    FmEd->Update();
    sprintf(text, "%8.2f",sig);
    SigEd->SetTextBuf(text);
    SigEd->Update();
    sprintf(text, "%6.4f",p);
    pEd->SetTextBuf(text);
    pEd->Update();
    sprintf(text, "%f",ChisTot * 1000);
    ChisqEd->SetTextBuf(text);
    ChisqEd->Update();
    //ShowStatus();
    if(ChisTot < minvalue)
    {
      minvalue = ChisTot;
      sigmin = sig;
      fmmin = fm;
      pmin = p;
      isigmin = isig;
      ifmmin = ifm;
      ipmin = ip;
      for(Cycle = 0; Cycle < AnalCycles; Cycle ++)
      //CycleTauMin[Cycle] = CycleTauReg[Cycle];
      CycleTauMin[Cycle] = CycleTau_ToRegress[Cycle];
      staumin = stau;
      //ShowProgress(FitStart, FitEnd, ChisTot, stau);
      stau = stau;
      //CycleTauMin[Cycle] = CycleTauReg[Cycle];
    }
  }
  sig = sigmin;
  fm  = fmmin;
  p   = pmin;

  for(Cycle = 0; Cycle < AnalCycles; Cycle ++)
  {
    FitStart = CycleStart[Cycle];
    if(Cycle < AnalCycles) FitEnd   = CycleEnd[Cycle + 1];
         else FitEnd = CycleEnd[AnalCycles - 1];
    stau = CycleTauMin[Cycle];
    ChiSq = GetCRes(FitStart, FitEnd);
  }
  ShowStatus();
  return minvalue;
}


void __fastcall TDataForm::MakeFitLift()
{
   float ChisAll, ChisFirst, foAll, foFirst, ResetDelVal;
   bool LowNoise, show = false;
   float ResetDelFactor = 0.5;
   if(AnalCycles > NoCycles -1) AnalCycles = NoCycles - 1;
   sigfree = SigFree->Checked;
   pfree = pFree->Checked;
   fmfree = FmFree->Checked;

   Regress(1, CycleEnd[AnalCycles - 1], 2);
   ChisAll = ChiSq;
   foAll = fit[0];
   ShowStatus();
   Regress(CycleStart[0],CycleEnd[0], 2);
   ChisFirst = ChiSq;
   foFirst = fit[0];
   fo = fit[0];
   fm = fit[CycleEnd[NoCycles - 1]];
   ShowStatus();
   if(ChisFirst < 0.05 * ChisAll) LowNoise = true;
   if(LowNoise) fo = foFirst;
   else fo = foAll;

   ResetDelVal = 0.2;
   ResetDel(ResetDelVal);
   FitStart = 1;
   FitEnd   = CycleEnd[AnalCycles - 1] + 1;
   show = false;
   ChiSq = GetTauResLift(0, tau[0], 0);  if(show) ShowStatusFRR();
   for(iter = 1; iter < 10; iter ++)
   {
      if (fmfree)  FitfmLift();           if(show) ShowStatusFRR();
      if (sigfree) FitSigLift();          if(show) ShowStatusFRR();
      {
         //ShowStatusFRR();
         //GetCRes(FitStart, FitEnd);
      }
   }
   ChiSq = 1.e10;
   ResetDel(0.2);
   for(iter = 1; iter < NoIter+1; iter ++)
   {
      if(iter > 10)
      {
         //if(fofree)  FitfoLift();            if(show) ShowStatusFRR();
         if(fmfree)  FitfmLift();            if(show) ShowStatusFRR();
         if(sigfree) FitSigLift();           if(show) ShowStatusFRR();
         //if(pfree)   FitpLift();             if(show) ShowStatusFRR();
         // p still ghas problems
      }

      for(int ntau = 0; ntau < 3; ntau++)
      {
         FitTauLift(ntau);
         if(show) ShowStatusFRR();
      }
      //---- Restore Correct Tau distribution
      GetTauResLift(0, tau[0], 0);           if(show) ShowStatusFRR();
      if(fmod(iter,20) == 0)
      {
         ResetDelVal *= ResetDelFactor;
         ShowStatusFRR();
         GetCResLift(0, 0, AnalCycles);
         ResetDel(ResetDelVal);
      }
   }
   iter = iter -1;
   FitDone = true;

}


void __fastcall TDataForm::MakeFit()
{
  float Chi, ChiLast;
  float sigcent, pcent, fmcent, siggrid, fmgrid, pgrid, rr;
  //AnalCycles = 10;
  FitDone = false;
  //AnalCycles = NoCycles - 1;
  Regress(1, CycleEnd[NoCycles - 1], 1);
  fo = fit[0];
  fm = fit[CycleEnd[NoCycles - 1]];
  ShowStatus();
  if(fm < fo * 1.1)
  {
     staulimit = 200;
     foreg = fit[0];
  }
  else
  {
      Regress(CycleStart[0],CycleEnd[0], 2);
      foreg = fit[0];
  }



  if(AnalCycles > NoCycles -1) AnalCycles = NoCycles - 1;
  for(int ic = 0; ic < AnalCycles; ic++)
  {
    CycleTau[ic] = 400 + ic * 100;
    if(CycleTau[ic] > 10000) CycleTau[ic] = 10000;
    CycleTauMin[ic] = CycleTau[ic];
  }
  norep = 0;
  sigfree = SigFree->Checked;
  pfree = pFree->Checked;
  fmfree = FmFree->Checked;
  Regress(CycleStart[NoCycles -1], CycleEnd[NoCycles - 1], 2);
  int fitlast = CycleEnd[NoCycles - 1];
  fmreg = fit[fitlast];
  if(fmreg < 1.02 * foreg) fmreg = 1.02 * fmreg;
  ResetDel(0.2);
  sigcent = sig;
  if(pfree) pcent = 0.3;
    else pcent = p;
  sigcent = 500;
  if(fmfree)
  {
      if(fmreg > 1.1 * foreg)
      {
         fmcent = foreg + 2 * (fmreg - foreg);
         fmgrid = 0.3 * (fmreg - foreg);
      }
      else
      {
         fmcent  = foreg * 1.2;
         fmgrid =  0.1 * foreg;
      }
  }
  else fmcent = fm;

  siggrid = sigcent * 0.2;
  pgrid = pcent/3.0;
  fittingtau = true;
  int iterations = NoIter;
  deltatau = 0.3;
//--DEBUG-----------
   //sigfree = false;
   //fmfree = false;
   //fmcent = 4500;
   //sigcent = 400;
   //fmgrid = 500;


//------------------

  Chi = GetArrayMin(sigcent, siggrid, fmcent, fmgrid, pcent, pgrid, iterations);
  if(sigindex == -3)
  {
    sigcent = sigcent - 4 * siggrid;
    siggrid = sigcent * 0.15;
    Chi = GetArrayMin(sigcent, siggrid, fmcent, fmgrid, pcent, pgrid, iterations);
  }
  else if(sigindex == 3)
  {
    sigcent = sigcent + 5 * siggrid;
    siggrid = sigcent * 0.2;
    Chi = GetArrayMin(sigcent, siggrid, fmcent, fmgrid, pcent, pgrid, iterations);
  }
  for(norep = 0; norep < 11; norep ++)
  {
     if(norep == 10) FitDone = true;
    //deltatau *= 0.9;
    deltatau *= 1.0;
    sigcent = sig;
    siggrid *= 0.4;
    fmcent  = fm;
    fmgrid *= 0.4;
    pcent = p;
    pgrid *= 0.4;
    if(pfree)
    {
      float pminus = pcent - 3 * pgrid;
      float pplus = pcent + 3 * pgrid - 0.8;
      if(pminus < 0) pcent -= pminus;
      if(pplus > 0)  pcent -= pplus;         //to kep p in 0.0 - 0.8 range
    }
    //iter = int(iter * 0.7);
    iterations = int(iterations * 1.0);
    //if (iter < 5) iter = 5;
    Chi = GetArrayMin(sigcent, siggrid, fmcent, fmgrid, pcent, pgrid, iterations);
/*
  MemoPtr->Lines->Add("------- Regressed Taus -------");
  for(Cycle = 0; Cycle < NoCycles; Cycle ++) CycleTau_ToRegress[Cycle] = CycleTauMin[Cycle];
  RegressTau(3);
  fittingtau = false;                       //operate with regressed taus
  siggrid = sigcent * 0.2;
  pgrid = pcent/5.0;
  fmgrid = 0.5/3.0 * (fmcent - foreg);

  for(int norep = 0; norep < 10; norep ++)
  {
    deltatau *= 0.7;
    sigcent = sig;
    siggrid *= 0.4;
    fmcent  = fm;
    fmgrid *= 0.4;
    pcent = p;
    pgrid *= 0.4;
    float pminus = pcent - 3 * pgrid;
    float pplus = pcent + 3 * pgrid - 0.8;
    if(pminus < 0) pcent -= pminus;
    if(pplus > 0)  pcent -= pplus;         //to kep p in 0.0 - 0.8 range
    Chi = GetArrayMin(sigcent, siggrid, fmcent, fmgrid, pcent, pgrid, iter);
  }
*/
  deltatau = 1.0;
   }
   PlotVars[PlotPoint][0] = fo;
   PlotVars[PlotPoint][1] = fm;
   PlotVars[PlotPoint][2] = fm - fo;
   PlotVars[PlotPoint][3] = (fm - fo)/fm;
   PlotVars[PlotPoint][5] = sig;
   PlotVars[PlotPoint][6] = p;
   PlotVars[PlotPoint][7] = CycleTauMin[0];
   PlotVars[PlotPoint][8] = CycleTauMin[1];
   PlotVars[PlotPoint][9] = CycleTauMin[2];
   PlotVars[PlotPoint][10] = CycleTauMin[5];
   PlotVars[PlotPoint][11] = CycleTauMin[10];
   PlotVars[PlotPoint][12] = CycleTauMin[15];
   PlotVars[PlotPoint][13] = CycleTauMin[20];
   PlotVars[PlotPoint][14] = CycleTauMin[30];
   PlotVars[PlotPoint][15] = CycleTauMin[40];
   PlotVars[PlotPoint][16] = CycleTauMin[50];
   PlotVars[PlotPoint][17] = CycleTauMin[60];
   PlotVars[PlotPoint][18] = CycleTauMin[NoCycles];

   for(int iplot = 0; iplot < 25; iplot ++)
   {
      if(plots[iplot].on)
      PLOTS[iplot]->AddXY(PlotPoint, PlotVars[PlotPoint][plots[iplot].var] * 100/plots[iplot].range, "", plots[iplot].color);
   }
   PlotPoints ++;
   PlotPoint ++;
   if(PlotPoint > PlotEnd)
   {
      PlotStart += PlotUpdate;
      PlotEnd   += PlotUpdate;
      DataChart->BottomAxis->SetMinMax(PlotStart, PlotEnd);
   }
   if(FileStoreAutoMode)
   {
      SaveResLIFT(ResultsFileName);
      if(Acquired_Data) StoreData(StoreFileName);
   }
}



float __fastcall TDataForm::GetCycleRes(float ffo, float ffm, float ssig, float pp)
{
  float fox, fmx, sigx, px;
  float Chi = 0;
  fox = fo; fmx = fm; sigx = sig; px = p;
  fo = ffo; fm = ffm; sig = ssig; p = pp;
  for(int ic = 0; ic < 2; ic ++)
  {
    FitStart = CycleStart[ic];
    FitEnd   = CycleEnd[ic];
    stau = CycleTau[ic];
    CStart = CycleC[ic];
    //GetCRes(FitStart, FitEnd);
    ChiSq = 1.e10;
    delC = 0.1 * CStart;
    for(iter = 1; iter < NoIter+1; iter ++)
    {
      FitC();
      if(fmod(iter,1) == 0) ShowStatus();
    }
    Chi += ChiSq;
  }
  sprintf(text, "%f",Chi * 1000000);
  ChisqEd->SetTextBuf(text);
  fo = fox; fm = fmx; sig = sigx, p = px;
  return Chi;
}

void __fastcall TDataForm::FitCyclefm()
{
  float xmin, xmax, xo, dx, delx, xc;
  float x[4], y[4];
  xo = fm;
  delx = delfm;
  GetCRes(FitStart, FitEnd);
  x[1] = xo - delx;
  x[2] = xo;
  x[3] = xo + delx;
  for(int i = 1; i < 4; i++) y[i] = GetCycleRes(fo, x[i], sig, p);
  x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
  x[0] = x[2] + Step * (x[0] - x[2]);
  y[0] = GetCycleRes(fo, x[0], sig, p);
  if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
  if (y[0] < chifact * ChiSqCycle)
  {
    fm = x[0];
    if(fm < 5 * fo) ChiSq = y[0];
    else
    {
      fm = 4.9 * fo;
      ChiSqCycle = GetCycleRes(fo, x[0], sig, p);
    }
    if ((x[0] > x[1]) && (x[0] < x[3])) delfm *= delfactor;
    else
    {
      if (delfm < 0.1 * fm) delfm *= 2;
    }
    if (delfm < DerValue * fm) delfm = DerValue * fm;
  }
  else delfm *= 0.5;
  if (delfm < DerValue * fm) delfm = DerValue * fm;
}

void TDataForm::FitCyclesig()
{
  float xmin, xmax, xo, dx, delx, xc;
  float x[4], y[4];
  xo = sig;
  delx = delsig;
  GetCRes(FitStart, FitEnd);
  x[1] = xo - delx;
  x[2] = xo;
  x[3] = xo + delx;
  for(int i = 1; i < 4; i++) y[i] = GetCycleRes(fo, fm, x[i], p);
  x[0] = FindMin(x[1], x[2], x[3], y[1], y[2], y[3]);
  x[0] = x[2] + Step * (x[0] - x[2]);
  y[0] = GetCycleRes(fo, fm, x[0], p);
  if(StepFitOn) FitForm->CEN->AddXY(x[0], y[0], "", clTeeColor);
  if (y[0] < chifact * ChiSqCycle)
  {
    sig = x[0];
    ChiSqCycle = y[0];
    if ((x[0] > x[1]) && (x[0] < x[3])) delsig *= delfactor;
    else
    {
      if (delsig < 0.1 * sig) delsig *= 2;
    }
    if (delsig < DerValue * sig) delsig = DerValue * sig;
  }
  else delsig *= 0.5;
  if (delsig < DerValue * sig) delsig = DerValue * sig;
}


void __fastcall TDataForm::SimulateBtnClick(TObject *Sender)
{
   Simulate(p, sig, CStart, FitStart, FitEnd);
   F->Clear();
   FIT->Clear();
   CC->Clear();
   REF->Clear();
   for(int i = 0; i < nodata + 1; i++)
   {
      f[i] = fs[i];
      if(TimeBase) F->AddXY(tim[i], f[i], "", clTeeColor);
      else  F->AddXY(i, f[i], "", clTeeColor);
   }
   FitChart->Update();
}
//---------------------------------------------------------------------------


void __fastcall TDataForm::Simulate(float pp, float ssig, float ccstart, int i1, int i2)
{
  float cc, np, res, ffv, dccc, alpsum, efactor, cs;
  int id, ip, dtlast;
  randomize();
  c[i1-1] = ccstart;
  np = 1 - pp;
  ffv = fm - fo;
  alpsum = 0;
  for(id = 0; id < NoTaus; id++) alpsum += alp[id];
  for(id = 0; id < NoTaus; id++)
  {
    alp[id] /= alpsum;
    als[id] = ccstart * alp[id];
  }
  dtlast = 1.e10;
  fAver = 0;
  for(ip = i1; ip < i2 + 1; ip++)
  {
    cs = 0;
    for(id = 0; id < NoTaus; id++)
    {
      if(fabs(dt[ip] - dtlast) > 0.01)
      {
        efactor = dt[ip]/tau[id];
        if (efactor < 1.e-10) texp[id] = 0;
        else texp[id] = exp(-efactor);
      }
      als[id] = als[id] * texp[id];
      cs += als[id];
    }
    dtlast = dt[ip];
    dccc = ssig * excal[ip] * (1-cs)/(1-cs * pp);
    cs += dccc;
    c[ip] = cs;
    fs[ip] = fo + ffv * cs *np/(1 - cs * pp);
    //f[ip] = f[ip]/fm;
    float rr =  0.00001 * random(100000) - 0.5;
    fs[ip] += fm * Noise * rr;
    fAver += f[ip];
    for(id = 0; id < NoTaus; id++) als[id] += dccc*alp[id];
  }
  fAver /= (i2 - i1);
  FitDone = false;
}

void __fastcall TDataForm::SaveParamBtnClick(TObject *Sender)
{
  fos = fo;
  fms = fm;
  sigs = sig;
  ps = p;
  NoTauss = NoTaus;
  for(int id = 0; id < 4; id++)
  {
    alps[id] = alp[id];
    taus[id] = tau[id];
  }
  FitStarts = FitStart;
  FitEnds = FitEnd;
  CStarts = CStart;
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::RestoreParamBtnClick(TObject *Sender)
{
  fo = fos;
  fm = fms;
  sig = sigs;
  ps = ps;
  NoTaus = NoTaus;
  for(int id = 0; id < 4; id++)
  {
    alp[id] = alps[id];
    tau[id] = taus[id];
  }
  FitStart = FitStarts;
  FitEnd = FitEnds;
  CStart = CStarts;
  Status();
}
//---------------------------------------------------------------------------

float __fastcall TDataForm::DoReg(int noreg)
{
  float sx, sxx, sy, sxy;
  sx = 0; sy = 0; sxy = 0; sxx = 0;
  for(int i = 1; i < noreg + 1; i++)
  {
    sx += i;
    sy += f[i];
    sxx += i * i;
    sxy += i * f[i];
  }
  float rr = sx*sx - noreg*sxx;
  if(rr > -0.0000001) rr = -0.0000001;
  float sa =( sx*sy - noreg*sxy)/rr;
  float sb =(sy - sa*sx)/noreg;
  fo = sb;
  fmreg = 0;
  for(int i = 0; i < 10; i ++) fmreg += f[100 - i];
  fmreg /= 10;
  return sb;
}

void __fastcall TDataForm::Invert(int dim)
{
	int i,j,k,l;
	double  save,amax;
  int     ik[13], jk[13];
  for(k=0; k<dim; k++)			//find the largest element in rest of the matrix
	{
		i = -1;
		j = -1;
    amax = 0;
    while (j < k)
		{
      while (i < k)
			{
        for(i=k; i<dim; i++)
				{
					for(j=k; j<dim; j++)
          {
            if(fabs(matrix[i][j]) > fabs(amax))
						{
							amax = matrix[i][j];
              ik[k] = i;
              jk[k] = j;
            }
          }
				}
        i = ik[k];
			}
      if(i > k)
      {
        for(j=0; j<dim; j++)
				{
          save = matrix[k][j];
          matrix[k][j] = matrix[i][j];
          matrix[i][j] = save;
        }
      }
      j = jk[k];
		}
    if(j > k)
    {
      for(i=0; i<dim; i++)
      {
        save = matrix[i][k];
        matrix[i][k] = matrix[i][j];
        matrix[i][j] = -save;
      }
    }
    for(i=0; i<dim; i++)
			if (!(i == k)) matrix[i][k] = -matrix[i][k]/(amax + 0.0001);
    for(i=0; i<dim; i++)
    {
      for(j=0; j<dim; j++)
      if((!(i == k)) && (!(j == k)))
				matrix[i][j] += matrix[i][k] * matrix[k][j];
    }
    for(j=0; j<dim; j++)
    if(!(j == k)) matrix[k][j] = matrix[k][j]/amax;
    matrix[k][k] = 1.0/amax;
	}
  for(l=0; l<dim; l++)
  {
    k = dim - l-1;
		j = ik[k];
    if(j > k)
		{
			for(i=0; i<dim; i++)
      {
				save = matrix[i][k];
				matrix[i][k] = -matrix[i][j];
				matrix[i][j] = save;
			}
		}
    i = jk[k];
    if(i > k)
		{
			for(j=0; j<dim; j++)
			{
				save = matrix[k][j];
				matrix[k][j] = -matrix[i][j];
				matrix[i][j] = save;
			}
    }
  }
}

void __fastcall TDataForm::Regress(int i1, int i2, int order)
{
  int ir, ic, ip;
  double bbx[10], aax[10][10], res;
  double matrold[10][10], result[10][10];
  float deltat;
  float rtim[2000] = {0};
  //if(i2 == nodata) i2 --;
  for(ip = i1; ip < i2 + 1; ip ++) rtim[ip] = tim[ip];
  deltat = rtim[i1 + 1] - rtim[i1];
  if(deltat < rtim[i1])
  {
    deltat = rtim[i1] - deltat;
    for(ip = i1; ip < i2 + 1; ip ++) rtim[ip]-= deltat;
  }
  for(ir = 0; ir < order + 1; ir ++)
  {
    bb[ir] = 0.0;
    bbx[ir] = 0.0;
    for(ic = 0; ic < order +1; ic ++)
    {
      matrix[ir][ic] = 0.0;
      aax[ir][ic] = 0.0;
    }
  }
  for(ip = i1; ip < i2 + 1; ip ++)
  {
    bbx[order] = f[ip];
    aax[order][order] = 1;
    for(ic = 1; ic < order + 1; ic ++)
      aax[order][order - ic] = aax[order][order -ic + 1] * rtim[ip];
    for(ir = 1; ir < order + 1; ir ++)
    {
      bbx[order - ir] = bbx[order - ir + 1] * rtim[ip];
      for(ic = 0; ic < order + 1; ic ++)
        aax[order - ir][order - ic] = aax[order - ir + 1][order - ic] * rtim[ip];
    }
    for(ir = 0; ir < order + 1; ir ++)
    {
      bb[ir] += bbx[ir];
      for(ic = 0; ic < order + 1; ic ++)
        matrix[ic][ir] += aax[ic][ir];
    }
  }

  for(ir = 0; ir < order + 1; ir ++)
  for(ic = 0; ic < order + 1; ic ++) matrold[ir][ic] = matrix[ir][ic];


  Invert(order + 1);
  for(ir = 0; ir < order + 1; ir ++)
  for(ic = 0; ic < order + 1; ic ++)
  {
    result[ir][ic] = 0.0;
    for(int k = 0; k < order + 1; k ++)
      result[ir][ic] += matrold[ir][k] *  matrix[k][ic];
  }

  for(ir = 0; ir < order + 1; ir ++)
  {
    coeff[ir] = 0;
    for(ic = 0; ic < order + 1; ic ++)
      coeff[ir] += matrix[ir][ic] * bb[ic];
  }
  ChiSq = 0;
  for(ip = i1; ip < i2 + 1; ip ++)
  {
    double alpha = 1;
    double beta = 1;
    fit[ip] = coeff[order];
    der[ip] = 0;
    for(ir = 1; ir < order + 1; ir ++)
    {
      alpha *= rtim[ip];                          //function power
      if(ir > 1) beta *= rtim[ip];                //derivative power
      fit[ip] += alpha * coeff[order - ir];
      der[ip] += ir * beta * coeff[order - ir];
    }
    res = f[ip] - fit[ip];
    if(weighted) ChiSq += res*res/(f[ip] + 0.01);
    else ChiSq += res*res/fAver;
  }
  for(ip = i1; ip < i2 + 1; ip ++)
  {
  }
  if(i1 == 1)
  {
    fo = coeff[order];
    fit[0] = coeff[order];
  }
}

void __fastcall TDataForm::RegressTau(int order)
{
  int ir, ic, ip;
  double bbx[10], aax[10][10], res;
  double matrold[10][10], result[10][10];
  float rtim[102] = {0};
  for(ip = 0; ip < NoCycles; ip ++) rtim[ip] = tim[CyclePump[ip]];
  for(ir = 0; ir < order + 1; ir ++)
  {
    bb[ir] = 0.0;
    bbx[ir] = 0.0;
    for(ic = 0; ic < order +1; ic ++)
    {
      matrix[ir][ic] = 0.0;
      aax[ir][ic] = 0.0;
    }
  }
  for(ip = 0; ip < NoCycles; ip ++)
  {
    bbx[order] = CycleTau_ToRegress[ip];
    aax[order][order] = 1;
    for(ic = 1; ic < order + 1; ic ++)
      aax[order][order - ic] = aax[order][order -ic + 1] * rtim[ip];
    for(ir = 1; ir < order + 1; ir ++)
    {
      bbx[order - ir] = bbx[order - ir + 1] * rtim[ip];
      for(ic = 0; ic < order + 1; ic ++)
        aax[order - ir][order - ic] = aax[order - ir + 1][order - ic] * rtim[ip];
    }
    for(ir = 0; ir < order + 1; ir ++)
    {
      bb[ir] += bbx[ir];
      for(ic = 0; ic < order + 1; ic ++)
        matrix[ic][ir] += aax[ic][ir];
    }
  }

  for(ir = 0; ir < order + 1; ir ++)
  for(ic = 0; ic < order + 1; ic ++) matrold[ir][ic] = matrix[ir][ic];


  Invert(order + 1);
  for(ir = 0; ir < order + 1; ir ++)
  for(ic = 0; ic < order + 1; ic ++)
  {
    result[ir][ic] = 0.0;
    for(int k = 0; k < order + 1; k ++)
      result[ir][ic] += matrold[ir][k] *  matrix[k][ic];
  }

  for(ir = 0; ir < order + 1; ir ++)
  {
    coeff[ir] = 0;
    for(ic = 0; ic < order + 1; ic ++)
      coeff[ir] += matrix[ir][ic] * bb[ic];
  }
  for(ip = 0; ip < NoCycles; ip ++)
  {
    double alpha = 1;
    double beta = 1;
    CycleTauReg[ip] = coeff[order];
    for(ir = 1; ir < order + 1; ir ++)
    {
      alpha *= rtim[ip];                          //function power
      CycleTauReg[ip] += alpha * coeff[order - ir];
    }
  }
}

void __fastcall TDataForm::RegressBtnClick(TObject *Sender)
{
  float fo1, fm1, fo2, fm2;
  int r1, r2, ip;
  if(Cycle == 100)
  {
    r1 = 1;
    r2 = nodata;
  }
  else
  {
    r1 = CycleStart[Cycle];
    r2 = CyclePump[Cycle];
  }
  if(r1 == 1)
  {
    FIT->Clear();
    CC->Clear();
    CHSEP->Clear();
  }
  Regress(r1, r2, RegressOrder);
  //fo1 = fit[r2] - foreg;
  fm1 = fit[r2] - foreg;
  sprintf(text, "%f",ChiSq * 1000000);
  ChisqEd->SetTextBuf(text);
  //------ Next Cycle
  r1 = CycleStart[Cycle + 1];
  r2 = CyclePump[Cycle + 1];
  Regress(r1, r2, RegressOrder);
  fo2 = fit[r1] - foreg;
  fm2 = fit[r2] - foreg;
  sprintf(text, "%10.2f",fo2);
  FoEd->SetTextBuf(text);
  sprintf(text, "%10.2f",fm1);
  FmEd->SetTextBuf(text);

  int p1 = CycleStart[Cycle];
  int p2 = CycleEnd[Cycle + 1];
  for(ip = p1; ip < p2; ip++)
  {
    FIT->AddXY(tim[ip], fit[ip], "", clTeeColor);
    CC->AddXY(tim[ip], der[ip] * 100, "", clTeeColor);
  }
  float t1 = dt[CycleStart[Cycle + 1]];
  float ttau = -t1/(log(fo2/fm1));

  for(ip = CycleStart[Cycle]; ip < CyclePump[Cycle] + 1; ip++)
  {
    derdel[ip] = der[ip] + (fit[ip]/fm2) * exp(-dt[ip]/ttau);
  }
}

void __fastcall TDataForm::RegressDecBtnClick(TObject *Sender)
{
  int r1, r2;
  if(Cycle == 100)
  {
    r1 = 1;
    r2 = nodata;
  }
  else
  {
    r1 = CyclePump[Cycle];
    r2 = CycleEnd[Cycle];
  }
  Regress(r1, r2, RegressOrder);
  int fstart = FitStart;
  if (!(Cycle == 100)) FitStart = CyclePump[Cycle];
  ShowStatus();
  FitStart = fstart;
}


void __fastcall TDataForm::SaveResLIFT(AnsiString FileName)
{
   AnsiString cc = "";
   char vv[20];
   bool NewFile = false;
   FILE* file;
   file = fopen(FileName.c_str(), "at");
   fseek(file, 0L, SEEK_END);
   if(ftell(file) == 0) NewFile = true;
   if(NewFile)
   {
      fputs("Filename                                                                  ChiSq         Fo        Fm        Fv     Fv/Fm   Fv/Fo     Sig       p     ", file);
      fputs("Tau(0)  Tau(1)  Tau(2)  Tau(5)  Tau(10) Tau(15) Tau(20) Tau(30) Tau(40) Tau(50)  Tau(60)  Taulast  Irrad  Temp\n", file);
      fputs("---------------------------------------------------------------------------------------------------------------------------", file);
      fputs("------------------------------------------------------------------------------------------------------------\n", file);
   }
   StoreFileIdName = StoreFileName;
   int p = StoreFileIdName.LastDelimiter("\\");
   if(p > 0) StoreFileIdName.Delete(1, p);
   if(StoreFileIdName == "") StoreFileIdName = "Source File unknown";
   cc = StoreFileIdName;
   cc.Delete(30,128);
   int len = cc.Length();
   for(int i = len; i < 32; i++) cc += " ";
   cc += DateTimeRecord +" | C00 "+StoreRecord;
   cc += "\n";
   fputs(cc.c_str(), file);
   fclose(file);
}

void __fastcall TDataForm::Save_Results_DlgClick(TObject *Sender)
{
   AnsiString FileName;
   if(FitDone)
   {
      SaveFileDlg->FileName = ResultsFileName;
      SaveFileDlg->Filter = "Result Data Files (*.res)|*.RES";
      if(SaveFileDlg->Execute())
      {
         FileName = SaveFileDlg->FileName;
         if(FileName.Pos(".res") == 0) FileName += ".res";
         //SaveResFRR(FileName);
         SaveResLIFT(FileName);
      }
   }
}

void __fastcall TDataForm::SaveResFRR(AnsiString FileName)
{
   AnsiString cc = "";
   char vv[20];
   bool NewFile = false;
   FILE* file;
   file = fopen(FileName.c_str(), "at");
   fseek(file, 0L, SEEK_END);
   if(ftell(file) == 0) NewFile = true;
   if(NewFile)
   {
      fputs("Filename                                                                   ", file);
      fputs("ChiSq       Fo        Fm        Fv    Fv/Fm   Fv/Fo    Sig      p     ", file);
      fputs("   Alp(1)    Tau(1)  Alp(2)    Tau(2)  Alp(3)    Tau(3)  Alp(4)    Tau(4) \n", file);
       fputs("---------------------------------------------------------------------------", file);
      fputs("-----------------------------------------------------------------", file);
      fputs("------------------------------------------------------------------------------\n", file);
   }
   StoreFileIdName = StoreFileName;
   int p = StoreFileIdName.LastDelimiter("\\");
   if(p > 0) StoreFileIdName.Delete(1, p);
   if(StoreFileIdName == "") StoreFileIdName = "Source File unknown";
   cc = StoreFileIdName;
   cc.Delete(30,128);
   int len = cc.Length();
   for(int i = len; i < 32; i++) cc += " ";
   cc += DateTimeRecord +" | C00 "+StoreRecord;
   cc += "\n";
   fputs(cc.c_str(), file);
   fclose(file);
}


void __fastcall TDataForm::Read_Data_DlgClick(TObject *Sender)
{
   AnsiString cc, cv;
   char line[80];
   bool FileDone = false;
   OpenFileDialog->FileName = StoreFileName;
   OpenFileDialog->Filter = "FRR Data Files (*.*)|*.*";
   fAver = 0;
   Acquired_Data = false;
   OpenFileDialog->Options<<ofFileMustExist;
   if(OpenFileDialog->Execute())
   {
      if(OpenFileDialog->FileName.Pos(".res") == 0)
      {
         FirstPassDone = false;
         FILE* ascfile;
         ascfile = fopen(OpenFileDialog->FileName.c_str(), "r");
         while (!FileDone)
         {
            fgets(line, 80, ascfile);
            fgets(line, 80, ascfile);
            fgets(line, 80, ascfile);
            fgets(line, 80, ascfile);
            int id = 0;
            do
            {
               cc.Delete(1, 100);
               fgets(line, 80, ascfile);
               cc.Insert(line, 1);
               if(!(cc == "----"))
               {
                  cv = cc.SubString(6,  10);
                  tim[id] = atof(cv.c_str());
                  cv = cc.SubString(17, 10);
                  excal[id]  = atof(cv.c_str());
                  excal[id] *= 1.e-6;
                  cv = cc.SubString(27, 10);
                  f[id]  = atof(cv.c_str());
                  fAver += f[id];
                  cv = cc.SubString(37, 10);
                  fit[id]  = atof(cv.c_str());
               id ++;
               }
            } while (!feof(ascfile) && !(cc == "----\n"));
            nodata = id - 1;
            fAver /= nodata;
            if(cc == "----\n") nodata -= 1;
            float deltat = tim[2] - tim[1];
            if(!(tim[1] == deltat))
            {
               deltat = tim[1] - deltat;
               for(id = 1; id < nodata + 1; id++)
               tim[id] -= deltat;
            }
            dt[0] = 0;
            for(id = 1; id < nodata + 1; id++) dt[id] = tim[id]-tim[id-1];
            FitStart = 1;
            FitEnd   = nodata;
            MemoPtr->Lines->Add(OpenFileDialog->FileName);
            FIT->Clear();
            CC->Clear();
            F->Clear();
            Profile->Clear();
            REF->Clear();
            FitChart->Update();
            //corr->Clear();
            //corr1->Clear()
            fAver = 0;
            for (int i = 1; i < nodata + 1; i++)
            {
               fAver += f[i];
               //dt[id] = tim[i] - tim[i - 1];
               if(TimeBase) F->AddXY(tim[i], f[i],"", clTeeColor);
               else F->AddXY(i, f[i], "", clTeeColor);
            }
            fAver /= (nodata -1);
            DataForm->Show();
            FitSheet->Show();
            //ExLenParsed = false;
            FitDone = false;
            FindCycle();
            if(feof(ascfile) || !FileStoreAutoMode) FileDone = true;
            if(FileStoreAutoMode) FitBtnClick(this);
         }
         fclose(ascfile);
      }
      else ShowMessage(OpenFileDialog->FileName + "\n" + AnsiString(" is not a FRR raw data file"));
   }
}

void __fastcall TDataForm::Read_Results_DlgClick(TObject *Sender)
{
   AnsiString Line;
   AnsiString stoken[40], sss;
   int RecNo, pstart, pend, TokenIndex, VarIndex, Linelen, iline, nolines, itoken;
   int VarTokenFirst = 6;        //First valid data token, ;
   int TokenLast;
   OpenFileDialog->FileName = ResultsFileName;
   OpenFileDialog->Options<<ofFileMustExist;
   OpenFileDialog->Filter = "Result Data Files (*.res)|*.RES";
   if(DataForm->OpenFileDialog->Execute())
   {
      ResultsMemo->Lines->LoadFromFile(DataForm->OpenFileDialog->FileName);
   }
   nolines   = ResultsMemo->Lines->Count;
   NoRecords = nolines - 2;
   RecNo = 0;
   for(iline = 2; iline < nolines; iline ++)
   {
      for(int i = 0; i < 40; i++) stoken[i] = "";
      Line = ResultsMemo->Lines->Strings[iline];
      Linelen = Line.Length();
      TokenIndex = 0;
      pstart = 1;
      do
      {
         while(Line.SubString(pstart,1) == ' ') pstart ++;
         sss = "";
         pend = pstart;
         while(!(Line.SubString(pend,1) == ' ') && (pend < Linelen + 1))
         {
            sss += Line.SubString(pend,1);
            pend ++;
         }
         pstart = pend;
         if(!(sss == "|"))          //Valid tokens
         {
            stoken[TokenIndex] = sss;
            TokenIndex ++;
         }
      }while (pend < Linelen);
      TokenLast = TokenIndex;
      VarIndex = TokenIndex - VarTokenFirst;
      if(VarIndex >=0)
      {
         for(itoken = VarTokenFirst; itoken < TokenLast; itoken ++)
         PlotVars[RecNo][itoken - VarTokenFirst] = atof(stoken[itoken].c_str());
      }
      RecNo ++;
   }
   NoPlotVariables = TokenIndex;
   PlotPoints = RecNo;
   for(int iRec = 0; iRec < RecNo; iRec ++)
   {
      for(int iplot = 0; iplot < 25; iplot ++)
      {
         if(plots[iplot].on)
         PLOTS[iplot]->AddXY(iRec, PlotVars[iRec][plots[iplot].var] * 100/plots[iplot].range, "", plots[iplot].color);
      }
   }
   PlotPoint = PlotPoints + 1;
}

void __fastcall TDataForm::View_Data_DlgClick(TObject *Sender)
{
   OpenFileDialog->FileName = StoreFileName;
   OpenFileDialog->Options<<ofFileMustExist;
   OpenFileDialog->Filter = "Raw Data Files";
   if(DataForm->OpenFileDialog->Execute())
   {
      if(OpenFileDialog->FileName.Pos(".res") == 0)
      {
         RawDataMemo->Lines->LoadFromFile(DataForm->OpenFileDialog->FileName);
      }
      else ShowMessage(OpenFileDialog->FileName + "\n" + AnsiString(" is not a FRR raw data file"));
   }
}

void __fastcall TDataForm::DeleteFileDlgClick(TObject *Sender)
{
   OpenFileDialog->Title = "Deleting Files";
   OpenFileDialog->Options<<ofAllowMultiSelect;
   if(OpenFileDialog->Execute())
   {
   }
   OpenFileDialog->Title = "OPEN";
   OpenFileDialog->Options.Clear();
}

void __fastcall TDataForm::FindCycle()
{
  float dtprev, discr;
  int ip;
  int ic = 0;
  NoCycles = 0;
  CycleStart[ic] = 1;
  cindex[1] = 0;
  discr = 50;
  for(ip = 2; ip < nodata +1; ip ++)
  {
    if((dt[ip - 1] < discr) && (dt[ip] > discr)) CyclePump[ic] = ip - 1;
    if((dt[ip - 1] < discr) && (dt[ip] > discr))
    {
      CycleEnd[ic] = ip - 1;
      ic ++;
      CycleStart[ic] = ip;
    }
    cindex[ip] = ic;
  }
  CycleEnd[ic] = nodata;
  NoCycles = ic + 1;
  AnalCycles = NoCycles - 1;
  sprintf(text, "%3i", AnalCycles);
  CycleNoEd->SetTextBuf(text);
  CycleNoEd->Update();
}


//---------------------------------------------------------------------------




//===================================================
//  FIT data entry
//===================================================

void __fastcall TDataForm::CycleNoEdChange(TObject *Sender)
{
   AnalCycles = atoi(CycleNoEd->Text.c_str());
}

void __fastcall TDataForm::FoEdChange(TObject *Sender)
{
  fo = atof(FoEd->Text.c_str());
}
void __fastcall TDataForm::FmEdChange(TObject *Sender)
{
  fm = atof(FmEd->Text.c_str());
}
void __fastcall TDataForm::SigEdChange(TObject *Sender)
{
  sig = atof(SigEd->Text.c_str());
}
void __fastcall TDataForm::pEdChange(TObject *Sender)
{
  p = atof(pEd->Text.c_str());
}

void __fastcall TDataForm::Alp0EdChange(TObject *Sender)
{
  alp[0] = atof(Alp0Ed->Text.c_str());
}
void __fastcall TDataForm::Alp1EdChange(TObject *Sender)
{
  alp[1] = atof(Alp1Ed->Text.c_str());
}
void __fastcall TDataForm::Alp2EdChange(TObject *Sender)
{
  alp[2] = atof(Alp2Ed->Text.c_str());
}
void __fastcall TDataForm::Alp3EdChange(TObject *Sender)
{
  alp[3] = atof(Alp3Ed->Text.c_str());
}
void __fastcall TDataForm::Tau0EdChange(TObject *Sender)
{
  stau = atof(Tau0Ed->Text.c_str());
}
void __fastcall TDataForm::Tau1EdChange(TObject *Sender)
{
  tau[1] = atof(Tau1Ed->Text.c_str());
}
void __fastcall TDataForm::Tau2EdChange(TObject *Sender)
{
  tau[2] = atof(Tau2Ed->Text.c_str());
}
void __fastcall TDataForm::Tau3EdChange(TObject *Sender)
{
  tau[3] = atof(Tau3Ed->Text.c_str());
}
void __fastcall TDataForm::ExPowerEdChange(TObject *Sender)
{
   float ExPowerLast, ExPowerEntered;
   ExPowerEntered = atof(ExPowerEd->Text.c_str());
   if(ExPowerEntered > 1.0)
   {
      ExPowerLast = ExPower;
      ExPower = ExPowerEntered;
      for(int i = 1; i < nodata; i++) excal[i] *= ExPower/ExPowerLast;
   }
}

void __fastcall TDataForm::IrradEdChange(TObject *Sender)
{
  Irrad = atof(IrradEd->Text.c_str());
}
void __fastcall TDataForm::CStartEdChange(TObject *Sender)
{
  CStart = atof(CStartEd->Text.c_str());
}
void __fastcall TDataForm::CStartFreeClick(TObject *Sender)
{
  CSfree = CStartFree->Checked;
}

void __fastcall TDataForm::NoTausEdChange(TObject *Sender)
{
  NoTaus = atoi(NoTausEd->Text.c_str());
  alp[0] = 0.5;
  alp[1] = 0.5;
  alp[2] = 0.2;
  alp[3] = 0.1;
  tau[0] = 400;
  tau[1] = 1000;
  tau[2] = 2000;
  tau[3] = 30000;
  stau = 1000;
  Status();
  if (!FitForm == NULL) FitForm->SelectButtons();
}
void __fastcall TDataForm::NoIterEdChange(TObject *Sender)
{
  NoIter = atoi(NoIterEd->Text.c_str());
}

void __fastcall TDataForm::DelFactorEdChange(TObject *Sender)
{
  delfactor = atof(DelFactorEd->Text.c_str());
}
void __fastcall TDataForm::DerValueEdChange(TObject *Sender)
{
  DerValue = atof(DerValueEd->Text.c_str());
}
void __fastcall TDataForm::NoiseEdChange(TObject *Sender)
{
  Noise = atof(NoiseEd->Text.c_str());
}
void __fastcall TDataForm::FoFreeClick(TObject *Sender)
{
  fofree = FoFree->Checked;
}
void __fastcall TDataForm::FmFreeClick(TObject *Sender)
{
  fmfree = FmFree->Checked;
}
void __fastcall TDataForm::SigFreeClick(TObject *Sender)
{
  sigfree = SigFree->Checked;
}
void __fastcall TDataForm::pFreeClick(TObject *Sender)
{
  pfree = pFree->Checked;
}
void __fastcall TDataForm::Tau0FreeClick(TObject *Sender)
{
  taufree[0] = Tau0Free->Checked;
}
void __fastcall TDataForm::Tau1FreeClick(TObject *Sender)
{
  taufree[1] = Tau1Free->Checked;
}
void __fastcall TDataForm::Tau2FreeClick(TObject *Sender)
{
  taufree[2] = Tau2Free->Checked;
}
void __fastcall TDataForm::Tau3FreeClick(TObject *Sender)
{
  taufree[3] = Tau3Free->Checked;
}
void __fastcall TDataForm::WeightedClick(TObject *Sender)
{
  weighted = Weighted->Checked;
}
void __fastcall TDataForm::RegrOrdEdChange(TObject *Sender)
{
  RegressOrder = atoi(RegrOrdEd->Text.c_str());
  if(RegressOrder < 1) RegressOrder = 1;
}



//======== SIMULATION INTERFACE =========

void __fastcall TDataForm::SeparateUnitsBtnClick(TObject *Sender)
{
  SimForm->SepUnits =   SeparateUnitsBtn->Checked;
  SimForm->Restricted = RestrictedTransferBtn->Checked;
  SimForm->Lake =       LakeBtn->Checked;
  SimForm->Puddle =     PuddleBtn->Checked;
}
void __fastcall TDataForm::RateModelBtnClick(TObject *Sender)
{
  SimForm->RateModel = RateModelBtn->Checked;
  SimForm->BipModel = ButlerModelBtn->Checked;
  kpEd->Visible =  SimForm->BipModel;
  klEd->Visible =  SimForm->BipModel;
  kfEd->Visible =  SimForm->BipModel;
  ktoEd->Visible = SimForm->RateModel;
  kboEd->Visible = SimForm->RateModel;
  ktcEd->Visible = SimForm->RateModel;
  kbcEd->Visible = SimForm->RateModel;
  klrcEd->Visible = SimForm->RateModel;
}
void __fastcall TDataForm::TwoStepTrBtnClick(TObject *Sender)
{
  SimForm->TwoStep = TwoStepTrBtn->Checked;
  SimForm->FiveStep = FiveStepTrBtn->Checked;
  TauQAPQEd->Visible =  SimForm->TwoStep;
  TauQAQBEd->Visible =  SimForm->FiveStep;
  TauQAQB2Ed->Visible = SimForm->FiveStep;
  TauQB2PQEd->Visible = SimForm->FiveStep;
  TauAssEd->Visible   = SimForm->FiveStep;
}

void __fastcall TDataForm::TauQAPQEdChange(TObject *Sender)
{
  SimForm->TauQAPQ = atof(TauQAPQEd->Text.c_str());
}
void __fastcall TDataForm::TauPQEdChange(TObject *Sender)
{
  SimForm->TauPQ = atof(TauPQEd->Text.c_str());
}
void __fastcall TDataForm::TauQAQBEdChange(TObject *Sender)
{
  SimForm->TauQAQB = atof(TauQAQBEd->Text.c_str());
}
void __fastcall TDataForm::TauQAQB2EdChange(TObject *Sender)
{
  SimForm->TauQAQB2 = atof(TauQAQB2Ed->Text.c_str());
}
void __fastcall TDataForm::TauQB2PQEdChange(TObject *Sender)
{
  SimForm->TauQB2PQ = atof(TauQB2PQEd->Text.c_str());
}
void __fastcall TDataForm::TauAssEdChange(TObject *Sender)
{
  SimForm->TauAss = atof(TauAssEd->Text.c_str());
}
void __fastcall TDataForm::NoRCEdChange(TObject *Sender)
{
  SimForm->NoRC = atoi(NoRCEd->Text.c_str());
}
void __fastcall TDataForm::PQPoolEdChange(TObject *Sender)
{
  SimForm->PQPool = atoi(PQPoolEd->Text.c_str());
}
void __fastcall TDataForm::kpEdChange(TObject *Sender)
{
  SimForm->kp = atof(kpEd->Text.c_str());
}
void __fastcall TDataForm::kfEdChange(TObject *Sender)
{
  SimForm->kf = atof(kfEd->Text.c_str());
}
void __fastcall TDataForm::klEdChange(TObject *Sender)
{
  SimForm->kl = atof(klEd->Text.c_str());
}
void __fastcall TDataForm::ktoEdChange(TObject *Sender)
{
  SimForm->kto = atof(ktoEd->Text.c_str());
}
void __fastcall TDataForm::kboEdChange(TObject *Sender)
{
  SimForm->kbo = atof(kboEd->Text.c_str());
}
void __fastcall TDataForm::ktcEdChange(TObject *Sender)
{
  SimForm->ktc = atof(ktcEd->Text.c_str());
}
void __fastcall TDataForm::kbcEdChange(TObject *Sender)
{
  SimForm->kbc = atof(kbcEd->Text.c_str());
}
void __fastcall TDataForm::klrcEdChange(TObject *Sender)
{
  SimForm->klrc = atof(klrcEd->Text.c_str());
}
void __fastcall TDataForm::SimTimeEdChange(TObject *Sender)
{
  SimForm->SimTime = atof(SimTimeEd->Text.c_str());
}
void __fastcall TDataForm::SimStepEdChange(TObject *Sender)
{
  SimForm->SimStep = atof(SimStepEd->Text.c_str());
}
void __fastcall TDataForm::SimRecEdChange(TObject *Sender)
{
  SimForm->SimRec = atof(SimRecEd->Text.c_str());
}
void __fastcall TDataForm::SimRunsEdChange(TObject *Sender)
{
  SimForm->SimRuns = atoi(SimRunsEd->Text.c_str());
}
void __fastcall TDataForm::SimStartBtnClick(TObject *Sender)
{
  SimForm->Simulate();
}



//======= PROTOCOL EDITOR =======

void __fastcall TDataForm::FontClick(TObject *Sender)
{
  FontDialog1->Font= Protocol->Font;

  if (FontDialog1->Execute())
    Protocol->SelAttributes->Assign(FontDialog1->Font);
}
void __fastcall TDataForm::Cut1Click(TObject *Sender)
{
  Protocol->CutToClipboard();
}
void __fastcall TDataForm::Delete1Click(TObject *Sender)
{
  Protocol->ClearSelection();
}
void __fastcall TDataForm::Copy1Click(TObject *Sender)
{
  Protocol->CopyToClipboard();
}
void __fastcall TDataForm::Paste1Click(TObject *Sender)
{
  Protocol->PasteFromClipboard();
}
void __fastcall TDataForm::Selectall1Click(TObject *Sender)
{
  Protocol->SelectAll();
}
void __fastcall TDataForm::ProtocolPopMenuPopup(TObject *Sender)
{
  Edit1Click(Sender);
}
void __fastcall TDataForm::Edit1Click(TObject *Sender)
{
  bool HasSelection;
  Paste1->Enabled = Clipboard()->HasFormat(CF_TEXT);
  Paste2->Enabled = Paste1->Enabled;
  HasSelection = Protocol->SelLength > 0;
  Cut1->Enabled = HasSelection;
  Cut2->Enabled = HasSelection;
  Copy1->Enabled = HasSelection;
  Copy2->Enabled = HasSelection;
  Delete1->Enabled = HasSelection;
  Delete2->Enabled = HasSelection;
}
void __fastcall TDataForm::Get_ProtocolClick(TObject *Sender)
{
   ProtocolForm->Get_Protocol();
}

void __fastcall TDataForm::Store_ProtocolClick(TObject *Sender)
{
   ProtocolForm->Store_Protocol();
}

void __fastcall TDataForm::Parse_ProtocolClick(TObject *Sender)
{
  ProtocolForm->Parse_Protocol();
}

void __fastcall TDataForm::Save_Protocol_FileClick(TObject *Sender)
{
  AnsiString FileName;
  SaveFileDlg->FileName = NULL;
  SaveFileDlg->InitialDir = DataForm->CurrentDir;
  SaveFileDlg->InitialDir += "\\Protocols";
  SaveFileDlg->Filter = "Sequencer files (*.seq)|*.SEQ";
  if(SaveFileDlg->Execute())
  {
    FILE* protfile;
    FileName = SaveFileDlg->FileName;
    if(FileName.Pos(".seq") == 0) FileName += ".seq";
    protfile = fopen(FileName.c_str(), "w+b");
    fwrite(&ProtocolForm->seq[0],   ProtocolForm->sequencer_len, 1, protfile);
    fclose(protfile);
  }
}
//---------------------------------------------------------------------------

//========= END OF PROTOCOL EDITOR ==========


//---------------------------------------------------------------------------


//---------------------------------------------------------------------------


void __fastcall TDataForm::CycleUpBtnClick(TObject *Sender)
{
  Cycle ++;
  if(Cycle == NoCycles)  Cycle = 100;
  else if(Cycle == 101)  Cycle = 0;
  UpdateCycle();
}

void __fastcall TDataForm::CycleDownBtnClick(TObject *Sender)
{
  Cycle --;
  if(Cycle == -1)       Cycle = 100;
  else if(Cycle == 99)  Cycle = NoCycles - 1;
  UpdateCycle();
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::UpdateCycle()
{
  if(!(Cycle == 100))
  {
    sprintf(text, "%4i",Cycle);
    CycleNoEd->SetTextBuf(text);
    sprintf(text, "%4i",CycleStart[Cycle]);
    CycleStartEd->SetTextBuf(text);
    sprintf(text, "%4i",CyclePump[Cycle]);
    CyclePumpEd->SetTextBuf(text);
    sprintf(text, "%4i",CycleEnd[Cycle]);
    CycleEndEd->SetTextBuf(text);
    FitStart = CycleStart[Cycle];
    FitEnd   = CycleEnd[Cycle];
  }
  else
  {
    CycleNoEd->SetTextBuf("-ALL-");
    sprintf(text, "%4i",1);
    CycleStartEd->SetTextBuf(text);
    CyclePumpEd->SetTextBuf("-----");
    sprintf(text, "%4i",nodata);
    CycleEndEd->SetTextBuf(text);
    FitStart = 1;
    FitEnd   = nodata;
  }

  sprintf(text, "%10.2f",CycleTauReg[Cycle]);
  Tau0Ed->SetTextBuf(text);
}
//---------------------------------------------------------------------------




void __fastcall TDataForm::FormClose(TObject *Sender, TCloseAction &Action)
{
   Application->MainForm->Close();
}
//---------------------------------------------------------------------------


void __fastcall TDataForm::SampleBtnClick(TObject *Sender)
{
  AllSamples = !AllSamples;
  if(AllSamples) SampleBtn->Caption = "Smp ON";
  else SampleBtn->Caption = "Smp OFF";
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::LoadSeqBtnClick(TObject *Sender)
{
   FindCycle();
   MainForm->SEQ_OUTBtnClick(this);
  //Application->
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::ExperimentRun()
{
   struct timeb t;
   TDateTime DateTime;
   char vv[10];
   int i, id, ip, iflash, iON, iOFF, OFFstart, OFFend, timedelay;
   float bcgr = 0;
   float fON, fOFF, rON, rOFF, rHalf, fSlope, fmin, fmax, RefAver, RunOFF;
   float stotal = 0.0;
   Acquired_Data = true;
   TimeNext = 0;
   if (LaserON)
   {
      while(LaserON)
      {
         MainForm->EXE_Start();
         Sleep(65);
      }
    }


   if(!GainDone)
   {
      GainIndex = GainIndexSet;
      FGainBox->ItemIndex = GainIndex;
      FGainBoxChange(NULL);
      GainDone = true;
   }
   int iseq = 0;
   do          // Starting sequence
   {
      iseq ++;
   do
   {
      MainForm->Memo->Clear();
      if(!(FixedGain))
      {
         GainIndex = GainIndexSet;
         FGainBox->ItemIndex = GainIndex;
         FGainBoxChange(NULL);
      }
      for(i = 1; i < nodata + 1; i ++) f[i] = 0;
      NoAver = 0;
      int iRun = 0;
      do
      {
         iRun   ++;
         NoAver ++;
         bcgr = 0;
         do
         {
            ftime(&t);
            TimeNow = t.time;
         } while (TimeNow < TimeNext);
         TimeLast = TimeNow;
         TimeNext = TimeNow + TimeInterval;

         MainForm->EXE_Start();
         timedelay = int(SeqTime);
         timedelay *= 8;
         Sleep(timedelay + 5);
         MainForm->FIFO_Read_BtnClick(this);

//-------Reference processing

         rHalf = 800;
         for (i = 1; i < 201; i++) bcgr += ri[i];
         bcgr /= 200;
         RunOFF = bcgr;
         id = 200;
         while (ri[id] < bcgr + rHalf) id ++;


         for (iflash = 1; iflash < nodata + 1; iflash++)
         {
            rON = 0; iON = 0;
            flashON[iflash] = id;
            do
            {
               iON ++;
               rON += ri[id];
               id ++;
            }
            while (ri[id] > bcgr + rHalf);
            flashOFF[iflash] = id;
            id += 1;
            if(iON > 0) rON /= iON; else rON = 0;
            ref[iflash] = rON - bcgr;
            rHalf = 0.9 * rHalf + 0.05 * ref[iflash];
            rOFF = 0; iOFF = 0;
            do
            {
               iOFF ++;
               rOFF += ri[id];
               id ++;
            }
            while (ri[id] < bcgr + rHalf);
            if (iOFF > 0) rOFF /= iOFF;
            bcgr = 0.9 * bcgr + 0.1 * rOFF;
         }

         for (i = 1; i < 201; i++) bcgr += ri[i];
         bcgr /= 200;
         RunOFF = bcgr;
         id = 200;
         for (iflash = 1; iflash < nodata + 1; iflash++)
         {
//--------- Fine Tune flashoff and flashon
            flashON[iflash] += 1;
            flashOFF[iflash] -= 1;
//----------------------------------------
//==========Reference
            iON  = 0;
            iOFF = 0;
            fOFF = 0.0;
            OFFstart = flashOFF[iflash] + 2;
            OFFend   = flashON[iflash + 1] - 2;             //Start of the OFF period
            for(i = OFFstart; i < OFFend + 1; i++)
            {
               fOFF += ri[i];
               iOFF ++;
            }
            if(iOFF == 0) iOFF = 1;
            fOFF /= iOFF;
            RunOFF = 0.9 * RunOFF + 0.1 * fOFF;
            fb[iflash + 1] = fOFF;
            fON = 0;
            iON = 0;
            for(i = flashON[iflash] - 1; i < flashOFF[iflash] + 2; i++)
            {
              fON += ri[i] - RunOFF;
              iON ++;
            }
            //if(iON > 0) fON /= iON;
            ref[iflash] = fON;
         }
         bcgr = 0;
         for (i = 1; i < 201; i++) bcgr += fi[i];
         bcgr /= 200;
         RunOFF = bcgr;
         for (iflash = 1; iflash < nodata + 1; iflash++)
         {
            iON  = 0;
            iOFF = 0;
            fOFF = 0.0;
            OFFstart = flashOFF[iflash] + 2;
            OFFend   = flashON[iflash + 1] - 2;             //Start of the OFF period
            for(i = OFFstart; i < OFFend + 1; i++)
            {
               fOFF += fi[i];
               iOFF ++;
            }
            if(iOFF == 0) iOFF = 1;
            fOFF /= iOFF;
            RunOFF = 0.9 * RunOFF + 0.1 * fOFF;
            fb[iflash + 1] = fOFF;
            fON = 0;
            iON = 0;
            for(i = flashON[iflash] - 1; i < flashOFF[iflash] + 2; i++)
            {
              fON += fi[i] - RunOFF;
              iON ++;
            }
            //if(iON > 0) fON /= iON;
            fon[iflash] = fON;
         }
         CORR1->Clear();
         F->Clear();
         FIT->Clear();
         CORR1->Active = false;
         F->Active = false;

         OFFstart = 0;
         for (iflash = 1; iflash < nodata + 1; iflash++)
         {
            //for(i = OFFstart; i < flashON[iflash] - 1; i++) DataForm->CORR1->AddXY(i, fb[iflash], "", clBlack);
            //OFFstart = flashOFF[iflash] + 2;

            //for(i = OFFstart; i < flashON[iflash] + 1; i++) DataForm->CORR1->AddXY(i, 1000, "", clBlack);
            //for(i = flashON[iflash]; i < flashOFF[iflash] + 1; i++) DataForm-CORR1->AddXY(i, 3000, "", clBlack);
            //OFFstart = flashOFF[iflash];


            //OFFstart = flashOFF[iflash] + 2;
            fs[iflash] = fon[iflash];// - fb[iflash];
         }
//------ SIMULATE ------
/*

         fo = 20;
         fm = 60;
         sig = 400;
         Simulate(p, sig, CStart, FitStart, FitEnd);
*/
//---------------------------------------------------
         sprintf(text, "%4i",iRun);
         iRunLabel->Caption = text;


         f[0] = 0;
         stotal = 0.0;
         for(i = 1; i < nodata + 1; i ++)
         {
            f[i] = fs[i];
            stotal += f[i];
         }
         f[nodata]   = f[nodata - 1];
         ref[nodata] = ref[nodata - 1];
         SignalUncalibrated = stotal/nodata;
         SignalCalibrated = (SignalUncalibrated - ScatValue)/GainValue;
         sprintf(vv, "%8.3f", SignalCalibrated);
         SignalCalVal->Caption = vv;
         sprintf(vv, "%8.3f", SignalUncalibrated);
         SignalUncalVal->Caption = vv;
         fmin =  100000.0;
         fmax = -100000.0;
         F->Clear();
         F->Active = false;
         REF->Clear();
         REF->Active = false;
         RefAver = 0.0;
         //for(i = 0; i < NoCycles + 1; i ++) ref[CycleStart[i]] *= 1.00;
         for(i = 1; i < nodata + 1; i ++)
         {
            RefAver += ref[i];
            excal[i] = ref[i] * ExCalValue * ExPower;
         }
         if(nodata > 0)RefAver /= nodata;
         for(i = 1; i < nodata + 1; i ++)
         ref[i] = ref[i]/RefAver;
         for(i = 1; i < nodata + 1; i ++)
         {
            f[i] = (f[i] - ScatValue)/GainValue;
            f[i] = f[i] * 100 / ref[i]; //ref[i];
            if(f[i] < fmin) fmin = f[i];
            if(f[i] > fmax) fmax = f[i];
            if(TimeBase) F->AddXY(tim[i], f[i], "", clTeeColor);
            else  F->AddXY(i, f[i], "", clTeeColor);
            ref[i] *= 1000;
            if(TimeBase) REF->AddXY(tim[i], ref[i], "", clTeeColor);
            else  REF->AddXY(i, ref[i], "", clTeeColor);
         }
         if(fmin > 0) fmin = 0;
         if(fmin < 0) fmin = - 2.0;
         if(fmax < 2) fmax =   2.0; else  fmax *= 1.2;
         //FitChart->LeftAxis->SetMinMax(fmin, fmax);
         F->Active = true;
         CORR1->Active = true;
         REF->Active = true;
         if(!FixedGain)
         {
            if((SignalUncalibrated < 500) && (GainIndex < 12))
            {
               for(i = 1; i < nodata + 1; i ++) f[i] = 0;
               NoAver = 0;
               iRun --;
               GainIndex ++;
               FGainBox->ItemIndex = GainIndex;
               FGainBoxChange(NULL);
            }
         }
         Sleep(10);
      }while((iRun < NoRuns) && ExecuteON);
      ftime(&t);
      DateTimeRecord = FormatDateTime("mm/dd/yyyy  hh:nn:ss", Now());
      sprintf(vv,"  %ld", t.time);
      DateTimeRecord += vv;
      //if (ExecuteON && FileStoreAutoMode) MakeFitFRR(CyclePumpStart[0], CyclePumpEnd[0], CycleDecStart[0], CycleDecEnd[0], true);
      if (ExecuteON && FileStoreAutoMode) FitBtnClick(this);
      if(!SingleExp)
      {
         for(int seconds = 0; seconds < SeqInterval; seconds ++) Sleep(1000);
      }
   }while(!SingleExp && ExecuteON);
   if(SingleExp && (iseq < NoSeq))
   {
      for(int seconds = 0; seconds < SeqInterval; seconds ++) Sleep(1000);
   }
   }while(iseq < NoSeq);
   EXEBtn->Caption = "START";
   EXECUTE_Ind->Brush->Color = clLime;
   ExecuteON = false;
}


void __fastcall TDataForm::EXEBtnClick(TObject *Sender)
{
   TExpRunThread* run;
   if(ExecuteON && SingleExp) ExecuteON = false;
   else if(!ExecuteON)
   {
      ExecuteON = true;
      //TExpRunThread* run = new TExpRunThread(true);
      run = new TExpRunThread(true);
      run->Priority = tpLower;
      run->Resume();
   }
   if(ExecuteON)
   {
      EXEBtn->Caption = "STOP";
      EXECUTE_Ind->Brush->Color = clRed;
   }
   else
   {
      EXEBtn->Caption = "START";
      EXECUTE_Ind->Brush->Color = clLime;
   }
   FitDone = false;
   if(!(run = NULL)) delete run;
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::TimeBaseBtnClick(TObject *Sender)
{
   TimeBase = !TimeBase;
   FIT->Clear();
   CC->Clear();
   F->Clear();
   REF->Clear();
   if(TimeBase)
   {
      TimeBaseBtn->Caption = "TimeBase";
      for (int i = 1; i < nodata; i++)
      {
         F->AddXY(tim[i], f[i], "", clTeeColor);
         if(FitDone) FIT->AddXY(tim[i], fit[i], "", clTeeColor);
         REF->AddXY(tim[i], ref[i], "", clTeeColor);
      }
      FitChart->BottomAxis->SetMinMax(-tim[nodata]*0.01, tim[nodata]* 1.01);
      FitChart->BottomAxis->Title->Caption = "Time (us)";
   }
   else
   {
      TimeBaseBtn->Caption = "PointBase";
      for (int i = 1; i < nodata; i++)
      {
         F->AddXY(i, f[i], "", clTeeColor);
         REF->AddXY(i, ref[i], "", clTeeColor);
         if(FitDone) FIT->AddXY(i, fit[i], "", clTeeColor);
      }
      FitChart->BottomAxis->SetMinMax(-2, nodata+2);
      FitChart->BottomAxis->Title->Caption = "DataPoint";
   }
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::FGainBoxChange(TObject *Sender)
{
   int index, d1, d2;
   index = FGainBox->ItemIndex;
   if(!ExecuteON)
   {
      switch (index)
      {
         case 0 : d1 = 134; d2 = 134; GainIndex = 0; break;
         case 1 : d1 = 153; d2 = 134; GainIndex = 1; break;
         case 2 : d1 = 172; d2 = 134; GainIndex = 2; break;
         case 3 : d1 = 185; d2 = 134; GainIndex = 3; break;
         case 4 : d1 = 199; d2 = 134; GainIndex = 4; break;
         case 5 : d1 = 217; d2 = 134; GainIndex = 5; break;
         case 6 : d1 = 230; d2 = 134; GainIndex = 6; break;
         case 7 : d1 = 245; d2 = 134; GainIndex = 7; break;
         case 8 : d1 = 250; d2 = 153; GainIndex = 8; break;
         case 9 : d1 = 250; d2 = 169; GainIndex = 9; break;
         case 10 : d1 = 250; d2 = 190; GainIndex = 9; break;
         case 11 : d1 = 250; d2 = 220; GainIndex = 9; break;
         case 12 : d1 = 250; d2 = 250; GainIndex = 9; break;
      }
      MainForm->SetFGain(d1, d2);
      GainValue = Gain[GainIndex];
      ScatValue = Scat[GainIndex];
      if(!(Sender == NULL)) GainIndexSet = index;
      GainDone = true;
   }
}


void __fastcall TDataForm::FGainEdChange(TObject *Sender)
{
   FGain = atof(FGainEd->Text.c_str());
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::XGainEdChange(TObject *Sender)
{
   XGain = atof(XGainEd->Text.c_str());
}

void __fastcall TDataForm::RunsEdChange(TObject *Sender)
{
  NoRuns = atoi(RunsEd->Text.c_str());
}

void __fastcall TDataForm::FGainBtnClick(TObject *Sender)
{
   int dbase1 = 134;
   int dbase2 = 134;
   int d1 = dbase1;
   int d2 = dbase2;
   if(FGain < 120) d1 = dbase1 + int(FGain);
   if(FGain > 120)
   {
      d1 = 255;
      d2 = dbase2 + int(FGain/120);
   }
   if(d1 < dbase1) d1 = dbase1;
   if(d2 < dbase2) d2 = dbase2;

   d2 = int(FGain);
   d1 = 250;
   MainForm->SetFGain(d1, d2);
}

void __fastcall TDataForm::PlotBoxClick(TObject *Sender)
{
   TCheckBox* sender = (TCheckBox*) Sender;
   if(Sender == PlotBox)         PlotColSym->Visible  =  PlotBox->Checked;
   if(Sender == FmPlotBox)       FmColSym->Visible    =  FmPlotBox->Checked;
   if(Sender == FvPlotBox)       FvColSym->Visible    =  FvPlotBox->Checked;
   if(Sender == DelPlotBox)      DelColSym->Visible   =  DelPlotBox->Checked;
   if(Sender == SigPlotBox)      SigColSym->Visible   =  SigPlotBox->Checked;
   if(Sender == pPlotBox)        pColSym->Visible     =  pPlotBox->Checked;
   if(Sender == al1QAPlotBox)    al1QAColSym->Visible =  al1QAPlotBox->Checked;
   if(Sender == t1QAPlotBox)     t1QAColSym->Visible  =  t1QAPlotBox->Checked;
   if(Sender == al2QAPlotBox)    al2QAColSym->Visible =  al2QAPlotBox->Checked;
   if(Sender == t2QAPlotBox)     t2QAColSym->Visible  =  t2QAPlotBox->Checked;
   if(Sender == al3QAPlotBox)    al3QAColSym->Visible =  al3QAPlotBox->Checked;
   if(Sender == t3QAPlotBox)     t3QAColSym->Visible  =  t3QAPlotBox->Checked;
   if(Sender == al1PQPlotBox)    al1PQColSym->Visible =  al1PQPlotBox->Checked;
   if(Sender == t1PQPlotBox)     t1PQColSym->Visible  =  t1PQPlotBox->Checked;
   if(Sender == al2PQPlotBox)    al2PQColSym->Visible =  al2PQPlotBox->Checked;
   if(Sender == t2PQPlotBox)     t2PQColSym->Visible  =  t2PQPlotBox->Checked;
   if(Sender == al3PQPlotBox)    al3PQColSym->Visible =  al3PQPlotBox->Checked;
   if(Sender == t3PQPlotBox)     t3PQColSym->Visible  =  t3PQPlotBox->Checked;
   if(Sender == IrradPlotBox)    IrradColSym->Visible =  IrradPlotBox->Checked;
   if(Sender == TempPlotBox)     TempColSym->Visible  =  TempPlotBox->Checked;
   plots[sender->Tag].on = sender->Checked;
   int ivar    = plots[sender->Tag].var;
   int iplot   = sender->Tag;
   if(!(sender->Checked)) PLOTS[iplot]->Clear();
   if(sender->Checked)
   {
      for(int pt = 0; pt < PlotPoints; pt ++)
      PLOTS[iplot]->AddXY(pt, PlotVars[pt][ivar] * 100/plots[iplot].range, "", plots[iplot].color);
   }
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::PlotColSymMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
   TShape* sender;
   sender = (TShape*)Sender;
   int ivar    = plots[sender->Tag].var;
   int iplot   = sender->Tag;
   int ypos = plots[sender->Tag].pos;
   int symbol = plots[sender->Tag].symbol;
   plots[sender->Tag].color = sender->Brush->Color;
   if(Button == 0)
   {
      if(ColorDlg->Execute())
      {
         sender->Brush->Color = ColorDlg->Color;
         plots[iplot].color = ColorDlg->Color;
      }
   }
   if(Button == 1)
   {
      symbol ++;
      if(symbol > 3) symbol = 0;
      if(symbol == 0)
      {
         sender->Shape = stRectangle;
         sender->Pen->Style = psClear;
         sender->Height = 4;
         sender->Top = ypos + 4;
         PLOTS[iplot]->Pen->Width = 1;
         PLOTS[iplot]->Pointer->Visible = false;
         PLOTS[iplot]->LinePen->Visible = true;
      }
      if(symbol == 1)
      {
         sender->Shape = stRectangle;
         sender->Pen->Style = psClear;
         sender->Height = 10;
         sender->Top = ypos;
         PLOTS[iplot]->Pen->Width = 2;
         PLOTS[iplot]->Pointer->Visible = false;
         PLOTS[iplot]->LinePen->Visible = true;
      }
      if(symbol == 2)
      {
         sender->Shape = stCircle;
         sender->Pen->Color = clBlack;
         sender->Pen->Style = psSolid;
         sender->Height = 10;
         sender->Top = ypos;
         PLOTS[iplot]->Pointer->Style = psCircle;
         PLOTS[iplot]->Pointer->HorizSize = 4;
         PLOTS[iplot]->Pointer->VertSize = 4;
         PLOTS[iplot]->Pointer->Visible = true;
         PLOTS[iplot]->LinePen->Visible = false;
      }
      if(symbol == 3)
      {
         sender->Shape = stSquare;
         sender->Pen->Color = clBlack;
         sender->Pen->Style = psSolid;
         sender->Height = 10;
         sender->Top = ypos;
         PLOTS[iplot]->Pointer->Style = psRectangle;
         PLOTS[iplot]->Pointer->HorizSize = 3;
         PLOTS[iplot]->Pointer->VertSize = 3;
         PLOTS[iplot]->Pointer->Visible = true;
         PLOTS[iplot]->LinePen->Visible = false;
      }
      plots[iplot].symbol = symbol;
   }
   PLOTS[iplot]->Clear();
   for(int pt = 0; pt < PlotPoints; pt ++)
   PLOTS[iplot]->AddXY(pt, PlotVars[pt][ivar] * 100/plots[iplot].range, "", plots[iplot].color);
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::SingleExpBtnClick(TObject *Sender)
{
   SingleExp = !SingleExp;
   if(SingleExp) SingleExpBtn->Caption = "SINGLE";
   else SingleExpBtn->Caption = "CONT";
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::FixedGainBtnClick(TObject *Sender)
{
   FixedGain = !FixedGain;
   if(FixedGain) FixedGainBtn->Caption = "FIXED";
   else FixedGainBtn->Caption = "AUTO";
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::Store_File_NameDlgClick(TObject *Sender)
{
   SaveFileDlg->FileName = NULL;
   SaveFileDlg->InitialDir = CurrentDir;
   SaveFileDlg->InitialDir += "\\Data";
   SaveFileDlg->Filter = "Data Files";
   if(SaveFileDlg->Execute())
   {
      StoreFileName = SaveFileDlg->FileName;
      ResultsFileName = StoreFileName;
      StoreFileNameLabel->Caption = StoreFileName;
      int pos = ResultsFileName.Pos("Data");
      ResultsFileName.Delete(pos, 4);
      ResultsFileName.Insert("Results", pos);
      if(ResultsFileName.Pos(".") == 0) ResultsFileName  += ".res";
      else
      {
         int p = ResultsFileName.Pos(".");
         ResultsFileName.Delete(p, 100);
         ResultsFileName  += ".res";
      }
   }
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::FileStoreModeBtnClick(TObject *Sender)
{
   FileStoreAutoMode = !FileStoreAutoMode;
   if(FileStoreAutoMode) FileStoreModeBtn->Caption = "AUTO";
   else FileStoreModeBtn->Caption = "MANUAL";
}
//---- PLOT CONTRLS ---------------------------------------------------------

void __fastcall TDataForm::MoveLeftBtnClick(TObject *Sender)
{
   if(Sender == MoveLeftBtn)
   {
      if(PlotStart - PlotUpdate > 0)
      {
         PlotStart -= PlotUpdate;
         PlotEnd   -= PlotUpdate;
      }
      else
      {
         PlotStart = 1;
         PlotEnd = PlotStart + PlotWindow - 1;
      }
   }
   if(Sender == MoveRightBtn)
   {
      PlotStart += PlotUpdate;
      PlotEnd   += PlotUpdate;
   }
   DataChart->BottomAxis->SetMinMax(PlotStart, PlotEnd);
}

void __fastcall TDataForm::PlotRangeEdChange(TObject *Sender)
{
   TEdit* sender = (TEdit*) Sender;
   //plots[sender->Tag].range = atof(sender->Text.c_str());
   New_range = atof(sender->Text.c_str());
   Plot_with_new_range = sender->Tag;
}

void __fastcall TDataForm::PlotOptionsEdChange(TObject *Sender)
{
   TEdit* sender = (TEdit*) Sender;
   if(sender == PlotOptionsEd)
   {
      PlotStart = atoi(PlotOptionsEd->Text.c_str());
      PlotEnd   = PlotStart + PlotWindow;
   }
   if(sender == PlotEndEd)
   {
      PlotEnd =   atoi(PlotEndEd->Text.c_str());
      PlotWindow = PlotEnd - PlotStart;
   }
   if(sender == PlotWindowEd)
   {
      PlotWindow = atoi(PlotWindowEd->Text.c_str());
      PlotEnd = PlotStart + PlotWindow;
   }
   if(sender == PlotUpdateEd)    PlotUpdate = atoi(PlotUpdateEd->Text.c_str());
   PlotOptionsPending = true;
}

void __fastcall TDataForm::ReplotMenuClick(TObject *Sender)
{

   //else
   {
      int iplot = Plot_with_new_range;
      if(New_range == 0) New_range = plots[iplot].range;
      plots[iplot].range = New_range;
      int ivar  = plots[iplot].var;
      PLOTS[iplot]->Clear();
      for(int pt = 0; pt < PlotPoints; pt ++)
      PLOTS[iplot]->AddXY(pt, PlotVars[pt][ivar] * 100/plots[iplot].range, "", plots[iplot].color);
   }
}

void __fastcall TDataForm::Page1Resize(TObject *Sender)
{
  FitChartsPanel->Height = Page1->Height - 188;
}

void __fastcall TDataForm::FormResize(TObject *Sender)
{
   FitChartsPanel->Width  = DataForm->Width;
   DataChart->Width = DataForm->Width - 144;
}

void __fastcall TDataForm::PlotClearClick(TObject *Sender)
{
   for(int iplot = 0; iplot < 25; iplot ++) PLOTS[iplot]->Clear();
   ResultsMemo->Clear();
   PlotPoint = 0;
   PlotPoints = 0;
}
//---------------------------------------------------------------------------


void __fastcall TDataForm::BlueBackgrLightEdChange(TObject *Sender)
{
   BlueLight = int(atof(BlueBackgrLightEd->Text.c_str()));
   if(BlueLight < 0) BlueLight = 0;
   if(BlueLight > 4096) BlueLight = 4096;
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::IRRBackgrLightEdChange(TObject *Sender)
{
    IRRLight = int(atof(IRRBackgrLightEd->Text.c_str()));
    if(IRRLight < 0) IRRLight = 0;
    if(IRRLight > 4096) IRRLight = 4096;
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::BlueLightBtnClick(TObject *Sender)
{
   MainForm->DACselect = 1;
   MainForm->DAC[1] = BlueLight + 4096;
   MainForm->DAC_SetBtnClick(Sender);
}
//---------------------------------------------------------------------------


void __fastcall TDataForm::IRRLightBtnClick(TObject *Sender)
{
   MainForm->DACselect = 0;
   MainForm->DAC[0] = IRRLight + 4096;
   MainForm->DAC_SetBtnClick(Sender);

}
//---------------------------------------------------------------------------

void __fastcall TDataForm::TimeIntervalEdChange(TObject *Sender)
{
   TimeInterval = atof(TimeIntervalEd->Text.c_str());
}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------

void __fastcall TDataForm::SaveCalibrationFileBtnClick(TObject *Sender)
{
   AnsiString FileName;
   DataForm->OpenFileDialog->FileName = NULL;
   DataForm->SaveFileDlg->InitialDir = DataForm->CurrentDir;
   DataForm->SaveFileDlg->InitialDir += "\\Protocols";
   DataForm->SaveFileDlg->Filter = "Calibration files (*.cal)|*.CAL";
   if(DataForm->SaveFileDlg->Execute())
   {
      FileName = DataForm->SaveFileDlg->FileName;
      if(FileName.Pos(".cal") == 0) FileName += ".cal";
      DataForm->Protocol->Lines->SaveToFile(FileName);
   }
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::GetCalibrattionFileBtnClick(TObject *Sender)
{
   AnsiString buffer, sval, token[20];
   int blen;
   DataForm->OpenFileDialog->FileName = NULL;
   DataForm->OpenFileDialog->InitialDir = DataForm->CurrentDir;
   DataForm->OpenFileDialog->InitialDir += "\\Protocols";
   DataForm->OpenFileDialog->Filter = "Calibration files (*.cal)|*.CAL";
   if(DataForm->OpenFileDialog->Execute())
   {
      DataForm->Protocol->Lines->LoadFromFile(DataForm->OpenFileDialog->FileName);
      int nolines = DataForm->Protocol->Lines->Count;
      AnsiString buffer, sval;
      int blen, ichar, itoken, notokens;
      for (int iline = 2; iline < nolines; iline++)
      {
         buffer = DataForm->Protocol->Lines->Strings[iline];
         blen = buffer.Length();
         ichar = 1; itoken = 0;
         do
         {
            sval = "";
            while ((ichar < blen + 1) &&  (buffer[ichar] == ' ')) ichar ++;
            while ((ichar < blen + 1) && !(buffer[ichar] == ' ')) {sval += buffer[ichar]; ichar ++;}
            token[itoken] = sval;
            itoken ++;
         }while (ichar < blen);
         Gain[iline - 2] = atof(token[2].c_str());
         Scat[iline - 2] = atof(token[3].c_str());
      }
   }
}
//---------------------------------------------------------------------------


void __fastcall TDataForm::ReplotBtnClick(TObject *Sender)
{
   if(PlotOptionsPending)
   {
      DataChart->BottomAxis->SetMinMax(PlotStart, PlotEnd);
      PlotOptionsPending = false;
      //---- Update Plot Options
      sprintf(text, "%4i",PlotStart);
      PlotOptionsEd->SetTextBuf(text);
      sprintf(text, "%4i",PlotEnd);
      PlotEndEd->SetTextBuf(text);
      sprintf(text, "%4i",PlotWindow);
      PlotWindowEd->SetTextBuf(text);
      DataChart->BottomAxis->SetMinMax(PlotStart, PlotEnd);
      PlotOptionsPending = false;
   }

}
//---------------------------------------------------------------------------

void __fastcall TDataForm::LaserTestBtnClick(TObject *Sender)
{
   LaserON = !LaserON;
   if(LaserON)
   {
      LaserTestBtn->Caption = "LASER ON";
   }
   else LaserTestBtn->Caption = "Laser_Test";
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::NoSeqEdChange(TObject *Sender)
{
   NoSeq = int(atof(NoSeqEd->Text.c_str()));
}
//---------------------------------------------------------------------------

void __fastcall TDataForm::SeqDelEdChange(TObject *Sender)
{
   SeqInterval = int(atof(SeqDelEd->Text.c_str()));
}










