#include <vcl.h>
#include <stdio.h>
//#include <NIDAQmx.h>
#include <fstream>
#include <string.h>
#include <math.h>
#include <iostream>
#include <SyncObjs.hpp>
#include <math.h>
//#include "visa.h"
#pragma hdrstop

#include "Unit1.h"
#include "Unit2.h"


/*#include <conio.h>
#include <vcl.h>
#include <windows.h>
#include <winsock.h>

*/
#pragma package(smart_init)
#pragma resource "*.dfm"

TEvent *timeevent = new TEvent(NULL, true, false, "timeevent");
TEvent *timeevent2 = new TEvent(NULL, true, false, "timeevent2");
using namespace std;
TForm1 *Form1;

   //----global variables

// globalni promenne
        double                 ***poledat=0;
        int                    pocetmereni=100;
    //    int32		       error=0;
     //	TaskHandle	       prvni=0,druha=0,treti=0;
        double                 data[1]={0.0};
        double                 data1[1]={0.0};
        float                  vstupninapeti[10];
        long                   read;
        int                    vzorky=20;
        double                 data2[10000];
	char                   errBuff[2048]={'\0'};
        bool                    measureenable=false;
        int                     krokux=10,krokuy=10;
        int                     measurestate=0;       //stav mereni 0- pred startem, 1 - pauze,3-probihajici,4-konec
        AnsiString              Datum,Cas;
        AnsiString              initialpath="c:\\Documents and Settings\\xkrcal04\\Plocha\\program vyvoj\\final\\data"; // vychozi cesta k programu
        double                  ix,iy;
        bool                    posuv;
        double                  polex[1],poley[1];
        bool                    progexec=false;
       

  struct measuredata
  {
  double minx;
  double miny;
  double maxx;
  double maxy;
  double stepx;
  double stepy;
  int    fvz;
  } measet, *maset;


  //--- prototypy funkci

 void Delay( int delay);
 float ReadSourceCurrent();
 void uklidpomereni(void);
 void zpracovani(double &polex,double &poley);
 void ziskejcas (void);
 void kresli (int color,double &polex, double &poley);
 bool readdatafile(int index);
 bool writedatafile(int index);
 //int32 CVICALLBACK EveryNCallback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples, void *callbackData);
// int32 CVICALLBACK DoneCallback(TaskHandle taskHandle, int32 status, void *callbackData);
 #include "mereni.h"
 measurecard measurecard1;
  thr* prudovezobraz;


//ViSession defaultRM, viDMM1, viLCR, viSource ;

/*void InitGPIB()
{
  viOpenDefaultRM(&defaultRM);
  viOpen(defaultRM, "GPIB0::5::INSTR",VI_NULL,VI_NULL,&viSource);
}

void ClosePort()
{
        viClose(defaultRM);
}

void Delay( int delay)
{
 unsigned int when = GetTickCount() + delay;
 while ( GetTickCount() < when)
 {
   Application->ProcessMessages();

 }
}


float ReadSourceCurrent()
{
  char viBuf[4096] ;
  viQueryf(viSource,"meas:curr:dc? p25v\n","%t",viBuf);
  return atof(viBuf);
}


int32 CVICALLBACK EveryNCallback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples, void *callbackData)
{
	int32       error=0;
	char        errBuff[2048]={'\0'};
	static int  totalRead=0;
	int32       read=0;
	float64     data[1000];

	/*********************************************/
	// DAQmx Read Code
	/*********************************************/

            /*    if (posuv==false)
                {
                polex[0]=ix;
                poley[0]=iy;
                DAQmxWriteAnalogF64(prvni,1,1,10.0,DAQmx_Val_GroupByChannel,poley,NULL,NULL);
                DAQmxWriteAnalogF64(druha,1,1,10.0,DAQmx_Val_GroupByChannel,polex,NULL,NULL);
                waiting();
                for(int a=0;a<10;a++)
	        DAQmxReadAnalogF64(treti,40,-1.0,DAQmx_Val_GroupByScanNumber,data2,200,&read,NULL);
                zpracovani(*polex,*poley);
                if(iy>=(measet.maxy-(measet.stepy/2)))
                        {
                        posuv=true;
                        iy=measet.maxy;
                        ix+=measet.stepx;
                        }
                else iy+=measet.stepy;
                }

                if(posuv==true)
                {
                iy=measet.miny;
                poley[0]=iy;
                DAQmxWriteAnalogF64(prvni,1,1,10.0,DAQmx_Val_GroupByChannel,poley,NULL,NULL);
                for (int b=0;b<10;b++)
                waiting();
                posuv=false;
                }



	if( read>0 ) {
        totalRead+=read;
   //     Form1->Label12->Caption=("Acquired: "+ IntToStr(read)+"total: " + IntToStr(totalRead));

		fflush(stdout);
	}

        if(ix>=measet.maxx)
                {
                uklidpomereni();
                measurestate=4;
                }

	return 0;
}


int32 CVICALLBACK DoneCallback(TaskHandle taskHandle, int32 status, void *callbackData)
{
	int32   error=0;
	char    errBuff[2048]={'\0'};
        if (error!=0)
        {
        Form1->Label12->Caption="error";
        }

	return 0;
}    */




//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------


void __fastcall TForm1::create(TObject *Sender)
{
        progexec=true;
        int pocetmereni=40;
        maset = new measuredata[pocetmereni];
        poledat = new double** [pocetmereni+1];
        for(int i=0;i<pocetmereni;i++) {
        poledat[i]= new double*[201];
        for(int j=0;j<201;j++) poledat[i][j] = new double[201];}
        for(int k=0;k<pocetmereni;k++)
        {
         Form1->ComboBox1->Items->Add("Data"+IntToStr(k));
         Form1->ComboBox2->Items->Add("Nastaveni "+IntToStr(k));
         }
         Form1->ComboBox1->ItemIndex=0;
         Form1->ComboBox2->ItemIndex=0;

        prudovezobraz = new thr(false,tpIdle);;

measet.minx=0.0;
measet.miny=0.0;
measet.maxx=10.0;
measet.maxy=10.0;




     /*   DAQmxCreateTask("jedna",&prvni);
        DAQmxCreateTask("dva",&druha);


        //volba výstupního kanálu a rozsahu
DAQmxCreateAOVoltageChan(prvni,"Dev1/ao0","ao0",-10.0,10.0,DAQmx_Val_Volts,"");
DAQmxCreateAOVoltageChan(druha,"Dev1/ao1","ao1",-10.0,10.0,DAQmx_Val_Volts,"");


DAQmxStartTask(prvni);
DAQmxStartTask(druha);


    */

Form1->ScrollBar1->Min=0;
Form1->ScrollBar1->Max=1000;
Form1->ScrollBar1->Position=0;
Form1->ScrollBar1->LargeChange=1;
//DAQmxWriteAnalogF64(prvni,1,1,10.0,DAQmx_Val_GroupByChannel,0,NULL,NULL);

Form1->ScrollBar2->Min=0;
Form1->ScrollBar2->Max=1000;
Form1->ScrollBar2->Position=0;
Form1->ScrollBar2->LargeChange=1;
//DAQmxWriteAnalogF64(druha,1,1,10.0,DAQmx_Val_GroupByChannel,0,NULL,NULL);

Form1->Edit5->Color=clMenuBar;
Form1->Edit4->Color=clWindow;
Form1->Edit7->Color=clMenuBar;
Form1->Edit6->Color=clWindow;
Form1->Button7->Visible=true;

for(int ind=0;ind<pocetmereni;ind++)
for(int i=0;i<200;i++)
for(int j=0;j<200;j++)
poledat[ind][i][j]=NULL;

//InitGPIB();

//viPrintf(viSource,"VOLT %3.3f\n",0);
//viPrintf(viSource,"OUTPUT ON\n");

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

void __fastcall TForm1::Button1Click(TObject *Sender)
{
Form2->Visible=1;
Form1->Visible=0;
Form2->ComboBox1->Clear();
for(int a=0;a<Form1->ComboBox1->Items->Count;a++)Form2->ComboBox1->Items->Add(Form1->ComboBox1->Items->Strings[a]);
Form2->ComboBox1->ItemIndex=0;
Form2->normalize(Form1->ComboBox1->ItemIndex);
Form2->ComboBox1->ItemIndex=Form1->ComboBox1->ItemIndex;
}
//---------------------------------------------------------------------------


void __fastcall TForm1::form1close(TObject *Sender, TCloseAction &Action)
{

        progexec=false;
        
        int pocetmereni=40;
        for(int i=0;i<pocetmereni;i++)
        {
        for(int j=0;j<201;j++) delete [] poledat[i][j];
        delete [] poledat[i];
        }
        delete [] poledat;
        delete [] maset;
        delete timeevent;
      //  delete prudovezobraz;
      
 //viPrintf(viSource,"VOLT 0\n");  //nastaveni 0V po dokonceni mereni
 //viPrintf(viSource,"OUTPUT OFF\n");
 //viPrintf(viSource,"*rst\n");
 //viClose(viSource);
 //ClosePort();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button2Click(TObject *Sender)
{
int item1=Form1->ComboBox1->ItemIndex;
Form1->ComboBox1->Items->Insert(item1,Form1->Edit1->Text);
Form1->ComboBox1->Items->Delete(item1+1);
Form1->ComboBox1->ItemIndex=item1;
        
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button3Click(TObject *Sender)
{
int item2=Form1->ComboBox2->ItemIndex;
Form1->ComboBox2->Items->Insert(item2,Form1->Edit2->Text);
Form1->ComboBox2->Items->Delete(item2+1);
Form1->ComboBox2->ItemIndex=item2;

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

           // UTILITY //




bool writedatafile(int index,string souborjmeno)
{
  DecimalSeparator = '.';
  fstream myfile;
  string pomx=("data\\" + souborjmeno + ".dat");

  if(!myfile.is_open())
  {
  myfile.open (pomx.c_str(), ios::out | ios::trunc );

String radka=(" -- Soubor s daty -- \n");

myfile << radka.c_str();

 for (int x=0;x<199;x++)
 {
 for (int y=0;y<199;y++)
 {
 radka = (FloatToStr(poledat[index][x][y])+"\n");
 myfile << radka.c_str();
 if(myfile.bad()) ShowMessage("Zapis do souboru nevysel");
 }
 }

  }
  myfile.close();

}





void __fastcall TForm1::Ulodata1Click(TObject *Sender)
{
int index = Form1->ComboBox1->ItemIndex;

/*for (int i=0;i<200;i++)
for (int j=0;j<200;j++)
{
poledat[index][i][j]=2;
}           */

String souborname=AnsiString(Form1->ComboBox1->Items->Strings[index]);
writedatafile(index,souborname.c_str());

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

void __fastcall TForm1::Konec1Click(TObject *Sender)
{
Form1->Close();
        
}
//---------------------------------------------------------------------------

void __fastcall TForm1::form1resize(TObject *Sender)
{
Form1->Width=700;
Form1->Height=500;
        
}
//---------------------------------------------------------------------------




void __fastcall TForm1::Edit4Click(TObject *Sender)
{
Form1->Edit5->Color=clMenuBar;
Form1->Edit4->Color=clWindow;
try
{
 Form1->ScrollBar1->Position=Form1->Edit4->Text.ToInt();
 measet.minx=double(Form1->ScrollBar1->Position)/100;
 data1[0]=double(Form1->ScrollBar1->Position)/100;
 measurecard1.move();
}
catch (...)
{
}
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Edit5Click(TObject *Sender)
{
Form1->Edit4->Color=clMenuBar;
Form1->Edit5->Color=clWindow;
try
{
 Form1->ScrollBar1->Position=Form1->Edit5->Text.ToInt();
  measet.maxx=double(Form1->ScrollBar1->Position)/100;
 data1[0]=double(Form1->ScrollBar1->Position)/100;
 measurecard1.move();
}
catch (...)
{
}
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Edit6click(TObject *Sender)
{
Form1->Edit7->Color=clMenuBar;
Form1->Edit6->Color=clWindow;
try
{
 Form1->ScrollBar2->Position=Form1->Edit6->Text.ToInt();
  measet.miny=double(Form1->ScrollBar2->Position)/100;
 data[0]=double(Form1->ScrollBar2->Position)/100;
 measurecard1.move();
}
catch (...)
{
}
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Edit7click(TObject *Sender)
{
Form1->Edit6->Color=clMenuBar;
Form1->Edit7->Color=clWindow;
try
{
 Form1->ScrollBar2->Position=Form1->Edit7->Text.ToInt();
 measet.maxy=double(Form1->ScrollBar2->Position)/100;
 data[0]=double(Form1->ScrollBar2->Position)/100;
 measurecard1.move();
}
catch (...)
{
}
}
//---------------------------------------------------------------------------

void __fastcall TForm1::scroll1(TObject *Sender)
{
if(Form1->Edit4->Color==clWindow)
{
Form1->Edit4->Text=IntToStr(Form1->ScrollBar1->Position);
measet.minx=double(Form1->ScrollBar1->Position)/100;
}
if(Form1->Edit5->Color==clWindow)
{
Form1->Edit5->Text=IntToStr(Form1->ScrollBar1->Position);
measet.maxx=double(Form1->ScrollBar1->Position)/100;
}
data1[0]=double(Form1->ScrollBar1->Position)/100;
measurecard1.move();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::scroll2(TObject *Sender)
{
if(Form1->Edit6->Color==clWindow)
{
Form1->Edit6->Text=IntToStr(Form1->ScrollBar2->Position);
measet.miny=double(Form1->ScrollBar2->Position)/100;
}
if(Form1->Edit7->Color==clWindow)
{
Form1->Edit7->Text=IntToStr(Form1->ScrollBar2->Position);
measet.maxy=double(Form1->ScrollBar2->Position)/100;
}
data[0]=double(Form1->ScrollBar2->Position)/100;
measurecard1.move();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button6Click(TObject *Sender)
{
static thr * mericivlak;
Form1->Button6->Enabled=false;
Form1->ScrollBar1->Enabled=false;
Form1->ScrollBar2->Enabled=false;
Form1->Edit8->Enabled=false;
Form1->Edit9->Enabled=false;
Form1->Button7->Visible=false;
ix=measet.minx;
iy=measet.miny;
for(int i=0;i<200;i++)
for(int j=0;j<200;j++)
poledat[37][i][j]=NULL;

posuv=false;

  if(measet.maxx>measet.minx && measet.maxy>measet.miny)
 {
measet.stepx=double (measet.maxx - measet.minx)/krokux;
measet.stepy=double (measet.maxy - measet.miny)/krokuy;
measet.fvz=vzorky;
//DAQmxCreateTask("",&treti);
//DAQmxCreateAIVoltageChan(treti,"Dev2/ai0","",DAQmx_Val_RSE,-10.0,10.0,DAQmx_Val_Volts,NULL);
//DAQmxCfgSampClkTiming(treti,"",10000.0,DAQmx_Val_Rising,DAQmx_Val_ContSamps,200);
//DAQmxRegisterEveryNSamplesEvent(treti,DAQmx_Val_Acquired_Into_Buffer,200,0,EveryNCallback,NULL);
//DAQmxRegisterDoneEvent(treti,0,DoneCallback,NULL);              //
//DAQmxStartTask(treti);
measurestate=3;
 }



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

void __fastcall TForm1::Edit8Change(TObject *Sender)
{
try
{
 krokux=Form1->Edit8->Text.ToInt();
}
catch (...)
{
}

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

void __fastcall TForm1::Edit9Change(TObject *Sender)
{
try
{
 krokuy=Form1->Edit9->Text.ToInt();
}
catch (...)
{
}
}
//---------------------------------------------------------------------------


void zpracovani(double &polex, double &poley)
{
static int osax=0,osay=0;
static int procentadone=0;
static double troicedat[3]={0,0,0};

        double meandata2=0.0;
        for (int counter1=0; counter1<measet.fvz; counter1++)
        {
        meandata2+=data2[counter1];
        }
        meandata2=meandata2/measet.fvz;
Form1->Label11->Caption=IntToStr(int((polex-measet.minx)/(measet.maxx-measet.minx)*100))+"%";
troicedat[0]=troicedat[1];
troicedat[1]=troicedat[2];
troicedat[2]=meandata2;

if(fabs((fabs(troicedat[0])-fabs(troicedat[1])))>=fabs((fabs(troicedat[1])-fabs(troicedat[2])))) meandata2=troicedat[2]; else meandata2=troicedat[0];
//Form1->Label12->Caption=FloatToStr(meandata2);
if(osax<=krokux)
{
poledat[37][osax][osay]=meandata2;
}
else
{
osax=0;
osay++;
}
osax++;

}

void uklidpomereni(void)
{
Form1->ScrollBar1->Enabled=true;
Form1->ScrollBar2->Enabled=true;
Form1->Edit8->Enabled=true;
Form1->Edit9->Enabled=true;
Form1->Button7->Visible=true;
Form1->Button6->Enabled=true;

	      //	DAQmxStopTask(treti);
	      //	DAQmxClearTask(treti);
}

void __fastcall TForm1::Button7Click(TObject *Sender)
{
for(int i=0;i<200;i++)
for(int j=0;j<200;j++)
{
int indeex=Form1->ComboBox1->ItemIndex;
poledat[indeex][i][j]=poledat[37][i][j];
}
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ahoj1Click(TObject *Sender)
{
        char* filenamer =new char[80];
        char* file_liner = new char[80];
int index = Form1->ComboBox1->ItemIndex;
        String addr=Form1->Edit3->Text.c_str();
        String pomx=("data\\" + addr + ".dat");
        strcpy( filenamer, pomx.c_str() );



    FILE *datas;
    if((datas = fopen(filenamer, "r"))==NULL)
    {
    ShowMessage("Nejde cist soubor s daty");
    }
    else
    {
    int index = Form1->ComboBox1->ItemIndex;


    
while(1) { fgets(file_liner, 80, datas); if(file_liner[0]>=48&&file_liner[0]<=57||file_liner[0]==NULL) break; }  //ignorovani hlavicky

for (int i=0;i<199;i++)
for (int j=0;j<199;j++)
{
//if(fgets(file_liner, 80, datas)!=NULL)
//{
if (j<=198&&i<=196)
poledat[index][i][j]=atof(fgets(file_liner, 80, datas));

//}
//else poledat[index][i][j]=NULL;
}

 fclose(datas);
 }
 delete [] filenamer;
 delete [] file_liner;

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



void __fastcall TForm1::Button4Click(TObject *Sender)
{
static double Napeti;
Napeti = StrToFloat(Form1->Edit10->Text.c_str());
//viPrintf(viSource,"appl p25v,%2.3f\n",Napeti);
//Form1->Label14->Caption="Proud clankem: " + FloatToStr(ReadSourceCurrent()*1000) + "mA";
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button8Click(TObject *Sender)
{
static bool fotonasobic=false;
if(fotonasobic)
{
fotonasobic=false;
Form1->Button8->Caption="Zapnout";
//viPrintf(viSource,"appl p6v,%2.3f\n",0);
}
else
{
fotonasobic=true;
Form1->Button8->Caption="Vypnout";
//viPrintf(viSource,"appl p6v,%2.3f\n",5.0);
}
}
//---------------------------------------------------------------------------

