//////////////////////////////////////////
 
// Data to root conversion root script
 
//
 
// Contributors: Rok Pestotnik, Rok Dolenec, Dino Tahirovic
 
//
 
// 3/1/2014 TDC cut relative to tdc offset
 
// 5/3/2014 TH3F h_correctedTDC; commented 'delete' commands
 
// 12/3/2014 declarations of all histos before while{}
 
 
 
#include "stdio.h"
 
#include "TROOT.h"
 
#include "TFile.h"
 
#include "TNtuple.h"
 
#include "TH1F.h"
 
#include "TH2F.h"
 
#include "TH3F.h"
 
#include "TF1.h"
 
#include "TMath.h"
 
#include "TStyle.h"
 
#include "TCanvas.h"
 
#include "TLine.h"
 
#include "zlib.h"
 
 
 
// ------------------------------------------------------------------------------
 
 
 
#define POSMARG 1000
 
 
 
#define READBUFFERLENGTH 10000
 
 
 
// data format
 
#define MAXDATA 16
 
#define NCH 64
 
#define TDC_BIN 1.0416 // 1 TDC bin in ns
 
#define MIKRO_BIN 0.49609/1000. //1 mikro step in mm; stage MM3MF
 
#define OFFSETX 4800  // Right edge of SiPM+Lightguide
 
#define OFFSETY 3400 // Lower edge of SiPM+Lightguide
 
 
 
#define RUNREC_ID 1
 
#define ENDREC_ID 2
 
#define POSREC_ID 3
 
#define EVTREC_ID 4
 
#define THRREC_ID 5
 
#define BIASREC_ID 6
 
 
 
typedef struct {
 
  unsigned int id,len;
 
  unsigned int fver,time;
 
  unsigned int thLow, thUp, thStep;
 
  unsigned int biasLow, biasUp, biasStep;
 
  unsigned int nev,nch,ped,xy;
 
  int nx,x0,dx,ny,y0,dy;
 
} RUNREC;
 
RUNREC *runrec;
 
RUNREC run;
 
 
 
typedef struct {
 
  unsigned int id,len;
 
  unsigned int time;
 
} ENDREC;
 
ENDREC *endrec;
 
 
 
typedef struct {
 
  unsigned int id,len;
 
  unsigned int time;
 
  int ix;
 
  int x;
 
  int xset;
 
  int iy;
 
  int y;
 
  int yset;
 
} POSREC;
 
POSREC *posrec;
 
POSREC pos;
 
 
 
typedef struct {
 
    unsigned int id;
 
    unsigned int len;
 
    unsigned int nev;
 
    } EVTREC;
 
EVTREC *evtrec;
 
 
 
typedef struct {
 
  unsigned int id;
 
  unsigned int len;
 
  unsigned int threshold;
 
} THRREC;
 
THRREC *thrrec;
 
THRREC thr;
 
 
 
typedef struct {
 
  unsigned int id;
 
  unsigned int len;
 
  unsigned int bias;
 
} BIASREC;
 
BIASREC *biasrec;
 
BIASREC bias;
 
 
 
double padCenter[NCH][2];
 
 
 
int position(int, int, int);
 
 
 
// ------------------------------------------------------------------------------
 
 
 
int analysisBias(char* dfile0="test", int dbg=0, double tdcCut=5.0)
 
{
 
  const double c_tdcOffset = 372*TDC_BIN; // ns, SiPM4
 
    
 
  printf(" Data to root conversion program\nUsage:\nd2r(input file name <without.dat>, debug on/off, TDC cut +-[ns])\n\n");
 
  
 
  char fullname[256];
 
  char sbuff[256];
 
  FILE *fp;
 
  
 
  //Chanel information
 
  
 
  double tdcOffset[NCH];
 
  sprintf(fullname, "d2r.ini");
 
  if( (fp=fopen(fullname, "rt")) == NULL )
 
    printf("Cannot open pad centers file %s !!!\n", fullname);
 
  else {
 
    printf("Opened pad centers file %s\n", fullname);
 
    char* result = fgets(sbuff,256, fp);
 
    if (dbg) printf("Read buffer %s\n", result);
 
    printf("%s", sbuff);
 
    for(int i=0; i<NCH; i++) {
 
      int channel;
 
      int message = fscanf(fp, "%d %lf %lf %lf\n", &channel, &padCenter[i][0], &padCenter[i][1], &tdcOffset[i]);
 
      if (dbg) printf("Read d2r.ini returned %d\n", message);
 
    }
 
    fclose(fp);
 
  }
 
  for(int i=0; i<NCH; i++) {
 
    tdcOffset[i] += c_tdcOffset;
 
    printf("%.2lf %.2lf %.2lf\n", padCenter[i][0], padCenter[i][1], tdcOffset[i]);
 
    }
 
    
 
        //data buffer
 
        unsigned int readbuf[READBUFFERLENGTH];
 
        unsigned int buf[READBUFFERLENGTH];
 
        
 
        //data file
 
        gzFile dfp;
 
        char dfile[256];
 
        int ftype=0;
 
        int fcount=1;
 
        do {
 
          switch(ftype++) {
 
            case 0:
 
              sprintf(dfile, "./data/%s_file%02d.dat", dfile0, fcount);
 
              break;
 
            case 1:
 
              sprintf(dfile, "./data/%s_file%02d.dat.gz", dfile0, fcount);
 
              break;
 
            case 2:
 
              sprintf(dfile, "./data/%s_file%02d.gz", dfile0, fcount);
 
              break;
 
            default:
 
        printf("  Cannot find data file for %s !!!\n", dfile0);
 
        return -1;
 
          }
 
          dfp=gzopen(dfile,"rb");
 
        } while(!dfp);
 
        printf("Opened data file %s\n", dfile);
 
                
 
        //opens ROOT file 
 
        char fnameroot[256];
 
        sprintf(fnameroot, "root/%s.root", dfile0); 
 
        TFile rootfile(fnameroot,"RECREATE",dfile0);
 
        if (rootfile.IsZombie()) {
 
       std::cout << "Error opening file" << std::endl;
 
       exit(-1);
 
  }
 
  if (rootfile.IsOpen()) std::cout << "ROOT file opened for writing." << std::endl;
 
                
 
  // -----------------------------------------------
 
        // loop trough records
 
        unsigned int rec_id, rec_len;
 
        unsigned int ulsize = sizeof(unsigned int);
 
        //unsigned int ulsize = 4;
 
        if (dbg) printf("Size of unsigned int: %lu\n", sizeof(unsigned int));
 
        int ceve=0;
 
        int end_of_file = 0;
 
        
 
        int ii;
 
        int nint;
 
        int nb;
 
        int status;
 
        char hname[256];
 
        TH2F* htdc = new TH2F("htdc",";TDC channel;SiPM channel",512,-0.5,511.5,NCH,-0.5,NCH-0.5);
 
  TH3F* h_correctedTDC = new TH3F("h_correctedTDC",";SiPM channel; ASD threshold [V]; t [ns]",
 
                                                          NCH, -0.5, NCH-0.5,
 
                                                          101,  1.0, 2.0,
 
                                                          33, -16.5*TDC_BIN, 16.5*TDC_BIN);
 
        TH1F* hnhitsx[NCH]; // move to 2d with (channel, position)
 
        TH1F* hnhitsy[NCH]; //-||-
 
        TH2F* h2d[NCH];     //-||-
 
        TH2F* h_bias = new TH2F("h_bias", "", 64, 0, 63, 20, 71.0,73.0);
 
        TH2F* h_threshold = new TH2F("h_threshold",";SiPM ch;Threshold[V]",
 
                                                    64,-0.5,63.5,
 
                                                                      101, 1.0, 2.0);
 
        TH2F* h_ch33 = new TH2F("h_ch33","ch. 33;x;y",100,20000,30000,100,0,10000);
 
        TNtuple* nt = new TNtuple("nt", "nt", "ch:x:y:tdc");
 
        
 
        while(1) {      
 
                if(gzeof(dfp)) end_of_file = 1;         
 
 
 
                gzread(dfp, (voidp)&readbuf, 2*ulsize);
 
                rec_id=readbuf[0];
 
                rec_len=readbuf[1];
 
                
 
                
 
                if(dbg) printf("-----------------------------------------------\n");
 
                if(dbg) printf("[%d] rec_id = %d | rec_len = %u\n", ceve, rec_id, rec_len);
 
    
 
    int nSteps = 0;
 
    int nBiasSteps = 0;
 
    
 
                switch(rec_id)
 
                {               
 
                        case RUNREC_ID:
 
                          if (dbg) printf("RUNREC\n");
 
                                gzread(dfp, (voidp)&readbuf[2], (rec_len-2*ulsize));
 
                                runrec = (RUNREC *) readbuf;
 
                          run=*runrec; 
 
                                
 
                                if(dbg) {
 
                                        printf("RUNREC_ID\n");
 
                                        printf("id = %d, len = %d, time = %d\n", run.id, run.len, run.time);
 
                                        printf("nev = %d, nch = %d\n", run.nev, run.nch);
 
                                        printf("nx = %d, x0 = %d, dx = %d\n", run.nx, run.x0, run.dx);
 
                                        printf("ny = %d, y0 = %d, dy = %d\n", run.ny, run.y0, run.dy);
 
                                        printf("thLow = %d, thUp = %d, thStep = %d\n", run.thLow, run.thUp, run.thStep);
 
                                }
 
                                
 
                                //create histograms
 
                                //nt = (TNtuple*) gROOT->FindObject("nt");
 
                                //if (nt) delete nt;
 
                                
 
                                //sprintf(hname, "htdc");
 
                                //htdc = (TH2F*) gROOT->FindObject(hname);
 
                                //if (htdc) delete htdc;
 
                                //htdc = new TH2F("htdc",";TDC channel;SiPM channel",512,0,512,NCH,0,NCH);
 
                                
 
        //TH1F* gsumV673A[NCH/16] = new TH1F(hn,hname,256,-0.5,255.5);
 
                                for(int i=0; i<NCH; i++) {
 
                                  /*    
 
                                        sprintf(hname, "htdcpos%d", i);
 
                                        htdcpos[i] = (TH1F*)gROOT->FindObject(hname);
 
                                        if(htdcpos[i]) delete htdcpos[i];
 
                                        htdcpos[i] = new TH1F(hname, hname, 512, 0, 512*TDC_BIN);
 
                                        
 
                                        sprintf(hname, "htdc%d", i);
 
                                        htdc[i] = (TH1F*)gROOT->FindObject(hname);
 
                                        if(htdc[i]) delete htdc[i];
 
                                        htdc[i] = new TH1F(hname, hname, 512, 0*TDC_BIN, 512*TDC_BIN);
 
                                        */
 
                                        
 
                                        sprintf(hname, "hnhitsx%d", i);
 
                                        hnhitsx[i] = (TH1F*)gROOT->FindObject(hname);
 
                                        if(hnhitsx[i]) delete hnhitsx[i];
 
                                        hnhitsx[i] = new TH1F(hname, hname, run.nx, 
 
                                                                            (run.x0 - OFFSETX - 0.5*run.dx)*MIKRO_BIN, 
 
                                                                            (run.x0 - OFFSETX + (run.nx-0.5)*run.dx)*MIKRO_BIN);
 
                                        
 
                                        sprintf(hname, "hnhitsy%d", i);
 
                                        hnhitsy[i] = (TH1F*)gROOT->FindObject(hname);
 
                                        if(hnhitsy[i]) delete hnhitsy[i];
 
                                        //hnhitsy[i] = new TH1F(hname, hname, run.ny, (run.y0-0.5*run.dy)*MIKRO_BIN, (run.y0+(run.ny-0.5)*run.dy)*MIKRO_BIN);
 
                                        hnhitsy[i] = new TH1F(hname, hname, run.ny, 
 
                                                                            (run.y0 - 0.5*run.dy - OFFSETY)*MIKRO_BIN, 
 
                                                                            (run.y0 + (run.ny-0.5)*run.dy - OFFSETY)*MIKRO_BIN);
 
                                        //hnhitsy[i] = new TH1F(hname, hname, 100, 0,100);
 
                                        
 
                                        sprintf(hname, "h2d%d", i);
 
                                        h2d[i] = (TH2F*)gROOT->FindObject(hname);
 
                                        if(h2d[i]) delete h2d[i];
 
                                        h2d[i] = new TH2F(hname, hname, run.nx, 
 
                                                                        (run.x0 - OFFSETX - 0.5*run.dx)*MIKRO_BIN, 
 
                                                                        (run.x0 - OFFSETX + (run.nx-0.5)*run.dx)*MIKRO_BIN,
 
                                                                        run.ny, 
 
                                                                        (run.y0 - OFFSETY - 0.5*run.dy)*MIKRO_BIN, 
 
                                                                        (run.y0 - OFFSETY + (run.ny-0.5)*run.dy)*MIKRO_BIN); 
 
                                }
 
                                
 
                                nBiasSteps = (run.biasUp - run.biasLow)/double(run.biasStep) + 1;
 
                                
 
                                h_correctedTDC = (TH3F*) gROOT->FindObject("h_correctedTDC");
 
                                if (h_correctedTDC) delete h_correctedTDC;
 
                                nSteps = (run.thUp - run.thLow)/double(run.thStep) + 1;
 
                                if (dbg) printf("nSteps %d\n", nSteps);
 
                                h_correctedTDC = new TH3F("h_correctedTDC",";SiPM channel; ASD threshold [V]; t [ns]",
 
                                                          NCH, 
 
                                                          -0.5, 
 
                                                          NCH-0.5,
 
                                                          nBiasSteps,  
 
                                                          (run.biasLow - 0.5*run.biasStep)/1000.0,
 
                                                          (run.biasUp  + 0.5*run.biasStep)/1000.0,
 
                                                          2*tdcCut+1, 
 
                                                          -tdcCut*TDC_BIN - 0.5*TDC_BIN,
 
                                                           tdcCut*TDC_BIN + 0.5*TDC_BIN);
 
                                                          
 
                                h_bias = (TH2F*) gROOT->FindObject("h_bias");
 
                                if (h_bias) delete h_bias;
 
                                h_bias = new TH2F("h_bias",";Channel; Bias [V]", 64, -0.5, 63.5,
 
                                                                nBiasSteps,
 
                                                               (run.biasLow - 0.5*run.biasStep)/1000.0,
 
                                                               (run.biasUp  + 0.5*run.biasStep)/1000.0);
 
                                                               
 
                                
 
                                if (h_threshold) delete h_threshold;
 
                                h_threshold = new TH2F("h_threshold",";SiPM ch;Threshold[V]",64,-0.5,63.5,
 
                                                                      nSteps, 
 
                                                                      (run.thLow - 0.5*run.thStep)/1000.0, 
 
                                                                      (run.thUp  + 0.5*run.thStep)/1000.0);
 
                                
 
                                //h_threshold = new TH2F("h_threshold","Threshold scan;SiPM ch;Threshold[mV]",64,-0.5,63.5,
 
                                //                                      101,995,2005);
 
                                                                      
 
                                if (h_ch33) delete h_ch33;
 
                                h_ch33 = new TH2F("h_ch33","ch. 33;x;y",100,20000,30000,100,0,10000);
 
 
 
                                if (dbg) printf("RUNREC: all histos created.\n");
 
                                break;
 
                        
 
                        case POSREC_ID:
 
                          if (dbg) printf("POSREC\n");
 
                                gzread(dfp, (voidp)&readbuf[2], (rec_len-2*ulsize));
 
                                posrec = (POSREC *) readbuf;
 
                                pos=*posrec;
 
                                
 
                                if(dbg) {
 
                                        printf("POSREC_ID\n");
 
                                        printf("id = %d, len = %d, time = %d\n", posrec->id, posrec->len, posrec->time);
 
                                        printf("ix = %d, x = %d, xset = %d\n", posrec->ix, posrec->x, posrec->xset);
 
                                        printf("iy = %d, y = %d, yset = %d\n", posrec->iy, posrec->y, posrec->yset);
 
                                } else  printf("        [%d,%d] %d, %d\n", pos.ix, pos.iy, pos.xset, pos.yset);
 
                                
 
                                break;
 
                                
 
                        case EVTREC_ID:
 
                          gzread(dfp, (voidp)&readbuf[2], ulsize); // last field of event record
 
                          evtrec = (EVTREC *) readbuf;
 
                          //evtrec->nev = buf[0];
 
                          //if (rec_len < 0 || rec_len > 10000) {
 
                          if (rec_len > READBUFFERLENGTH) {
 
                            printf("Len %u\n", rec_len);
 
                            return(1);
 
                            }
 
                          nb = rec_len - 3*ulsize; // no. of bytes to read
 
                                gzread(dfp, (voidp)&buf, nb);
 
        
 
                                if(dbg) {
 
                                        printf("EVTREC_ID\n");
 
                                        printf("id = %d, len = %d, nev = %d\n", evtrec->id, evtrec->len, evtrec->nev);
 
                                        //for(int datai = 0; datai < NCH; datai++) printf("%u ", evtrec->data[datai]);
 
                                        //printf("\n");
 
                                        //for(int datai = NCH; datai < NCH+NCH; datai++) printf("%u ", evtrec->data[datai]);
 
                                        //printf("\n");
 
                                        break;
 
                                }
 
                                
 
                                nint = nb / ulsize; // no. of subrecords
 
                                if (dbg) printf("No. of subrecords %d \n", nint);
 
                                ii=0;
 
        while (ii<nint){
 
          int recid = buf[ii++];
 
          int len   = buf[ii++];
 
          if (dbg) printf("Buffer pointer %d\n", ii);     
 
          unsigned int *dbuf = (unsigned int *)&buf[ii];
 
          //if (n%1000==0) 
 
                if (dbg) printf("%d 0x%03x Len=%d\n",evtrec->nev,recid,len);
 
          //unsigned short edge;
 
          //int nhits;
 
                                  if (recid==0x140 || recid==0x141) {
 
            for (int i=0; i<len; i++) {
 
              int data      =  dbuf[i] & 0xFFFF ;
 
              int edge_type = (dbuf[i]>>16)&0x1  ;
 
              int overflow  = (dbuf[i]>>17)&0x1  ;
 
              int tdc_num   = (dbuf[i]>>25)&0x1  ;
 
              int channel   = ((dbuf[i]>>18)&0x1F) | tdc_num<<5 ;
 
              int ev_dat    = (dbuf[i]>>23)&0x1  ;    
 
              int last_dat  = (dbuf[i]>>30)&0x1  ;
 
              int nval_dat  = (dbuf[i]>>31)&0x1  ;
 
              if (dbg){
 
                if (ev_dat) printf("Event %d\n",data);
 
                else printf("ch=%d edge=%d ev=%d data=%d last=%d nval=%d\n",
 
                channel, edge_type,ev_dat,data,last_dat,nval_dat);
 
              }             
 
              if (!ev_dat){
 
                if (!edge_type && !overflow) {
 
                  htdc->Fill(data, channel);
 
                  if (dbg) printf("ch: %d tdc: %d\n", channel, data);
 
                  if (dbg) nt->Fill(channel, pos.ix, pos.iy, data);
 
                  double tdcmin = tdcOffset[channel] - tdcCut;
 
                  double tdcmax = tdcOffset[channel] + tdcCut;
 
                  double time = data*TDC_BIN - tdcOffset[channel];
 
                  if(time >= -tdcCut and time <= tdcCut) {
 
                    h_correctedTDC->Fill(channel, bias.bias/1000.0, time);
 
                    hnhitsx[channel]->Fill((pos.xset - OFFSETX) * MIKRO_BIN);
 
                    hnhitsy[channel]->Fill((pos.yset - OFFSETY) * MIKRO_BIN);
 
                    h2d[channel]->Fill((pos.xset - OFFSETX) * MIKRO_BIN, (pos.yset - OFFSETY) * MIKRO_BIN);
 
 
 
                    if (position(pos.xset-OFFSETX, pos.yset-OFFSETY, channel)) { 
 
                      h_ch33->Fill(pos.xset-OFFSETX, pos.yset-OFFSETY);
 
                      h_threshold->Fill(channel, thr.threshold/1000.0);
 
                      h_bias->Fill(channel, bias.bias/1000.0); 
 
                    }
 
                  }
 
                  //gV673A->Fill(data,channel);
 
                  //gsumV673A[channel/16]->Fill(data);
 
                } 
 
              }
 
              if (last_dat) break;
 
            }        
 
          } // if (recid== 0x140 || recid== 0x141)
 
          ii += len;
 
        } //while
 
 
 
                                break;
 
                  
 
                  case THRREC_ID:
 
                    status = gzread(dfp, (voidp)&readbuf[2], (rec_len-2*ulsize));
 
                    thrrec = (THRREC*) readbuf;
 
                    thr = *thrrec;
 
                    if (dbg) printf("THRREC id = %d len = %d threshold %d\n", 
 
                                    thrrec->id, thrrec->len, thrrec->threshold);
 
                    break;
 
                        
 
                        case ENDREC_ID:
 
                                gzread(dfp, (voidp)&readbuf[2], (rec_len-2*ulsize));
 
                                endrec = (ENDREC *) readbuf;
 
                                
 
                        case BIASREC_ID:
 
                          status = gzread(dfp, (voidp)&readbuf[2], (rec_len-2*ulsize));
 
                          biasrec = (BIASREC*) readbuf;
 
                          bias = *biasrec;
 
                          if (dbg) printf("BIASREC id = %d len = %d bias %d\n",
 
                                          bias.id, bias.len, bias.bias);
 
                          break;        
 
                                
 
                                if(dbg) {
 
                                        printf("ENDREC_ID\n");
 
                                        printf("id = %d, len = %d, time = %d\n", endrec->id, endrec->len, endrec->time);
 
                                } else printf(" ENDREC\n");
 
                                
 
        fcount++;
 
        switch(ftype-1) {
 
            case 0:
 
              sprintf(dfile, "./data/%s_file%02d.dat", dfile0, fcount);
 
              break;
 
            case 1:
 
              sprintf(dfile, "./data/%s_file%02d.dat.gz", dfile0, fcount);
 
              break;
 
            case 2:
 
              sprintf(dfile, "./data/%s_file%02d.gz", dfile0, fcount);
 
              break;
 
          }
 
        
 
        if(dfp) gzclose(dfp);
 
                
 
        dfp=gzopen(dfile,"rb");
 
        if(!dfp) {
 
          printf("      Cannot open data file: %s ---> Exiting\n", dfile);
 
                end_of_file = 1;
 
        } else {
 
          printf("      Opened data file: %s\n", dfile);
 
          end_of_file = 0;
 
        }
 
                        
 
                                break;
 
                        
 
                        default:
 
                                printf("switch(rec_id): default !!!\n");
 
                                end_of_file = 1;
 
                                break;
 
                }
 
                                
 
                ceve++;
 
                if ( (ceve%50000) == 0) printf("        Current event = %d\n", ceve);
 
                //if(dbg) if( ceve>dbg ) break;
 
                if (end_of_file) break;
 
  }
 
 
 
        if(dfp) {
 
          gzclose(dfp);
 
          //delete dfp;
 
        }
 
        //if(dbg) return 0;     
 
        if(rootfile.IsOpen()) {
 
          nt->Write();
 
                rootfile.Write();
 
                printf("Saved to %s\n", fnameroot);
 
                rootfile.Close();
 
                //delete rootfile;
 
        }               
 
        
 
        return 0;
 
}
 
 
 
int position(int x, int y, int channel)
 
{
 
  int flag = 0;
 
  if ( (x > (padCenter[channel][0] - 5040)) and (x < (padCenter[channel][0] + 5040)) and
 
      (y > (padCenter[channel][1] - 5040)) and (y < (padCenter[channel][1] + 5040)) ) flag = 1;
 
  return flag;
 
}