////////////////////////////////////////////////////////////////
// File - capeval_v29_1.c
//
// Legacy code was generated by DriverWizard v6.03 - http://www.jungo.com.
// The library accesses the hardware via WinDriver functions.
// 
// Replicated from DALIB readout Version 04 for readout speed evaluation
// 
// Version 01 for starters -- NOT WORKING -- 27JAN04-GSV
// Version 02 for testing the CAPevB1 Pixel board -- 27JAN04-GSV
// Version 03 stripped Version 02 for quicker display -- 28JAN04-GSV
// Version 04 version for doing a diff on the two values -- 28JAN04-GSV
// Version 05 first version with real data from pixel detector -- 4FEB04-GSV
// Version 06 zero-suppressed version with correct ordering -- 9FEB04-GSV/MB
// Version 07 low-light level scan version -- 9FEB04-GSV
// Version 08 first scan for high-level fluctuations -- 9FEB04-GSV/MB
// Version 09 random frame data acq. -- 10FEB04-GSV
// Version 10 scan for gain -- 10FEB04-GSV
// Version 11 pick up a couple of pixels for stat -- 18FEB04-MB
// Version 12 record complete frames -- 19FEB04-MB
//            BEWARE: 110kB per event
// Version 13 messing around with data alignement -- 26FEB04-MB
//            cleaner file writing procedure --04MAR04-MB
//            cosmic_flag added (add diff max headers) --11MAR04-MB
// Version 14 record diff max only (source runs pre-rad) -- 15MAR04-MB
// Version 15 first test version for TWO parallel F1c1 boards -- 29MAR04-MB
// Version 16 for TWO parallel F1c1 boards -- 30MAR04-MB
// Version 17 for TWO parallel F1c1 boards -- 31MAR04-MB
//            In this version, two separate trigger levels have to be provided
//            If one of the channels record an event, both channels are 
//            sequentially recorded.
// Version 18 for TWO parallel F1c1 boards -- 31MAR04-MB
//            triggers are on a pixel by pixel base.
// Version 19 For TWO parallel F1c1 boards -- 05APR04-MB
//            Triggers are on a pixel by pixel base.
//            Opens a log file containing each 100,000 evts a recording of the time
// Version 20 For FOUR parallel F1c1 boards -- 05APR04-MB
//            Triggers are on a pixel by pixel base.
//            Opens a log file containing, each "write_to_logfile_cycle" evts, a recording of the time
// Version 21 For FOUR parallel F1c1 boards -- 16APR04-MB
//            Triggers are on a pixel by pixel base.
//            Opens a log file containing, each "write_to_logfile_cycle" evts, a recording of the time
//            TWO out of FOUR must trigger!!!!!!!!!
// Version 22 For FOUR parallel F1c1 boards, trigg pix by pix base -- 19APR04-MB
//            Coincidence flag added = number of detector triggering required
// Version 23 1) Add test mode for physical orientation of detectors -- 27APR04-MB
//               (The GET_ORIENTATION flag...)
//            2) Add ROTATE_CHANNEL3 flag... ACTUAL DATA ROTATION IN DATA DISPLAY ONLY , NOT HERE ,
//               TO KEEP COHERENCE WITH STAT FILES GENERATION AND OTHERS!!!
// Version 24 Added to allow for instant access for Samo's PAW scripts
// Version 25 defined some correlated_data variables...
// Version 26 In this version, online running averaging over 20 events     --03JUN04-KU/MB
//            of the noise in one pixel in each detector. Shifts of the noise levels 
//            might be monitored by this way.
//
// Version 28 Try to copy the logic of version 27 and implement a data processing --03JUN04-GV/KU/MB
//            time reduction of a factor 4 by reading one of the 3 first detector first...
//            You can now require a trigger in detector A or detector B or C. This detector is
//            then the first to be read out and acquisition speed is always /4
//
// Version 29 Put in explicit trigger signal to avoid potential race condition on 
//            B2 firmware
//
// Version 29_1 Same as 29 but for a one detector readout only ...      --22JUN04-MB 
//
////////////////////////////////////////////////////////////////

#include "testapp_lib.h"
#include "/root/WinDriver//samples/shared/pci_diag_lib.h"
#include <stdio.h>
#include "/root/WinDriver//include/status_strings.h"
#include <sys/timeb.h>

#define VENDOR_ID 0x10b5
#define DEVICE_ID 0x9030 

#define COL_MAX 132
#define ROW_MAX 64
#define AMUX_MAX 4
#define OCHAN_MAX 16
#define SAMPLE_MAX 2


float get_gain1=0;
float get_gain2=0;

#define EVT_MAX 100
char logfile[512] = "logfile.dat";
FILE *log_file;
#define write_to_logfile_cycle 1000

#define COSMIC_FLAG 1 // to add event headers "diff max" in a file.
#define PRINT_TO_FILE 1 // 0 = no file out, 1 = file out .
#define COINCIDENCE 1 // 1 = single detect trigg, 2 = two detect trigg ...
#define ROTATE_CHANNEL3 1 // 0 = no rotation, 1 = test beam configuration 

#define ALIGN_A 2 // 1 to align A, 0 if not         JUST ONE AT
#define NO_MISALIGNEMENT 1 // 1==disregard misalignement, 0==take it into account

#define A_SIGMA -10

int A_SKIP_MAX;   //number of samples to blow off due to ADC pipelining (frame1)
int A_SKIP_MAX2;   //number of samples to blow off due to ADC pipelining (frame2)


//////////////////////////////////////////////////////////////////
// channel A:
#define A_p1_col 78    // -1 for dummy pix
#define A_p1_row 60    // -1 for dummy pix
#define A_p2_col 105    // -1 for dummy pix
#define A_p2_row 33    // -1 for dummy pix
#define A_p3_col 86    // -1 for dummy pix
#define A_p3_row 39    // -1 for dummy pix       // F3c6 tunings
#define A_p4_col 115    // -1 for dummy pix
#define A_p4_row 55    // -1 for dummy pix
#define A_p5_col 107    // -1 for dummy pix
#define A_p5_row 24    // -1 for dummy pix
#define A_p6_col 119    // -1 for dummy pix
#define A_p6_row 45    // -1 for dummy pix
#define A_p7_col 93    // -1 for dummy pix
#define A_p7_row 36    // -1 for dummy pix
#define A_p8_col 113    // -1 for dummy pix
#define A_p8_row 25    // -1 for dummy pix
#define A_p9_col 47    // -1 for dummy pix
#define A_p9_row 18    // -1 for dummy pix

//char tmp_fileA[512] = "04JUN04-veryhot-36-stat.dat";
//char tmp_fileA[512] = "02JUN04-hotnois-36-stat.dat";
//char tmp_fileA[512] = "03JUN04-normalnois-36-stat.dat";
char tmp_fileA[512] = "NOISE_FILES_BEAMTEST/03JUN04-normalnois-36-stat.dat";


///////////////////////////////////////////////////////////////////

#define DALIDEBUG 0
int evtnum;
FILE *fileout ;
FILE *file_transcript;
char filename[80];
char filename2[80] = "Log_";

int Trigger_on_A;
int TRIG_A;

float Online_Noise_in_A[20];
float Online_Noise_A;
float Drift_A;

int triggered_evts,i;
int ch1colmax, ch1rowmax, ch1diffmax;
float ch1trigg_qual_max;
UINT ch1data[COL_MAX][ROW_MAX][SAMPLE_MAX];
int ch2colmax, ch2rowmax, ch2diffmax;
float ch2trigg_qual_max;
UINT ch2data[COL_MAX][ROW_MAX][SAMPLE_MAX];
int ch3colmax, ch3rowmax, ch3diffmax;
float ch3trigg_qual_max;
UINT ch3data[COL_MAX][ROW_MAX][SAMPLE_MAX];
int OVERWRITE_KEEP_EVT;
int MISALIGN_VARIABLE;
int KEEP, FLAGKEEP;
FILE *file_meanA; // the four files containing means of the two channels
double A_mean[COL_MAX*(ROW_MAX-16)];
double A_sigma[COL_MAX*(ROW_MAX-16)];

// input command from user
static char line[256];

///////////////////////////////////////////////////////////////////



int TESTAPP_BlockRead_ch(TESTAPP_HANDLE hTESTAPP, TESTAPP_ADDR ad_sp, TESTAPP_MODE ad_mode, int channel_flag, int KEEPthat)
{
    int col,row,row2,amuxchan,ochan,smpl,skip;
    UINT addr = 0;
    UINT rawdata[COL_MAX][ROW_MAX][SAMPLE_MAX];
    UINT data[COL_MAX][ROW_MAX][SAMPLE_MAX];
    UINT crap,second1,second2;
    int samp1,samp2,diff;
    int diffmax = 0;
    int colmax = 0;
    int rowmax = 0;
    int FLAGK =0;
    float trigg_quality_max = -1000.;
    float trigg_quality = 0.;

    char tmp[512], tmp1[512], datarec[512];

    int TRIG_LEVEL;
    int SKIP_MAX, SKIP_MAX2;
    int p1_col, p1_row, p2_col, p2_row, p3_col, p3_row; 
    int p4_col, p4_row, p5_col, p5_row, p6_col, p6_row;
    int p7_col, p7_row, p8_col, p8_row, p9_col, p9_row;

    int line_of_mean;

    FLAGKEEP = KEEPthat;
    
    if ((channel_flag==1)||(channel_flag==-99)) {
      //printf("CHANNEL A\n");
      if (channel_flag==-99) TRIG_LEVEL = -1;
      SKIP_MAX = A_SKIP_MAX;
      SKIP_MAX2 = A_SKIP_MAX2;
      p1_col = A_p1_col;
      p1_row = A_p1_row;
      p2_col = A_p2_col;
      p2_row = A_p2_row;
      p3_col = A_p3_col;
      p3_row = A_p3_row;
      p4_col = A_p4_col;
      p4_row = A_p4_row;
      p5_col = A_p5_col;
      p5_row = A_p5_row;
      p6_col = A_p6_col;
      p6_row = A_p6_row;
      p7_col = A_p7_col;
      p7_row = A_p7_row;
      p8_col = A_p8_col;
      p8_row = A_p8_row;
      p9_col = A_p9_col;
      p9_row = A_p9_row;
    }
    else {
      printf("This program is written for a ONE detector readout only!!! ERROR!!! \n");
    }
    
    //    printf("Offset: Data\n");

    // collect data sample
    //
    for(smpl=0;smpl<SAMPLE_MAX;smpl++)
      {
	for(skip=0;skip<SKIP_MAX;skip++)
	  {
	    crap = TESTAPP_ReadWord(hTESTAPP, ad_sp, addr); // skip these values
	  }
	for(col=0;col<COL_MAX;col++)
	  {
	    //	    for(row=0;row<ROW_MAX;row++)
	    //	      {
		for(amuxchan=0;amuxchan<AMUX_MAX;amuxchan++)
		  {
		  for(ochan=0;ochan<OCHAN_MAX;ochan++)
		    {
		      row2 = 4*ochan + amuxchan;
		      //printf("row, row2 = %d : %d \n",row,row2);
		      rawdata[col][row2][smpl] = TESTAPP_ReadWord(hTESTAPP, ad_sp, addr);
		    }
		  }
		//	      }
	  }
	for(skip=0;skip<SKIP_MAX2;skip++)  
	  {
	    crap = TESTAPP_ReadWord(hTESTAPP, ad_sp, addr); // skip these values on 2nd time through
	  }
      }
    //
    // process for alignment/pairing
    //

	for(col=0;col<COL_MAX;col++)
	  {
	    for(row=16;row<ROW_MAX;row++)
	      {
		samp1 = (rawdata[col][row][0])&0x03FF;
		samp2 = (rawdata[col][row][1])&0x03FF;
		diff = samp2-samp1;
		if (diff<-200) {
		  samp2=samp2+512;
		  diff=samp2-samp1;
		}
		if ((col==131) && (row==16)) {
		  if ((samp1!=511)||(samp2!=511))
		    //if (diff>10) 
		    {
	      	      OVERWRITE_KEEP_EVT=1; // MIS-ALIGNEMENT CONDITION!!!!!!!!!!!!!!!!!!!!!!!! 
		      if (NO_MISALIGNEMENT==1)
			{
			  OVERWRITE_KEEP_EVT=0;
			}
		      //printf("MIS-ALIGNEMENT CONDITION!!!!!!!!!!!!!!!!!!!!!!!! \n");
		      MISALIGN_VARIABLE++;
		    }
		}
		
		if( (col < 129) & (col > 1) ) 
		  {
		    if( (row > 17) & (row < 62) ) 
		      {
			if( !( (col == p1_col) & (row == p1_row)))
			  {
			    if( !( (col == p2_col) & (row == p2_row)))
			      {
				if( !( (col == p3_col) & (row == p3_row)))
				  {
				    if( !( (col == p4_col) & (row == p4_row)))
				      {
					if( !( (col == p5_col) & (row == p5_row)))
					  {
					    if( !( (col == p6_col) & (row == p6_row)))
					      {
						if( !( (col == p7_col) & (row == p7_row)))
						  {
						    if( !( (col == p8_col) & (row == p8_row)))
						      {
							if( !( (col == p9_col) & (row == p9_row)))
							  {
							    line_of_mean=48*col+row-16;
							    
							    if (channel_flag==1) {
							      if ((A_sigma[line_of_mean]) !=0) {

								if ((evtnum%20)==10) {
								  if ((col==125) && (row==60)) {
								    for (i=1;i<20;i++) {
								      Online_Noise_in_A[i-1]=Online_Noise_in_A[i];
								    }
								    Online_Noise_in_A[19]=diff;
								    Online_Noise_A=0;
								    for (i=19;i>=0;i--) {
								      Online_Noise_A=Online_Noise_A+(Online_Noise_in_A[i]/20.0);
								    }
								    printf("leak current drift pixel 125 60 for detA: %f\n",Online_Noise_A);
								    Drift_A = Online_Noise_A - A_mean[line_of_mean];
								  }
								}

								trigg_quality = (diff - (A_mean[line_of_mean])) / (A_sigma[line_of_mean]);
								if (trigg_quality > trigg_quality_max) {
								  trigg_quality_max = trigg_quality;
								  diffmax = diff;
								  colmax = col;
								  rowmax = row;
								}
								if ((diff - (A_mean[line_of_mean])) > (A_SIGMA * A_sigma[line_of_mean]))
								  { 
								    FLAGK=1;
								    TRIG_A=1;
								    Trigger_on_A;
								  }
							      }
							    }
							    else if ((channel_flag==-99)||(channel_flag==-98)||(channel_flag==-97)||(channel_flag==-96)) {}
							    else {
							      printf("ERROR, out of channel range!!!\n");
							    }
							  }
						      }
						  }
					      }
					  }
				      }
				  }
			      }
			  }
		      }
		  }
		//	    printf("%d %d %d \n",samp1,samp2,diff);
	      }
	  }

    //    printf("Diff max = %d \n",diffmax);
    //    printf("Col max, Row max = %d %d \n",colmax,rowmax);

    //
    // dump event
    //

    if (FLAGK==1) {
      FLAGKEEP=FLAGKEEP+1;
    }

	
	if (channel_flag == -99) {      
	  printf("End of 1st dummy loop %d \n", channel_flag);  
	}
	else if (channel_flag == -98) {
	  printf("End of 2nd dummy loop %d \n", channel_flag);
	}
	else if (channel_flag == -97) {
	  printf("End of 2nd dummy loop %d \n", channel_flag);
	}
	else if (channel_flag == -96) {
	  printf("End of 2nd dummy loop %d \n", channel_flag);
	}
	
	else if (channel_flag == 1) {
	  
	  if(FLAGKEEP<COINCIDENCE)
	    {
	      printf("Missed Coincidence with the following parameters:\n");	  
	      printf("A: Diff max  = %3d on %3d / %3d, SNR= %f \n",diffmax,colmax,rowmax,trigg_quality_max);
	      printf("  \n");
	    }

	  if ((FLAGKEEP>=COINCIDENCE)&&(OVERWRITE_KEEP_EVT!=1))	    
	    {
	      printf ("hi there\n");
	      if (PRINT_TO_FILE>0)
		{
		  if (COSMIC_FLAG>0)
		    {
		      printf ("hi there too\n");
		      triggered_evts++;
		      sprintf(tmp, "Evt_nb %d \n", triggered_evts);
		      fwrite(tmp, sizeof(char), strlen(tmp), fileout);

		      sprintf(tmp, "Diff max on channel A = %d, trigg_qual is %f \n", diffmax, trigg_quality_max);
		      fwrite(tmp, sizeof(char), strlen(tmp), fileout);
		      sprintf(tmp1, "Col max, Row max channel A = %d %d \n", colmax, rowmax);
		      fwrite(tmp1, sizeof(char), strlen(tmp1), fileout);
		      
		      printf("Diff max on channel A = %d, trigg_qual is %f \n", diffmax, trigg_quality_max);
		      printf("Col max, Row max channel A = %d %d \n", colmax, rowmax);
		      file_transcript = fopen(filename2, "a");
		      fprintf(file_transcript,"Triggered Event # = %d \n", triggered_evts);
		      fprintf(file_transcript,"Diff max on channel A = %d, trigg_qual is %f \n", diffmax, trigg_quality_max);
		      fprintf(file_transcript,"Col max, Row max channel A = %d %d \n", colmax, rowmax);
		      fclose(file_transcript);

		      printf("Triggered Event # = %d \n", triggered_evts);

		    }
		  
		  // write channel 1 data to file
		  for(col=0;col<COL_MAX;col++) 
		    {
		      for(row=16;row<ROW_MAX;row++)
			//for(row=0;row<ROW_MAX;row++)
			{
			  samp1 = (rawdata[col][row][0])&0x03FF;
			  samp2 = (rawdata[col][row][1])&0x03FF;
			  diff = samp2-samp1;

			  if (diff<-200) {
			    samp2=samp2+512;
			    diff=samp2-samp1;
			  }

			  //sprintf(datarec, "%d %d %d %d %d \n",col,row,samp1,samp2,diff);
			  //fwrite(datarec, sizeof(char), strlen(datarec), fileout);
			  fprintf(fileout,"%d %d %d %d %d \n",col, row, samp1, samp2, diff);
			}
		    }
		  // end of write channel 1 data to file
		}
	      else 
		{
		  // write channel 1 data to screen
		  printf("ON CHANNEL A. Diff max = %d at Col max, Row max = %d %d \n",diffmax,colmax,rowmax);
		  printf("trigg_quality_max %f \n", trigg_quality_max);
		  if (ALIGN_A==1) {
		    for(col=131;col<COL_MAX;col++) 
		      {
			for(row=11;row<ROW_MAX-29;row++)
			  {
			    samp1 = (rawdata[col][row][0])&0x03FF;
			    samp2 = (rawdata[col][row][1])&0x03FF;
			    diff = samp2-samp1;
			    printf("CHANNEL A %d %d %d %d %d \n",col,row,samp1,samp2,diff);
			    //get_gain1=get_gain1+0.01*samp1;
			    //get_gain2=get_gain2+0.01*samp2;
			    //printf("average on CHANNEL D: %f / %f\n",get_gain1, get_gain2);
			  }
		      }
		  }
		  else if (ALIGN_A==2) {
		    for(col=131;col<COL_MAX;col++) 
		      {
			for(row=15;row<ROW_MAX-43;row++)
			  {
			    samp1 = (rawdata[col][row][0])&0x03FF;
			    samp2 = (rawdata[col][row][1])&0x03FF;
			    diff = samp2-samp1;
			    printf("CHANNEL A: %d %d %d %d %d \n",col,row,samp1,samp2,diff);
			  }
		      }
		  }
		  else {
		  }
		  // end of write channel 1 data to screen
		 
		      triggered_evts++;
		      printf("Triggered Event # = %d \n", triggered_evts);

		}
	      //printf("End of channel %d readout \n", channel_flag);
	    }
	}
	else {
	  printf("This program is written for a ONE channel readout only!!! ERROR!!! \n");
	}
	

    return FLAGKEEP;
    
    
}



TESTAPP_HANDLE TESTAPP_LocateAndOpenBoard(DWORD dwVendorID, DWORD dwDeviceID)
{
    DWORD cards, my_card;
    TESTAPP_HANDLE hTESTAPP = NULL;

    if (dwVendorID==0)
    {
        printf ("Enter VendorID: ");
        fgets(line, sizeof(line), stdin);
        sscanf (line, "%x",&dwVendorID);
        if (dwVendorID==0) return NULL;

        printf ("Enter DeviceID: ");
        fgets(line, sizeof(line), stdin);
        sscanf (line, "%x",&dwDeviceID);
    }
    cards = TESTAPP_CountCards (dwVendorID, dwDeviceID);
    if (cards==0)
    {
        printf ("%s", TESTAPP_ErrorString);
        return NULL;
    }
    else if (cards==1)
        my_card = 1;
    else
    {
        UINT i;

if (DALIDEBUG)       printf ("Found %u matching PCI cards\n", (UINT)cards);
if (DALIDEBUG)        printf ("Select card (1-%u): ", (UINT)cards);
        i = 0;
        fgets(line, sizeof(line), stdin);
        sscanf (line, "%d",&i);
        if (i>=1 && i <=cards) my_card = i;
        else 
        {
            printf ("Choice is out of range\n");
            return NULL;
        }
    }
    if (!TESTAPP_Open (&hTESTAPP, dwVendorID, dwDeviceID, my_card - 1))
    {
        printf ("%s", TESTAPP_ErrorString);
        return NULL;
    }
if (DALIDEBUG)     printf ("TESTAPP PCI card found!\n");
    return hTESTAPP;
}



int main(int argc, char *argv[])
{

    int cmd;
    DWORD dwOffset;
    DWORD dwVal;
    TESTAPP_HANDLE hTESTAPP = NULL;
    HANDLE hWD;
    struct timeb start_time;			//declaring start time
    struct timeb end_time;                      //declaring the end time  
    ftime(&start_time);    			//getting start time of program

    struct timeb current_time;                      //declaring the current time  
    char time_tmp[512];
    char channel_defA[100],channel_defB[100],channel_defC[100],channel_defD[100];
    char channel_defA2[100],channel_defB2[100],channel_defC2[100],channel_defD2[100];
    int col, row;
    double data_A0,data_A1,data_A2,data_A3;
    double data_B0,data_B1,data_B2,data_B3;
    double data_C0,data_C1,data_C2,data_C3;
    double data_D0,data_D1,data_D2,data_D3;
    char xxA[2];
    char xxB[2];
    char xxC[2];
    char xxD[2];

    int inoise;

    printf ("\n DALI Rev. B diagnostic utility.\n");
    //    printf ("Application accesses hardware using WinDriver.\n");
    // Make sure WinDriver is loaded
    if (!PCI_Get_WD_handle(&hWD))
        return 0;
   WD_Close (hWD);

    hTESTAPP = TESTAPP_LocateAndOpenBoard(VENDOR_ID, DEVICE_ID);

    if (hTESTAPP)
      {

    // Master Reset (MRS)  -- MUST include, otherwise segmentation faults!

	dwOffset = 0x54;  // GPIOC address offset

	dwVal = 0x00492000;  // no Evt Clear & sel1 off & sel0 off 
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);


	///////////////////////////////////////////////////////////////
	//                   INITIALIZATION PHASE                    //

	printf ("YOU'RE RUNNING A ONE DETECTOR VERSION OF THE PROGRAM, WITH CAP1\n");

	A_SKIP_MAX=8;  //number of samples to blow off due to ADC pipelining (frame1)
	A_SKIP_MAX2=7;  //number of samples to blow off due to ADC pipelining (frame2)
	

	if (PRINT_TO_FILE>0)
	  {
	    printf ("file name??? BEWARE, WILL OVERWRITE OLD FILES\n");
	    scanf("%s", filename);

	    if ((fileout = fopen(filename, "w")) == NULL)
	      fclose(fileout);

	    strncpy(filename2+4,filename,70);
	    printf("Opening filename = %s\n",filename);
	    printf("Transcript filename = %s\n",filename2);
	    file_transcript = fopen(filename2, "w");

	    printf ("Channel A definition (xx syntax only!) \n");
	    printf ("for ex, F1_5 and Cap1_3: 53. \n");
	    scanf("%s", xxA);
	    sprintf(channel_defA, "Channel A is: %s\n",xxA);
	    fwrite(channel_defA, sizeof(char), strlen(channel_defA), fileout);
	    fclose(fileout);
	    printf ("\nPLEASE NOTE THAT THE COHERENCE BETWEEN THE DETECTOR DEFINITION \n");
	    printf ("YOU GAVE AND THE STAT FILE YOU USE SHOULD BE CHECKED!\n\n");
	    
	  }

	if ((log_file = fopen(logfile, "w")) == NULL)
	  fclose(log_file);	
	sprintf(time_tmp, "Starting Time = %d seconds.\n",start_time.time);
	fwrite(time_tmp, sizeof(char), strlen(time_tmp), log_file);
	fclose(log_file);


	if ((file_meanA = fopen(tmp_fileA, "r")) == NULL)
	  printf("Can not open file CHANNEL A\n");
	for(col=0;col<COL_MAX;col++) 
	  {
	    for(row=0;row<ROW_MAX-16;row++)
	      {
		fscanf(file_meanA, "%lf%lf%lf%lf",&data_A0,&data_A1,&data_A2,&data_A3);
		A_mean[col*(ROW_MAX-16)+row] = data_A2;
		A_sigma[col*(ROW_MAX-16)+row] = data_A3;		
		if ((col*(ROW_MAX-16)+row) == 6044) {
		  printf("A_mean/sigma %f/%f for col %d row %d\n",A_mean[col*(ROW_MAX-16)+row],A_sigma[col*(ROW_MAX-16)+row],(int) data_A0,(int) data_A1);
		}
	      }
	  }
	printf("A_mean/sigma %f/%f for col %d row %d\n",A_mean[131*(ROW_MAX-16)+47],A_sigma[131*(ROW_MAX-16)+47],(int) data_A0,(int) data_A1);
	fclose(file_meanA);


	if (PRINT_TO_FILE>0)
	  {
	    printf ("\nYOU USE: for channel A : %s \n", tmp_fileA);	    
	  }

	for (inoise=0;inoise<20;inoise++){
	  Online_Noise_in_A[inoise]=0;
	}


	//                END OF INITIALIZATION PHASE                //
	///////////////////////////////////////////////////////////////



	///////////////////////////////////////////////////////////
	// this part is to have a first dummy readout:           //
	// independant of stopping conditions, the first readout //
	// recorded should then be alright....                   //


	dwVal = 0x00592000;  // force Evt Clear & sel1 off & sel0 off
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);	
	dwVal = 0x004b2000;  // no Evt Clear & sel1 on & sel0 off
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);

	// add trigger initiation

	dwVal = 0x00C92000;  // force Trigger high
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);	

	dwVal = 0x00000000;
	printf ("in the dummy readout loop\n");

	while(!((dwVal & 0x00000800)==0x00000800))
	  {
	    dwVal = TESTAPP_ReadDword(hTESTAPP, 0, dwOffset);
	    //printf("GPIOC Register set to: %x\n",dwVal);
	  }
	if (hTESTAPP) TESTAPP_BlockRead_ch(hTESTAPP,2,TESTAPP_MODE_WORD,-99,KEEP);
	
	dwVal = 0x00592000;  // force Evt Clear & sel1 off & sel0 off
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);	
	dwVal = 0x004b2000;  // no Evt Clear & sel1 on & sel0 off
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);
	
	// add trigger initiation

	dwVal = 0x00C92000;  // force Trigger high
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);	

	dwVal = 0x00000000;
	while(!((dwVal & 0x00000800)==0x00000800))
	  {
	    dwVal = TESTAPP_ReadDword(hTESTAPP, 0, dwOffset);
	    //printf("GPIOC Register set to: %x\n",dwVal);
	  }
	if (hTESTAPP) TESTAPP_BlockRead_ch(hTESTAPP,2,TESTAPP_MODE_WORD,-98,KEEP);

	dwVal = 0x0592000;  // force Evt Clear & sel1 off & sel0 off
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);
	dwVal = 0x0496000;  // no Evt Clear & sel1 off & sel0 on
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);
	
	// add trigger initiation

	dwVal = 0x00C92000;  // force Trigger high
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);	

	dwVal = 0x00000000;
	while(!((dwVal & 0x00000800)==0x00000800))
	  {
	    dwVal = TESTAPP_ReadDword(hTESTAPP, 0, dwOffset);
	    //		printf("GPIOC Register set to: %x\n",dwVal);
	  }
	if (hTESTAPP) TESTAPP_BlockRead_ch(hTESTAPP,2,TESTAPP_MODE_WORD,-97,KEEP);

	dwVal = 0x0592000;  // force Evt Clear & sel1 off & sel0 off
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);
	dwVal = 0x04b6000;  // no Evt Clear & sel1 on & sel0 on
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);
	
	// add trigger initiation

	dwVal = 0x00C92000;  // force Trigger high
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);	

	dwVal = 0x00000000;
	while(!((dwVal & 0x00000800)==0x00000800))
	  {
	    dwVal = TESTAPP_ReadDword(hTESTAPP, 0, dwOffset);
	    //		printf("GPIOC Register set to: %x\n",dwVal);
	  }
	if (hTESTAPP) TESTAPP_BlockRead_ch(hTESTAPP,2,TESTAPP_MODE_WORD,-96,KEEP);


	dwVal = 0x0592000;  // force Evt Clear & sel1 off & sel0 off
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);
	dwVal = 0x00492000;  // no Evt Clear & sel1 on & sel0 off
	TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);

	
	//printf("test\n");

	
	// this part was to have a first dummy readout:          //
	// independant of stopping conditions, the first readout //
	// recorded should then be alright....                   //
	///////////////////////////////////////////////////////////

	for(evtnum=0;evtnum<EVT_MAX;evtnum++)
	  {

	    Trigger_on_A=0;
	    TRIG_A=0;
	    
	    if ((evtnum%write_to_logfile_cycle)==0) {
	      if ((log_file = fopen(logfile, "a")) == NULL)
		fclose(log_file);	
	      ftime(&current_time);
	      sprintf(time_tmp, "Current Time = %d seconds. Time from start = %d seconds for %d events.\n",current_time.time,(current_time.time-start_time.time), evtnum);
	      fwrite(time_tmp, sizeof(char), strlen(time_tmp), log_file);
	      sprintf(time_tmp, "Nb of misaligned events: %d.\n",MISALIGN_VARIABLE);
	      fwrite(time_tmp, sizeof(char), strlen(time_tmp), log_file);

	      fclose(log_file);
	    }

	    KEEP=0;
	    OVERWRITE_KEEP_EVT=0;
	    FLAGKEEP=0;


	    if (PRINT_TO_FILE>0)
	      {
		if ((fileout = fopen(filename, "a")) == NULL)
		  printf("Can not open file\n");		  
	      }
	    

	    //printf("KEEP ici: %d \n", KEEP);


	      // add trigger initiation
	      dwVal = 0x0C92000;  // no Evt Clear & sel1 off & sel0 off
	      TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);

	      dwVal = 0x00000000;
	      while(!((dwVal & 0x00000800)==0x00000800))
		{
		  dwVal = TESTAPP_ReadDword(hTESTAPP, 0, dwOffset);
		  //printf("1st GPIOC Register set to: %x\n",dwVal);
		}
	      if (DALIDEBUG)     printf("Event # = %d \n\n",evtnum);
	      if (DALIDEBUG)  printf("\n Event # = %d\n", evtnum);
	      if (hTESTAPP) KEEP=TESTAPP_BlockRead_ch(hTESTAPP,2,TESTAPP_MODE_WORD,1,KEEP);
	      /////////////////////////////////
	      // end of first channel readout//
	      /////////////////////////////////


	      printf("Event number = %d -- coincidence = %d\n", evtnum,KEEP);
	      printf("Average drift from pedestal in pixel 125 60 of detector A: %f \n\n",Drift_A);
	      
	      printf("*** Cumulative Number of Triggered Event # = %d \n", triggered_evts);
	      printf("==================================================\n\n");

	      if (PRINT_TO_FILE>0)
		{
		  fclose(fileout);
		}	
	      
	    

	    dwVal = 0x0592000;  // force Evt Clear & sel1 off & sel0 off
	    TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);
	    dwVal = 0x0492000;  // force Evt Clear & sel1 off & sel0 off
	    TESTAPP_WriteDword(hTESTAPP, 0, dwOffset, dwVal);
	    

	  }
      }
    
    //getting the ending time. and printing it.
    ftime (&end_time);
    if(end_time.millitm<start_time.millitm)
    {
     	printf("Elapsed Time = %d seconds",end_time.time-start_time.time-1);
      	printf(" %d milliseconds\n",(end_time.millitm+1000)-start_time.millitm);
    }
    else
    {
     	printf("Elapsed Time = %d seconds",end_time.time-start_time.time);
        printf(" %d milliseconds\n",end_time.millitm-start_time.millitm);
    }
//    printf(" Start Time = %dsec and %dmsec\n",start_time.time,start_time.millitm);
//    printf("    End Time = %dsec and %dmsec\n",end_time.time,end_time.millitm); 


    if (hTESTAPP)
        TESTAPP_Close(hTESTAPP);

    return 0;
}

