Proper message and abort in case of missing DATE_RUN_NUMBER env variable
[u/mrichter/AliRoot.git] / ITS / ITSSPDSCANda.cxx
1 /*
2 - Contact: - henrik.tydesjo@cern.ch
3 - Link: - http://tydes.home.cern.ch/tydes/doc/CalibrationOverview/CalibrationAlgorithms/
4 - Run Type: - DAQ_MIN_TH_SCAN,DAQ_MEAN_TH_SCAN,DAQ_UNIFORMITY_SCAN,DAQ_NOISY_PIX_SCAN,DAQ_PIX_DELAY_SCAN,DAQ_FO_UNIF_SCAN
5 - DA Type: - LDC
6 - Number of events needed:
7 - Input Files: - daq db config files: spd_standal_params,spd_perm_noisy ,  previous noisy lists: ./calibResults/ScanNoisy/* ,  raw data
8 - Output Files: - Ref Data: ./calibResults/ScanReference/* ,  DCS update: ./calibResults/ScanDCSconfigToFXS/* ,  OCDB update: ./calibResults/ScanNoisyToFXS/* ,  persistent files: ./calibResults/ScanNoisy/*
9 - Trigger types used: 
10 */
11
12 ////////////////////////////////////////////////////////////////////////////////
13 // This program can be compiled in two modes.                                 //
14 //                                                                            //
15 // 1. With the DAQ DA framework on. This is the default operating mode.       //
16 // Call this program with the name of the executable followed by the          //
17 // data files to process.                                                     //
18 //                                                                            //
19 // 2. Without the DAQ DA framework on. Define the SPD_DA_OFF environment var. //
20 // Call this program with the name of the executable followed by the          //
21 // runNr and the data files to process.                                       //
22 //                                                                            //
23 ////////////////////////////////////////////////////////////////////////////////
24
25 #ifndef SPD_DA_OFF
26 extern "C" {
27 #include "daqDA.h"
28 }
29 #endif
30 #include "event.h"
31 #include "monitor.h"
32 #include "AliRawReaderDate.h"
33 #include "AliITSRawStreamSPD.h"
34 #include "AliITSOnlineSPDscan.h"
35 #include "AliITSOnlineSPDscanSingle.h"
36 #include "AliITSOnlineSPDscanMultiple.h"
37 #include "AliITSOnlineSPDscanMeanTh.h"
38 #include "AliITSOnlineSPDscanAnalyzer.h"
39 #include "AliITSOnlineCalibrationSPDhandler.h"
40 #include "AliLog.h"
41 #include <iostream>
42 #include <fstream>
43 #include <TROOT.h>
44 #include <TPluginManager.h>
45 #include <TObjArray.h>
46 #include <TString.h>
47
48 int main(int argc, char **argv) {
49   if (argc<2) {
50     printf("Wrong number of arguments\n");
51     return -1;
52   }
53
54   // directory structure, hard coded
55   char *saveDirNoisy         = "./calibResults/ScanNoisy";          // may NOT delete content
56   char *saveDirNoisyToFXS    = "./calibResults/ScanNoisyToFXS";     //     may delete content
57   char *saveDirDCSconfigToFXS= "./calibResults/ScanDCSconfigToFXS"; //     may delete content
58   char *saveDirRef           = "./calibResults/ScanReference";      //     may delete content
59   char *saveDirIdsToFXS      = "./calibResults/IdsToFXS";           //     may delete content
60   char *configFilesDir       = "./configFiles";                     //     may delete content
61
62   // make sure the directory structure is correct:
63   system("mkdir ./calibResults >& /dev/null");
64   system("mkdir ./calibResults/ScanNoisy >& /dev/null");
65   system("mkdir ./calibResults/ScanNoisyToFXS >& /dev/null");
66   system("mkdir ./calibResults/ScanDCSconfigToFXS >& /dev/null");
67   system("mkdir ./calibResults/ScanReference >& /dev/null");
68   system("mkdir ./calibResults/IdsToFXS >& /dev/null");
69   system("mkdir ./configFiles >& /dev/null");
70   // prameters config files
71   TString paramsFileName = Form("%s/standal_params.txt",configFilesDir);
72   TString permNoisyFileName = Form("%s/perm_noisy.txt",configFilesDir);
73
74   // This line is needed in case of a stand-alone application w/o
75   // $ROOTSYS/etc/system.rootrc file
76   gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
77                                         "*",
78                                         "TStreamerInfo",
79                                         "RIO",
80                                         "TStreamerInfo()");
81
82   // turn off annoying warning messages
83   new AliLog;
84   AliLog::Instance()->SetGlobalDebugLevel(-20);
85
86   // calib scan types
87   enum calib_types{MINTH,MEANTH,DAC,UNIMA,NOISE,DELAY};
88
89
90   // ********* STEP 0: Get configuration files from db (if there are any) , then read parameters*********
91   UInt_t nrTuningParams = 0;
92   TObjArray paramNames;  paramNames.SetOwner(kTRUE);
93   TObjArray paramVals;  paramVals.SetOwner(kTRUE);
94   
95   // tuning parameters:
96   Int_t status = 0;
97 #ifndef SPD_DA_OFF
98   TString idp = "spd_standal_params";
99   status=daqDA_DB_getFile(idp.Data(),paramsFileName.Data());
100   if (status) {
101     printf("Failed to get config file %s: status=%d. Using default tuning parameters.\n",idp.Data(),status);
102   }
103 #endif
104   if (status==0) {
105     ifstream paramsFile;
106     paramsFile.open(paramsFileName.Data(), ifstream::in);
107     if (paramsFile.fail()) {
108       printf("No config file (%s) present. Using default tuning parameters.\n",paramsFileName.Data());
109     }
110     else {
111       while(1) {
112         Char_t paramN[50];
113         Char_t paramV[50];
114         paramsFile >> paramN;
115         if (paramsFile.eof()) break;
116         paramsFile >> paramV;
117         TString* paramNS = new TString(paramN);
118         TString* paramVS = new TString(paramV);
119         paramNames.AddAtAndExpand((TObject*)paramNS,nrTuningParams);
120         paramVals.AddAtAndExpand((TObject*)paramVS,nrTuningParams);
121         nrTuningParams++;
122         if (paramsFile.eof()) break;
123       }
124       paramsFile.close();
125     }
126   }
127   //  for (UInt_t i=0; i<nrTuningParams; i++) {
128   //    printf("Entry %d: N=%s , V=%s\n",i,((TString*)paramNames.At(i))->Data(),((TString*)paramVals.At(i))->Data());
129   //  }
130
131   // perm noisy list:
132   Int_t permstatus = 0;
133 #ifndef SPD_DA_OFF
134   TString idn = "spd_perm_noisy";
135   permstatus=daqDA_DB_getFile(idn.Data(),permNoisyFileName.Data());
136   if (permstatus) {
137     printf("Failed to get config file %s: status=%d. No permanently noisy pixels will be added.\n",idn.Data(),permstatus);
138   }
139 #endif
140
141
142
143
144   // ********* STEP 1: Produce scan container files (Reference Data). ***********************************
145   int startSeg = 1;
146
147 #ifndef SPD_DA_OFF
148   if (getenv("DATE_RUN_NUMBER")==0) {
149     printf("DATE_RUN_NUMBER not properly set.\n");
150     return -1;
151   }
152   int runNr = atoi(getenv("DATE_RUN_NUMBER"));
153 #else
154   int runNr = atoi(argv[1]);
155   startSeg = 2;
156 #endif
157
158   // container objects
159   AliITSOnlineSPDscan *scanObj[20];
160   Bool_t bScanInit[20];
161   for (UInt_t eqId=0; eqId<20; eqId++) {
162     scanObj[eqId]=NULL;
163     bScanInit[eqId]=kFALSE;
164   }
165   // header data variables
166   UInt_t routerNr[20];
167   Bool_t halfStaveScanned[20][6];
168   UInt_t type[20];
169   Bool_t dataFormat[20];
170   UInt_t triggers[20];
171   Bool_t chipPresent[20][6][10];
172   UInt_t dacStart[20];  
173   UInt_t dacEnd[20];
174   UInt_t dacStep[20];
175   UInt_t dacId[20];
176   UInt_t rowStart[20];  
177   UInt_t rowEnd[20];
178   UInt_t rowValue[20];
179   UInt_t dacValue[20];
180   UInt_t dacHigh[20][6];
181   UInt_t dacLow[20][6];
182   UInt_t TPAmp[20][6];
183   Bool_t minTHchipPresent[20][10];
184   // current scan step flag
185   Int_t currentStep[20];
186   for (UInt_t eqId=0; eqId<20; eqId++) currentStep[eqId] = 9999;
187
188   // loop over run segments
189   for (int segNr=startSeg; segNr<argc; segNr++) {
190
191     int status;
192
193     /* define data source : this is argument 1 */  
194     status=monitorSetDataSource( argv[segNr] );
195     if (status!=0) {
196       printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
197       return -1;
198     }
199     /* declare monitoring program */
200     status=monitorDeclareMp("ITS_SPD_CAL");
201     if (status!=0) {
202       printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
203       return -1;
204     }
205     /* define wait event timeout - 1s max */
206     monitorSetNowait();
207     monitorSetNoWaitNetworkTimeout(1000);
208     
209     
210     UInt_t eventNr=0;
211
212     /* main loop (infinite) */
213     for(;;) {
214       
215       struct eventHeaderStruct *event;
216       eventTypeType eventT;
217       
218       /* check shutdown condition */
219 #ifndef SPD_DA_OFF
220       if (daqDA_checkShutdown()) {break;}
221 #endif
222       /* get next event (blocking call until timeout) */
223       status=monitorGetEventDynamic((void **)&event);
224       if (status==MON_ERR_EOF) {
225         printf ("End of File detected\n");
226         break; /* end of monitoring file has been reached */
227       }
228       if (status!=0) {
229         printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
230         break;
231       }
232       /* retry if got no event */
233       if (event==NULL) {
234         continue;
235       }
236
237       eventT=event->eventType;
238       if (eventT == PHYSICS_EVENT) {
239         
240         eventNr++;
241         //      printf("eventNr %d\n",eventNr);
242         
243         AliRawReader *reader = new AliRawReaderDate((void*)event);
244         AliITSRawStreamSPD *str = new AliITSRawStreamSPD(reader);
245         
246         for (UInt_t eqId=0; eqId<20; eqId++) {
247           
248           reader->Reset();
249           reader->Select("ITSSPD",eqId,eqId);
250           
251           // Hit Event flags, specific for one event
252           Bool_t hitEventHSIncremented[6];
253           Bool_t hitEventChipIncremented[6][10];
254           for (UInt_t hs=0; hs<6; hs++) {
255             hitEventHSIncremented[hs] = kFALSE;
256             for (UInt_t chip=0; chip<10; chip++) {
257               hitEventChipIncremented[hs][chip] = kFALSE;
258             }
259           }
260           
261           if (str->ReadCalibHeader()>0) {
262             // first check the type:
263             if (bScanInit[eqId] && type[eqId]!=str->GetHtype()) {
264               printf("Calib header problem. Type changed (%d -> %d)!\n",type[eqId],str->GetHtype());
265             }
266
267             // read calib values
268             routerNr[eqId]    = str->GetHrouterNr();
269             type[eqId]        = str->GetHtype();
270             dataFormat[eqId]  = str->GetHdataFormat();
271             triggers[eqId]    = str->GetHtriggers();
272             dacStart[eqId]    = str->GetHdacStart();
273             dacEnd[eqId]      = str->GetHdacEnd();
274             dacStep[eqId]     = str->GetHdacStep();
275             dacId[eqId]       = str->GetHdacId();
276             rowStart[eqId]    = str->GetHrowStart();
277             rowEnd[eqId]      = str->GetHrowEnd();
278             rowValue[eqId]    = str->GetHrowValue();
279             dacValue[eqId]    = str->GetHdacValue();
280             for (UInt_t hs=0; hs<6; hs++) {
281               halfStaveScanned[eqId][hs] = str->GetHhalfStaveScanned(hs);
282               dacHigh[eqId][hs]          = str->GetHdacHigh(hs);
283               dacLow[eqId][hs]           = str->GetHdacLow(hs);
284               TPAmp[eqId][hs]            = str->GetHTPAmp(hs);
285               for (UInt_t chip=0; chip<10; chip++) {
286                 chipPresent[eqId][hs][chip]      = str->GetHchipPresent(hs,chip);
287               }
288             }
289             for (UInt_t chip=0; chip<10; chip++) {
290               minTHchipPresent[eqId][chip] = str->GetHminTHchipPresent(chip);
291             }
292
293             currentStep[eqId] = (dacValue[eqId]-dacStart[eqId])/dacStep[eqId];
294             if (type[eqId]==DELAY) {
295               currentStep[eqId]=currentStep[eqId]*2;
296               dacValue[eqId]=dacValue[eqId]*2;
297               if (dacHigh[eqId][0]==128) { // misc_ctrl value
298                 currentStep[eqId]=currentStep[eqId]+1;
299                 dacValue[eqId]=dacValue[eqId]+1;
300               }
301             }
302
303             // router nr check:
304             if (routerNr[eqId]!=eqId) {
305               printf("Router nr problem? Router nr %d != EqID %d\n",routerNr[eqId],eqId);
306             }
307
308             if (!bScanInit[eqId]) {
309               // initialize container object
310               TString fileName = Form("%s/SPDcal_run_%d_eq_%d.root",saveDirRef,runNr,eqId);
311               switch (type[eqId]) {
312               case NOISE:
313               case UNIMA:
314                 scanObj[eqId] = new AliITSOnlineSPDscanSingle(fileName.Data());
315                 ((AliITSOnlineSPDscanSingle*)scanObj[eqId])->ClearThis();
316                 bScanInit[eqId]=kTRUE;
317                 break;
318               case MINTH:
319               case DAC:
320               case DELAY:
321                 scanObj[eqId] = new AliITSOnlineSPDscanMultiple(fileName.Data());
322                 scanObj[eqId]->ClearThis();
323                 bScanInit[eqId]=kTRUE;
324                 break;
325               case MEANTH: 
326                 scanObj[eqId] = new AliITSOnlineSPDscanMeanTh(fileName.Data());
327                 scanObj[eqId]->ClearThis();
328                 bScanInit[eqId]=kTRUE;
329                 break;
330               default:
331                 printf("Unknown scan type: %d.\n",type[eqId]);
332               }
333               // some multiple scan data
334               if (type[eqId]==MINTH || type[eqId]==MEANTH || type[eqId]==DAC || type[eqId]==DELAY) {
335                 ((AliITSOnlineSPDscanMultiple*)scanObj[eqId])->SetDacId(dacId[eqId]);
336               }
337               // some common data
338               scanObj[eqId]->SetRunNr((UInt_t)runNr);
339               scanObj[eqId]->SetRouterNr(routerNr[eqId]);
340               for (UInt_t hs=0; hs<6; hs++) {
341                 scanObj[eqId]->SetHalfStaveScanned(hs,halfStaveScanned[eqId][hs]);
342               }
343               scanObj[eqId]->SetType(type[eqId]);
344               scanObj[eqId]->SetDataFormat(dataFormat[eqId]);
345               for (Int_t hs=0; hs<6; hs++) {
346               
347                 // remove later when the chip present is set correctly !!!!!!!!!!!!!!!!!!!!!!!!!!!
348                 Bool_t halfStavePresent = str->GetHalfStavePresent(hs);
349                 // remove later when the chip present is set correctly !!!!!!!!!!!!!!!!!!!!!!!!!!!
350
351                 for (UInt_t chip=0; chip<10; chip++) {
352                   scanObj[eqId]->SetChipPresent(hs,chip,chipPresent[eqId][hs][chip]);
353
354                   // remove later when the chip present is set correctly !!!!!!!!!!!!!!!!!!!!!!!!!!!
355                   if (halfStavePresent) scanObj[eqId]->SetChipPresent(hs,chip,kTRUE);
356                   // remove later when the chip present is set correctly !!!!!!!!!!!!!!!!!!!!!!!!!!!
357
358                 }
359               }
360               scanObj[eqId]->SetRowStart(rowStart[eqId]);
361               scanObj[eqId]->SetRowEnd(rowEnd[eqId]);
362               scanObj[eqId]->SetDacStart(dacStart[eqId]);
363               scanObj[eqId]->SetDacEnd(dacEnd[eqId]);
364               scanObj[eqId]->SetDacStep(dacStep[eqId]);
365             }
366
367             if (type[eqId]==MINTH) {
368               scanObj[eqId]->SetTriggers(currentStep[eqId],triggers[eqId]);
369             }
370             if (type[eqId]==UNIMA || type[eqId]==NOISE) {
371               if (currentStep[eqId]==9999) printf("SPDcalibratorStep1 (eq %d): single step\n",eqId);
372               currentStep[eqId]=0;
373             }
374             if (type[eqId]==MINTH || type[eqId]==MEANTH || type[eqId]==DAC || type[eqId]==DELAY) {
375               ((AliITSOnlineSPDscanMultiple*)scanObj[eqId])->SetDacValue(currentStep[eqId],dacValue[eqId]);
376               if (type[eqId]==DELAY) {
377                 printf("SPDcalibratorStep1 (eq %d): DAC %d/%d , step %d\n",eqId,dacValue[eqId]/2,dacHigh[eqId][0],currentStep[eqId]);
378               }
379               else {
380                 printf("SPDcalibratorStep1 (eq %d): DAC %d , step %d\n",eqId,dacValue[eqId],currentStep[eqId]);
381               }
382             }
383             if (type[eqId]==MEANTH) {
384               for (Int_t hs=0; hs<6; hs++) {
385                 ((AliITSOnlineSPDscanMeanTh*)scanObj[eqId])->SetDacLow(currentStep[eqId],hs,dacLow[eqId][hs]);
386                 ((AliITSOnlineSPDscanMeanTh*)scanObj[eqId])->SetDacHigh(currentStep[eqId],hs,dacHigh[eqId][hs]);
387                 ((AliITSOnlineSPDscanMeanTh*)scanObj[eqId])->SetTPAmp(currentStep[eqId],hs,TPAmp[eqId][hs]);
388               }
389             }
390
391
392           }
393
394           if (bScanInit[eqId]) {
395             while (str->Next()) {
396               UInt_t hs = str->GetHalfStaveNr();
397               UInt_t chip = str->GetChipAddr();
398               //***remove last condition when minthpresent put correctly in calib header?
399 #ifndef SPD_DA_OFF
400               if (type[eqId]!=MINTH || minTHchipPresent[eqId][chip] || runNr<=416900) {
401 #else
402               if (type[eqId]!=MINTH || minTHchipPresent[eqId][chip] || runNr<=416900) {
403 #endif
404                 //*************************************************************************
405                 scanObj[eqId]->IncrementHits(currentStep[eqId],hs,chip,str->GetChipCol(),str->GetChipRow());
406                 
407                 if (!hitEventHSIncremented[hs]) {
408                   scanObj[eqId]->IncrementHitEventsTot(currentStep[eqId],hs);
409                   hitEventHSIncremented[hs]=kTRUE;
410                 }
411                 
412                 if (!hitEventChipIncremented[hs][chip]) {
413                   scanObj[eqId]->IncrementHitEvents(currentStep[eqId],hs,chip);
414                   hitEventChipIncremented[hs][chip]=kTRUE;
415                 }
416               }
417
418             }
419
420             if (type[eqId]!=MINTH) { // for minth, triggers are set from header info
421               scanObj[eqId]->IncrementTriggers(currentStep[eqId]);
422             }
423
424           }
425
426         }
427
428         delete str;
429         delete reader;
430
431       }
432
433       /* free resources */
434       free(event);
435
436     }
437
438 #ifndef SPD_DA_OFF
439     daqDA_progressReport((unsigned int)( ((Float_t)(segNr-startSeg+1))/(argc-startSeg)*50 ));
440 #else
441     printf("progress: %d\n",(unsigned int)( ((Float_t)(segNr-startSeg+1))/(argc-startSeg)*50 ));
442 #endif
443
444   }
445
446   
447   // clean up scan objects (which also saves them)
448   for (UInt_t eqId=0; eqId<20; eqId++) {
449     if (scanObj[eqId]!=NULL) delete scanObj[eqId];
450   }
451
452
453
454
455
456   // ********* STEP 2: Analyze scan container files. ************************************************
457
458   // clear noisyToFXS and DCSconfigToFXS dirs:
459   TString command = Form("cd %s; rm -f *",saveDirNoisyToFXS);
460   system(command.Data());
461   TString command2 = Form("cd %s; rm -f *",saveDirDCSconfigToFXS);
462   system(command2.Data());
463   UInt_t nrNoisyFilesProduced=0;
464   UInt_t nrDCSconfigFilesProduced=0;
465
466   AliITSOnlineCalibrationSPDhandler* handler = new AliITSOnlineCalibrationSPDhandler();
467   AliITSOnlineSPDscanAnalyzer *analyzer = NULL;
468   AliITSOnlineCalibrationSPDhandler* handlerPermNoisy = NULL;
469   // fill permanent noisy list to add later...
470   if (permstatus==0) { 
471     handlerPermNoisy = new AliITSOnlineCalibrationSPDhandler();
472     UInt_t permNoisy = handlerPermNoisy->ReadNoisyFromText(permNoisyFileName.Data(),240); // 240 = read for all modules
473     if (permNoisy>0) {
474       printf("%d noisy pixels read from permanent list.\n",permNoisy);
475     }
476   }
477
478   Bool_t reset_made = kFALSE;
479
480   // *** *** *** start loop over equipments (eq_id)
481   for (int eqId=0; eqId<20; eqId++) {
482
483     // create analyzer for this eq
484     TString fileName = Form("%s/SPDcal_run_%d_eq_%d.root",saveDirRef,runNr,eqId);
485     analyzer = new AliITSOnlineSPDscanAnalyzer(fileName.Data(),handler);
486
487     // configure analyzer with tuning parameters etc:
488     for (UInt_t i=0; i<nrTuningParams; i++) {
489       analyzer->SetParam(((TString*)paramNames.At(i))->Data(),((TString*)paramVals.At(i))->Data());
490     }
491
492     UInt_t type  = analyzer->GetType();
493     UInt_t dacId = analyzer->GetDacId();
494     UInt_t routerNr = analyzer->GetRouterNr();
495     if (type!=99) {
496       if (type==DAC) {
497         printf("SPD scan calibrator Step2: eqId %d, type %d, dacId %d\n",eqId,type,dacId);
498       }
499       else printf("SPD scan calibrator Step2: eqId %d type %d\n",eqId,type);  
500     }
501
502
503
504     // algorithms for the different types of scans:
505
506     if (type==UNIMA) {
507
508     }
509
510     else if (type==NOISE) {
511       // read previous noisy list (clear if overwriting)
512       handler->SetFileLocation(saveDirNoisy);
513       if (analyzer->IsOverWriteSet() && !reset_made) {
514         handler->ResetNoisy();
515         handler->WriteToFilesAlways();
516         reset_made=kTRUE;
517       }
518       else {
519         handler->ReadFromFiles();
520       }
521       if (analyzer->ProcessNoisyPixels(/*saveDirNoisy*/)) {
522         if (permstatus==0) {
523           handler->AddNoisyFrom(handlerPermNoisy);
524         }
525         // init dcs config text file
526         TString dcsConfigFileName = Form("%s/dcsConfig_run_%d_eq_%d.txt",saveDirDCSconfigToFXS,runNr,eqId);
527         ofstream dcsfile;
528         dcsfile.open(dcsConfigFileName.Data());
529         dcsfile << "[SPD SCAN]\n";
530         dcsfile << "RunNumber=" << runNr << "\n";
531         dcsfile << "Type=" << type << "\n";
532         dcsfile << "Router=" << routerNr << "\n";
533         dcsfile << "ActualDetConfiguration=" << "0,-1,-1\n"; // dummy values for now
534         dcsfile << "[NOISY]\n";
535         nrDCSconfigFilesProduced++;
536
537         for (UInt_t hs=0; hs<6; hs++) {
538           for (UInt_t chip=0; chip<10; chip++) {
539             if (analyzer->IsChipPresent(hs,chip) || analyzer->IsOverWriteSet()) {
540               dcsfile << "-" << eqId << "," << hs << "," << chip << "\n";
541               UInt_t nrNoisy = handler->GetNrNoisyC(eqId,hs,chip);
542               for (UInt_t ind=0; ind<nrNoisy; ind++) {
543                 UInt_t col = handler->GetNoisyColAtC(eqId,hs,chip,ind);
544                 UInt_t row = handler->GetNoisyRowAtC(eqId,hs,chip,ind);
545                 dcsfile << col << "," << row << "\n";
546               }
547             }
548           }
549         }
550         handler->SetFileLocation(saveDirNoisy);
551         handler->WriteNoisyToFile(eqId);
552         handler->SetFileLocation(saveDirNoisyToFXS);
553         handler->WriteNoisyToFile(eqId);
554         nrNoisyFilesProduced++;
555         
556         dcsfile.close();
557       }
558     }
559
560     else if (type==MINTH || (type==DAC && dacId==39)) {
561       // init dcs config text file
562       TString dcsConfigFileName = Form("%s/dcsConfig_run_%d_eq_%d.txt",saveDirDCSconfigToFXS,runNr,eqId);
563       ofstream dcsfile;
564       dcsfile.open(dcsConfigFileName.Data());
565       dcsfile << "[SPD SCAN]\n";
566       dcsfile << "RunNumber=" << runNr << "\n";
567       dcsfile << "Type=" << type << "\n";
568       dcsfile << "Router=" << routerNr << "\n";
569       dcsfile << "ActualDetConfiguration=" << "0,-1,-1\n"; // dummy values for now
570       dcsfile << "[DACvalues]\n";
571       nrDCSconfigFilesProduced++;
572       for (UInt_t hs=0; hs<6; hs++) {
573         for (UInt_t chipNr=0; chipNr<10; chipNr++) {
574           Int_t minTh = -1;
575           if (analyzer->GetOnlineScan()->GetChipPresent(hs,chipNr)) {
576             minTh = analyzer->GetMinTh(hs,chipNr);
577             if (minTh!=-1) {
578               dcsfile << "39," << eqId << "," << hs << "," << chipNr << "=" << minTh << "\n";
579             }
580             else {
581               printf("MinTh failed for Eq %d , HS %d , Chip %d\n",eqId,hs,chipNr);
582             }
583           }
584         }
585       }
586       dcsfile.close();
587     }
588
589     else if (type==DELAY) {
590       // init dcs config text file
591       TString dcsConfigFileName = Form("%s/dcsConfig_run_%d_eq_%d.txt",saveDirDCSconfigToFXS,runNr,eqId);
592       ofstream dcsfile;
593       dcsfile.open(dcsConfigFileName.Data());
594       dcsfile << "[SPD SCAN]\n";
595       dcsfile << "RunNumber=" << runNr << "\n";
596       dcsfile << "Type=" << type << "\n";
597       dcsfile << "Router=" << routerNr << "\n";
598       dcsfile << "ActualDetCoonfiguration=" << "0,-1,-1\n"; // dummy values for now
599       dcsfile << "[DACvalues]\n";
600       nrDCSconfigFilesProduced++;
601       for (UInt_t hs=0; hs<6; hs++) {
602         for (UInt_t chipNr=0; chipNr<10; chipNr++) {
603           Int_t clockCycle = -1;
604           Int_t delayCtrl = -1;
605           Int_t miscCtrl = -1;
606           if (analyzer->GetOnlineScan()->GetChipPresent(hs,chipNr)) {
607             clockCycle = analyzer->GetDelay(hs,chipNr);
608             delayCtrl = clockCycle/2;
609             miscCtrl = 192;
610             if (clockCycle!=-1) {
611               if (clockCycle%2==1) miscCtrl = 128;
612               dcsfile << "42," << eqId << "," << hs << "," << chipNr << "=" << delayCtrl << "\n";
613               dcsfile << "43," << eqId << "," << hs << "," << chipNr << "=" << miscCtrl << "\n";
614             }
615             else {
616               printf("Delay failed for Eq %d , HS %d , Chip %d\n",eqId,hs,chipNr);
617             }
618           }
619         }
620       }
621       dcsfile.close();
622     }
623
624     delete analyzer;
625
626 #ifndef SPD_DA_OFF
627     daqDA_progressReport((unsigned int)(50+(eqId+1)*2.5));
628 #else
629     printf("progress: %d\n",(unsigned int)(50+(eqId+1)*2.5));
630 #endif
631
632   }
633   // *** *** *** end loop over equipments (eq_id)
634
635
636   delete handler;
637   if (handlerPermNoisy!=NULL) {
638     delete handlerPermNoisy;
639   }
640
641
642   TString idsFXSFileName = Form("%s/FXSids_run_%d.txt",saveDirIdsToFXS,runNr);
643   ofstream idsFXSfile;
644   idsFXSfile.open(idsFXSFileName.Data());
645
646
647
648   // send noisy data to FXS
649   if (nrNoisyFilesProduced>0) {
650     // send a tared file of all new noisy maps
651     TString command = Form("cd %s; tar -cf noisy_scan.tar *",saveDirNoisyToFXS);
652     //    printf("\n\n%s\n\n",command.Data());
653     system(command.Data());
654     TString fileName = Form("%s/noisy_scan.tar",saveDirNoisyToFXS);
655     TString id = "SPD_scan_noisy";
656 #ifndef SPD_DA_OFF
657     Int_t status = daqDA_FES_storeFile(fileName.Data(),id.Data());
658     if (status!=0) {
659       printf("Failed to export file %s , status %d\n",fileName.Data(),status);
660       return -1;
661     }
662 #endif
663     idsFXSfile << Form("%s\n",id.Data());
664   }
665
666   // send dcs config files to FXS
667   if (nrDCSconfigFilesProduced>0) {
668     // send a tared file of all the dcsConfig text files
669     TString command = Form("cd %s; tar -cf dcsConfig.tar *",saveDirDCSconfigToFXS);
670     //    printf("\n\n%s\n\n",command.Data());
671     system(command.Data());
672     TString fileName = Form("%s/dcsConfig.tar",saveDirDCSconfigToFXS);
673     TString id = "SPD_dcsConfig";
674 #ifndef SPD_DA_OFF
675     Int_t status = daqDA_FES_storeFile(fileName.Data(),id.Data());
676     if (status!=0) {
677       printf("Failed to export file %s , status %d\n",fileName.Data(),status);
678       return -1;
679     }
680 #endif
681     //idsFXSfile << Form("%s\n",id.Data()); // do NOT write this id (this is not for preprocessor)
682   }
683
684   // send reference data to FXS
685   for (UInt_t eqId=0; eqId<20; eqId++) {
686     if (bScanInit[eqId]) {
687       TString fileName = Form("%s/SPDcal_run_%d_eq_%d.root",saveDirRef,runNr,eqId);
688       TString id = Form("SPD_ref_scan_%d",eqId);
689 #ifndef SPD_DA_OFF
690       Int_t status = daqDA_FES_storeFile(fileName.Data(),id.Data());
691       if (status!=0) {
692         printf("Failed to export file %s , status %d\n",fileName.Data(),status);
693         return -1;
694       }
695 #endif
696       idsFXSfile << Form("%s\n",id.Data());
697     }
698   }
699
700
701   idsFXSfile.close();
702
703
704
705   return 0;
706 }