/[PAMELA software]/DarthVader/OrbitalInfo/src/OrbitalInfoCore.cpp
ViewVC logotype

Diff of /DarthVader/OrbitalInfo/src/OrbitalInfoCore.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.35 by mocchiut, Thu Dec 11 10:08:19 2008 UTC revision 1.93 by mayorov, Thu Dec 27 13:12:28 2018 UTC
# Line 1  Line 1 
 //  
1  // C/C++ headers  // C/C++ headers
2  //  //
3  #include <fstream>  #include <fstream>
# Line 9  Line 8 
8  //  //
9  // ROOT headers  // ROOT headers
10  //  //
11    //#include <TCanvas.h>
12    #include <TH2F.h> //for test only. Vitaly.
13    #include <TVector3.h>
14    //#include <TF1.h>
15    
16  #include <TTree.h>  #include <TTree.h>
17  #include <TClassEdit.h>  #include <TClassEdit.h>
18  #include <TObject.h>  #include <TObject.h>
# Line 22  Line 26 
26  #include <TSQLServer.h>  #include <TSQLServer.h>
27  #include <TSQLRow.h>  #include <TSQLRow.h>
28  #include <TSQLResult.h>  #include <TSQLResult.h>
29    #include <TObjectTable.h>
30  //  //
31  // RunInfo header  // RunInfo header
32  //  //
# Line 44  Line 49 
49  #include <OrbitalInfoCore.h>  #include <OrbitalInfoCore.h>
50  #include <InclinationInfo.h>  #include <InclinationInfo.h>
51    
52    //
53    // Tracker and ToF classes headers and definitions
54    //
55    #include <ToFLevel2.h>
56    #include <TrkLevel2.h>
57    #include <ExtTrack.h> // new tracking code
58    
59  using namespace std;  using namespace std;
60    
61  //  //
62  // CORE ROUTINE  // CORE ROUTINE
63  //  //
64  //  //
65  int OrbitalInfoCore(UInt_t run, TFile *file, GL_TABLES *glt, Int_t OrbitalInfoargc, char *OrbitalInfoargv[]){  int OrbitalInfoCore(UInt_t run, TFile *file, GL_TABLES *glt, Int_t OrbitalInfoargc, char *OrbitalInfoargv[]){  
66    //    //
67    Int_t i = 0;    Int_t i = 0;
68    TString host = glt->CGetHost();    TString host = glt->CGetHost();
# Line 60  int OrbitalInfoCore(UInt_t run, TFile *f Line 72  int OrbitalInfoCore(UInt_t run, TFile *f
72    //    //
73    stringstream myquery;    stringstream myquery;
74    myquery.str("");    myquery.str("");
75    myquery << "SET time_zone='+0:00'";    myquery << "SET time_zone='+0:00';";
76    dbc->Query(myquery.str().c_str());    delete dbc->Query(myquery.str().c_str());
77      delete dbc->Query("SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';");
78    //    //
79    TString processFolder = Form("OrbitalInfoFolder_%u",run);    TString processFolder = Form("OrbitalInfoFolder_%u",run);
80    //    //
# Line 77  int OrbitalInfoCore(UInt_t run, TFile *f Line 90  int OrbitalInfoCore(UInt_t run, TFile *f
90      i = 0;      i = 0;
91      while ( i < OrbitalInfoargc ){      while ( i < OrbitalInfoargc ){
92        if ( !strcmp(OrbitalInfoargv[i],"-processFolder") ) {        if ( !strcmp(OrbitalInfoargv[i],"-processFolder") ) {
93          if ( OrbitalInfoargc < i+1 ){        if ( OrbitalInfoargc < i+1 ){
94            throw -3;      throw -3;
95          };    }
96          processFolder = (TString)OrbitalInfoargv[i+1];    processFolder = (TString)OrbitalInfoargv[i+1];
97          i++;    i++;
98        };        }
99        if ( (!strcmp(OrbitalInfoargv[i],"--debug")) || (!strcmp(OrbitalInfoargv[i],"-g")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--debug")) || (!strcmp(OrbitalInfoargv[i],"-g")) ) {
100          verbose = true;          verbose = true;
101          debug = true;          debug = true;
102        };        }
103        if ( (!strcmp(OrbitalInfoargv[i],"--verbose")) || (!strcmp(OrbitalInfoargv[i],"-v")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--verbose")) || (!strcmp(OrbitalInfoargv[i],"-v")) ) {
104          verbose = true;          verbose = true;
105        };        }
106        if ( (!strcmp(OrbitalInfoargv[i],"--standalone")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--standalone")) ) {
107          standalone = true;          standalone = true;
108        };        }
109        if ( (!strcmp(OrbitalInfoargv[i],"--calculate-pitch")) ) {        if ( (!strcmp(OrbitalInfoargv[i],"--calculate-pitch")) ) {
110          standalone = false;          standalone = false;
111        };        }
112        i++;        i++;
113      };      }
114    };    }
115      if ( debug ){
116        printf("START\n");
117        gObjectTable->Print();
118      }
119    //    //
120    const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));    const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));
121    //    //
# Line 117  int OrbitalInfoCore(UInt_t run, TFile *f Line 134  int OrbitalInfoCore(UInt_t run, TFile *f
134    TTree *OrbitalInfotrclone = 0;    TTree *OrbitalInfotrclone = 0;
135    Bool_t reproc = false;    Bool_t reproc = false;
136    Bool_t reprocall = false;    Bool_t reprocall = false;
137      Bool_t igrfloaded = false;
138    UInt_t nobefrun = 0;    UInt_t nobefrun = 0;
139    UInt_t noaftrun = 0;    UInt_t noaftrun = 0;
140    UInt_t numbofrun = 0;    UInt_t numbofrun = 0;
# Line 124  int OrbitalInfoCore(UInt_t run, TFile *f Line 142  int OrbitalInfoCore(UInt_t run, TFile *f
142    TString fname;    TString fname;
143    UInt_t totfileentries = 0;    UInt_t totfileentries = 0;
144    UInt_t idRun = 0;    UInt_t idRun = 0;
145      UInt_t anni5 = 60 * 60 * 24 * 365 * 5 ;//1576800
146    //    //
147    // My variables. Vitaly.    // My variables. Vitaly.
148    //    //
149    //  UInt_t iev = 0;  //  UInt_t oi = 0;
   //  UInt_t j3 = 0;  
   UInt_t oi = 0;  
150    Int_t tmpSize = 0;    Int_t tmpSize = 0;
151    //    //
152    // variables needed to handle error signals    // variables needed to handle error signals
# Line 141  int OrbitalInfoCore(UInt_t run, TFile *f Line 158  int OrbitalInfoCore(UInt_t run, TFile *f
158    //    //
159    OrbitalInfo *orbitalinfo = new OrbitalInfo();    OrbitalInfo *orbitalinfo = new OrbitalInfo();
160    OrbitalInfo *orbitalinfoclone = new OrbitalInfo();    OrbitalInfo *orbitalinfoclone = new OrbitalInfo();
161    
162    //    //
163    // define variables for opening and reading level0 file    // define variables for opening and reading level0 file
164    //    //
165    TFile *l0File = 0;    TFile *l0File = 0;
166    TTree *l0tr = 0;    TTree *l0tr = 0;
167    TTree *l0trm = 0;    //  TTree *l0trm = 0;
168      TChain *ch = 0;
169    // EM: open also header branch    // EM: open also header branch
170    TBranch *l0head = 0;    TBranch *l0head = 0;
171    pamela::EventHeader *eh = 0;    pamela::EventHeader *eh = 0;
# Line 176  int OrbitalInfoCore(UInt_t run, TFile *f Line 195  int OrbitalInfoCore(UInt_t run, TFile *f
195    //    //
196    // IGRF stuff    // IGRF stuff
197    //    //
198    float dimo = 0.0; // dipole moment (computed from dat files)    Float_t dimo = 0.0; // dipole moment (computed from dat files) // EM GCC 4.7
199    float bnorth, beast, bdown, babs;    Float_t bnorth, beast, bdown, babs;
200    float xl; // L value    Float_t xl; // L value
201    float icode; // code value for L accuracy (see fortran code)    Int_t icode; // code value for L accuracy (see fortran code)
202    float bab1; // What's  the difference with babs?    Float_t bab1; // What's  the difference with babs?
203    float stps = 0.005; // step size for field line tracing    Float_t stps = 0.005; // step size for field line tracing
204    float bdel = 0.01; // required accuracy    Float_t bdel = 0.01; // required accuracy
205    float bequ;  // equatorial b value (also called b_0)    Float_t bequ;  // equatorial b value (also called b_0)
206    bool value = 0; // false if bequ is not the minimum b value    Bool_t value = 0; // false if bequ is not the minimum b value
207    float rr0; // equatorial radius normalized to earth radius    Float_t rr0; // equatorial radius normalized to earth radius
208    
209    //    //
210    // Working filename    // Working filename
# Line 209  int OrbitalInfoCore(UInt_t run, TFile *f Line 228  int OrbitalInfoCore(UInt_t run, TFile *f
228    OrbitalInfofolder << tempname.str().c_str();    OrbitalInfofolder << tempname.str().c_str();
229    tempname << "/OrbitalInfotree_run";    tempname << "/OrbitalInfotree_run";
230    tempname << run << ".root";      tempname << run << ".root";  
231      UInt_t totnorun = 0;
232    //    //
233    // DB classes    // DB classes
234    //    //
# Line 218  int OrbitalInfoCore(UInt_t run, TFile *f Line 238  int OrbitalInfoCore(UInt_t run, TFile *f
238    //    //
239    //Quaternions classes    //Quaternions classes
240    //    //
241    Quaternions *L_QQ_Q_l_lower = new Quaternions();    Quaternions *L_QQ_Q_l_lower = 0;
242    InclinationInfo *RYPang_lower = new InclinationInfo();    InclinationInfo *RYPang_lower = 0;
243    Quaternions *L_QQ_Q_l_upper = new Quaternions();    Quaternions *L_QQ_Q_l_upper = 0;
244    InclinationInfo *RYPang_upper = new InclinationInfo();    InclinationInfo *RYPang_upper = 0;
245        
246    cEci eCi;    cEci eCi;
247        
248    // Initialize fortran routines!!!    // Initialize fortran routines!!!
249      Int_t ltp1 = 0;
250    Int_t ltp2 = 0;    Int_t ltp2 = 0;
251    Int_t ltp3 = 0;    GL_PARAM *glparam0 = new GL_PARAM();
   Int_t uno = 1;  
   char *niente = " ";  
252    GL_PARAM *glparam = new GL_PARAM();    GL_PARAM *glparam = new GL_PARAM();
253    GL_PARAM *glparam2 = new GL_PARAM();    GL_PARAM *glparam2 = new GL_PARAM();
254    Int_t parerror=glparam->Query_GL_PARAM(1,301,dbc); // parameters stored in DB in GL_PRAM table  
255    //    //
256    // Orientation variables    // Orientation variables. Vitaly
257    //    //
258    
259    UInt_t evfrom = 0;    UInt_t evfrom = 0;
260    UInt_t jumped = 0;    UInt_t jumped = 0;
261    Int_t itr = -1;        Int_t itr = -1;    
262    Double_t A1;    //  Double_t A1;
263    Double_t A2;    //  Double_t A2;
264    Double_t A3;    //  Double_t A3;
265    Double_t Px = 0;    Double_t Px = 0;
266    Double_t Py = 0;          Double_t Py = 0;  
267    Double_t Pz = 0;      Double_t Pz = 0;  
268    TTree *ttof = 0;    TTree *ttof = 0;
269    ToFLevel2 *tof = new ToFLevel2();    ToFLevel2 *tof = new ToFLevel2();
270      TTree *ttrke = 0;
271      TrkLevel2 *trke = new TrkLevel2();
272    OrientationInfo *PO = new OrientationInfo();    OrientationInfo *PO = new OrientationInfo();
273    Int_t nz = 6;    Int_t nz = 6;
274    Float_t zin[6];    Float_t zin[6];
275    Int_t nevtofl2 = 0;    Int_t nevtofl2 = 0;
276    //      Int_t nevtrkl2 = 0;
277      if ( verbose ) cout<<"Reading quaternions external file"<<endl;
278      cout.setf(ios::fixed,ios::floatfield);  
279      /******Reading recovered quaternions...*********/
280      vector<Double_t> recqtime;
281      vector<Float_t> recq0;
282      vector<Float_t> recq1;
283      vector<Float_t> recq2;
284      vector<Float_t> recq3;
285      Float_t Norm = 1;
286      recqtime.reserve(1500000);
287      recq0.reserve(1500000);
288      recq1.reserve(1500000);
289      recq2.reserve(1500000);
290      recq3.reserve(1500000);
291    
292      vector<UInt_t> RTtime1;
293      vector<UInt_t> RTtime2;
294      vector<Double_t> RTbank1;
295      vector<Double_t> RTbank2;
296      vector<Double_t> RTbpluto1;
297      vector<Double_t> RTbpluto2;
298      vector<Int_t> RTazim;
299      vector<UInt_t> RTstart;
300      vector<UInt_t> RTpluto2;
301      vector<UInt_t> RTpluto1;
302      vector<Int_t> RTerrq;
303      vector<Int_t> RTqual;
304      RTtime1.reserve(200000);
305      RTtime2.reserve(200000);
306      RTbank1.reserve(200000);
307      RTbank2.reserve(200000);
308      RTbpluto1.reserve(200000);
309      RTbpluto2.reserve(200000);
310      RTazim.reserve(200000);
311      RTstart.reserve(200000);
312      RTpluto1.reserve(200000);
313      RTpluto2.reserve(200000);
314      RTerrq.reserve(200000);
315      RTqual.reserve(200000);
316    
317      TClonesArray *tcNucleiTrk = NULL;
318      TClonesArray *tcExtNucleiTrk = NULL;
319      TClonesArray *tcExtTrk = NULL;
320      TClonesArray *tcNucleiTof = NULL;
321      TClonesArray *tcExtNucleiTof = NULL;
322      TClonesArray *tcExtTof = NULL;
323      TClonesArray *torbNucleiTrk = NULL;
324      TClonesArray *torbExtNucleiTrk = NULL;
325      TClonesArray *torbExtTrk = NULL;
326      Bool_t hasNucleiTrk = false;
327      Bool_t hasExtNucleiTrk = false;
328      Bool_t hasExtTrk = false;
329      Bool_t hasNucleiTof = false;
330      Bool_t hasExtNucleiTof = false;
331      Bool_t hasExtTof = false;
332    
333      ifstream in;
334      ifstream an;
335      //  ofstream mc;
336      //  TString gr;
337      Int_t parerror2=0;
338    
339      Int_t parerror=glparam0->Query_GL_PARAM(1,303,dbc); // parameters stored in DB in GL_PRAM table
340      if ( verbose ) cout<<parerror<<"\t"<<(char*)(glparam0->PATH+glparam0->NAME).Data()<<endl;
341    if ( parerror<0 ) {    if ( parerror<0 ) {
342      code = parerror;      code = parerror;
343      goto closeandexit;      goto closeandexit;
344    };    }
345    ltp2 = (Int_t)(glparam->PATH+glparam->NAME).Length();    in.open((char*)(glparam0->PATH+glparam0->NAME).Data(),ios::in);
346    if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());    while(!in.eof()){
347    //      recqtime.resize(recqtime.size()+1);
348    parerror=glparam2->Query_GL_PARAM(1,302,dbc); // parameters stored in DB in GL_PRAM table      Int_t sizee = recqtime.size();
349    if ( parerror<0 ) {      recq0.resize(sizee);
350        recq1.resize(sizee);
351        recq2.resize(sizee);
352        recq3.resize(sizee);
353        in>>recqtime[sizee-1];
354        in>>recq0[sizee-1];
355        in>>recq1[sizee-1];
356        in>>recq2[sizee-1];
357        in>>recq3[sizee-1];
358        in>>Norm;
359    /* CHECK RECOVERED QUATERNIONS PROBLEM
360        if(recqtime[sizee-1]>=1160987921.75 && recqtime[sizee-1]<=1160987932.00){
361          cout<<"We found it at start"<<"\t"<<recqtime[sizee-1]<<endl;
362        } */
363      }
364      in.close();
365      if ( verbose ) cout<<"We have read recovered data"<<endl;
366      if (debug) cout << "size of recovered quaterions data set is " << recqtime.size() << endl;
367      if ( debug )  printf(" RQ size %i RQ capacity %i \n",(int)recqtime.size(),(int)recqtime.capacity());
368      
369      if ( verbose ) cout<<"read Rotation Table"<<endl;
370      
371      parerror2=glparam0->Query_GL_PARAM(1,305,dbc);
372    
373      if ( verbose ) cout<<parerror2<<"\t"<<(char*)(glparam0->PATH+glparam0->NAME).Data()<<endl;
374      if ( parerror2<0 ) {
375      code = parerror;      code = parerror;
376      goto closeandexit;      goto closeandexit;
377    };    }
378    ltp3 = (Int_t)(glparam2->PATH+glparam2->NAME).Length();    an.open((char*)(glparam0->PATH+glparam0->NAME).Data(),ios::in);
379    if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam2->PATH+glparam2->NAME).Data());    while(!an.eof()){
380    //      RTtime1.resize(RTtime1.size()+1);
381    initize_((char *)niente,&uno,(char *)(glparam->PATH+glparam->NAME).Data(),&ltp2,(char *)(glparam2->PATH+glparam2->NAME).Data(),&ltp3);      Int_t sizee = RTtime1.size();
382    //      RTbank1.resize(sizee+1);
383    // End IGRF stuff//      RTazim.resize(sizee+1);
384    //      RTerrq.resize(sizee+1);
385        RTstart.resize(sizee+1);
386        RTpluto1.resize(sizee+1);
387        RTbpluto1.resize(sizee+1);
388        RTqual.resize(sizee+1);
389        an>>RTtime1[sizee-1];
390        an>>RTbank1[sizee-1];
391        an>>RTstart[sizee-1];
392        an>>RTpluto1[sizee-1];
393        an>>RTbpluto1[sizee-1];
394        an>>RTazim[sizee-1];
395        an>>RTerrq[sizee-1];
396        an>>RTqual[sizee-1];
397        if(sizee>1) {
398          RTtime2.resize(sizee+1);
399          RTbank2.resize(sizee+1);
400          RTpluto2.resize(sizee+1);
401          RTbpluto2.resize(sizee+1);
402          RTtime2[sizee-2]=RTtime1[sizee-1];
403          RTpluto2[sizee-2]=RTpluto1[sizee-1];
404          RTbank2[sizee-2]=RTbank1[sizee-1];
405          RTbpluto2[sizee-2]=RTbpluto1[sizee-1];
406        }
407      }
408      an.close();
409      //cout<<"put some number here"<<endl;
410      //Int_t yupi;
411      //cin>>yupi;
412      
413      if ( verbose ) cout<<"We have read Rotation Table"<<endl;
414        //Geomagnetic coordinates calculations staff
415      
416      if ( debug ) printf(" RT size %i RT capacity %i \n",(int)RTtime2.size(),(int)RTtime2.capacity());
417    
418      GMtype_CoordGeodetic location;
419      //  GMtype_CoordDipole GMlocation;
420      GMtype_Ellipsoid Ellip;
421      GMtype_Data G0, G1, H1;
422      
423      //  {  // this braces is necessary to avoid jump to label 'closeandexit'  error   // but it is wrong since the variable "igpath" will not exist outside. To overcome the "jump to label 'closeandexit'  error" it is necessary to set the "igpath" before line 276
424      //    TString igpath="/data03/Malakhov/pam9Malakhov/installed10/calib/orb-param/";
425      //  }
426    
427      //cout << G0.element[0] << "\t" << G1.element[0] << "\t" << H1.element[0] << endl;
428      //cout << G0.element[5] << "\t" << G1.element[5] << "\t" << H1.element[5] << endl;
429    
430      GM_SetEllipsoid(&Ellip);
431    
432      // IGRF stuff moved inside run loop!  
433    
434    for (Int_t ip=0;ip<nz;ip++){    for (Int_t ip=0;ip<nz;ip++){
435      zin[ip] = tof->GetZTOF(tof->GetToFPlaneID(ip));      zin[ip] = tof->GetZTOF(tof->GetToFPlaneID(ip));
436    };    };
437    //    //
438    if ( !standalone ){    if ( !standalone ){
439      //      //
440      // Does it contain the Tracker tree?      // Does it contain the Tracker and ToF trees?
441      //      //
442      ttof = (TTree*)file->Get("ToF");      ttof = (TTree*)file->Get("ToF");
443      if ( !ttof ) {      if ( !ttof ) {
444        if ( verbose ) printf(" OrbitalInfo - ERROR: no tof tree\n");        if ( verbose ) printf(" OrbitalInfo - ERROR: no tof tree\n");
445        code = -900;        code = -900;
446        goto closeandexit;        goto closeandexit;
447      };      }
448      ttof->SetBranchAddress("ToFLevel2",&tof);        ttof->SetBranchAddress("ToFLevel2",&tof);  
449      nevtofl2 = ttof->GetEntries();      nevtofl2 = ttof->GetEntries();
450    };  
451        //
452        // Look for extended tracking algorithm
453        //
454        if ( verbose ) printf("Look for extended and nuclei tracking algorithms in ToF\n");
455        // Nuclei tracking algorithm
456        Int_t checkAlgo = 0;
457        tcNucleiTof =  new TClonesArray("ToFTrkVar");
458        checkAlgo = ttof->SetBranchAddress("TrackNuclei",&tcNucleiTof);    
459        if ( !checkAlgo ){
460          if ( verbose ) printf(" Nuclei tracking algorithm ToF branch found! :D \n");
461          hasNucleiTof = true;
462        } else {
463          if ( verbose ) printf(" Nuclei tracking algorithm ToF branch not found :( !\n");
464          printf(" ok, this is not a problem (it depends on tracker settings) \n");
465          delete tcNucleiTof;
466          tcNucleiTof=NULL; // 10RED reprocessing bug  
467        }
468        // Nuclei tracking algorithm using calorimeter points
469        tcExtNucleiTof =  new TClonesArray("ToFTrkVar");
470        checkAlgo = ttof->SetBranchAddress("RecoveredTrackNuclei",&tcExtNucleiTof);    
471        if ( !checkAlgo ){
472          if ( verbose ) printf(" Recovered nuclei tracking algorithm ToF branch found! :D \n");
473          hasExtNucleiTof = true;
474        } else {
475          if ( verbose ) printf(" Recovered nuclei tracking algorithm ToF branch not found :( !\n");
476          printf(" ok, this is not a problem (it depends on tracker settings) \n");
477          delete tcExtNucleiTof;
478          tcExtNucleiTof=NULL; // 10RED reprocessing bug  
479        }
480        // Tracking algorithm using calorimeter points
481        tcExtTof =  new TClonesArray("ToFTrkVar");
482        checkAlgo = ttof->SetBranchAddress("RecoveredTrack",&tcExtTof);
483        if ( !checkAlgo ){
484          if ( verbose ) printf(" Recovered track algorithm ToF branch found! :D \n");
485          hasExtTof = true;
486        } else {
487          if ( verbose ) printf(" Recovered track algorithm ToF branch not found :( !\n");
488          printf(" ok, this is not a problem (it depends on tracker settings) \n");
489          delete tcExtTof;
490          tcExtTof=NULL; // 10RED reprocessing bug  
491        }
492    
493        ttrke = (TTree*)file->Get("Tracker");
494        if ( !ttrke ) {
495          if ( verbose ) printf(" OrbitalInfo - ERROR: no trk tree\n");
496          code = -903;
497          goto closeandexit;
498        }
499        ttrke->SetBranchAddress("TrkLevel2",&trke);  
500        nevtrkl2 = ttrke->GetEntries();
501    
502        //
503        // Look for extended tracking algorithm
504        //
505        if ( verbose ) printf("Look for extended and nuclei tracking algorithms\n");
506        // Nuclei tracking algorithm
507        checkAlgo = 0;
508        tcNucleiTrk =  new TClonesArray("TrkTrack");
509        checkAlgo = ttrke->SetBranchAddress("TrackNuclei",&tcNucleiTrk);    
510        if ( !checkAlgo ){
511          if ( verbose ) printf(" Nuclei tracking algorithm branch found! :D \n");
512          hasNucleiTrk = true;
513        } else {
514          if ( verbose ) printf(" Nuclei tracking algorithm branch not found :( !\n");
515          printf(" ok, this is not a problem (it depends on tracker settings) \n");
516          delete tcNucleiTrk;
517          tcNucleiTrk=NULL; // 10RED reprocessing bug  
518        }
519        // Nuclei tracking algorithm using calorimeter points
520        tcExtNucleiTrk =  new TClonesArray("ExtTrack");
521        checkAlgo = ttrke->SetBranchAddress("RecoveredTrackNuclei",&tcExtNucleiTrk);    
522        if ( !checkAlgo ){
523          if ( verbose ) printf(" Recovered nuclei tracking algorithm branch found! :D \n");
524          hasExtNucleiTrk = true;
525        } else {
526          if ( verbose ) printf(" Recovered nuclei tracking algorithm branch not found :( !\n");
527          printf(" ok, this is not a problem (it depends on tracker settings) \n");
528          delete tcExtNucleiTrk;
529          tcExtNucleiTrk=NULL; // 10RED reprocessing bug  
530        }
531        // Tracking algorithm using calorimeter points
532        tcExtTrk =  new TClonesArray("ExtTrack");
533        checkAlgo = ttrke->SetBranchAddress("RecoveredTrack",&tcExtTrk);
534        if ( !checkAlgo ){
535          if ( verbose ) printf(" Recovered track algorithm branch found! :D \n");
536          hasExtTrk = true;
537        } else {
538          if ( verbose ) printf(" Recovered track algorithm branch not found :( !\n");
539          printf(" ok, this is not a problem (it depends on tracker settings) \n");
540          delete tcExtTrk;
541          tcExtTrk=NULL; // 10RED reprocessing bug  
542        }
543    
544        if ( (hasNucleiTrk && !hasNucleiTof) || (!hasNucleiTrk && hasNucleiTof) ||
545             (hasExtNucleiTrk && !hasExtNucleiTof) || (!hasExtNucleiTrk && hasExtNucleiTof) ||
546             (hasExtTrk && !hasExtTof) || (!hasExtTrk && hasExtTof)
547             ){
548          if ( verbose ) printf(" ERROR: Mismatch between tracker and tof tree branches concerning extended tracking algorithm(s)\n");
549          if ( debug ) printf("hasNucleiTrk %i hasExtNucleiTrk %i hasExtTrk %i \n",hasNucleiTrk,hasExtNucleiTrk,hasExtTrk);
550          if ( debug ) printf("hasNucleiTof %i hasExtNucleiTof %i hasExtTof %i \n",hasNucleiTof,hasExtNucleiTof,hasExtTof);
551          throw -901;
552        }
553    
554      }
555    //    //
556    // Let's start!    // Let's start!
557    //    //
# Line 342  int OrbitalInfoCore(UInt_t run, TFile *f Line 606  int OrbitalInfoCore(UInt_t run, TFile *f
606    // number of run to be processed    // number of run to be processed
607    //    //
608    numbofrun = runinfo->GetNoRun();    numbofrun = runinfo->GetNoRun();
609    UInt_t totnorun = runinfo->GetRunEntries();    totnorun = runinfo->GetRunEntries();
610    //    //
611    // Try to access the OrbitalInfo tree in the file, if it exists we are reprocessing data if not we are processing a new run    // Try to access the OrbitalInfo tree in the file, if it exists we are reprocessing data if not we are processing a new run
612    //    //
# Line 376  int OrbitalInfoCore(UInt_t run, TFile *f Line 640  int OrbitalInfoCore(UInt_t run, TFile *f
640        //        //
641        reprocall = true;        reprocall = true;
642        //        //
643        if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing all runs\n");        if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing all runs\n Deleting old tree...\n");
644        //        //
645      } else {      } else {
646        //        //
# Line 394  int OrbitalInfoCore(UInt_t run, TFile *f Line 658  int OrbitalInfoCore(UInt_t run, TFile *f
658        tempOrbitalInfo = OrbitalInfotrclone->CloneTree(-1,"fast");        tempOrbitalInfo = OrbitalInfotrclone->CloneTree(-1,"fast");
659        tempOrbitalInfo->SetName("OrbitalInfo-old");        tempOrbitalInfo->SetName("OrbitalInfo-old");
660        tempfile->Write();        tempfile->Write();
661          tempOrbitalInfo->Delete();
662        tempfile->Close();          tempfile->Close();  
663      }      }
664      //      //
665      // Delete the old tree from old file and memory      // Delete the old tree from old file and memory
666      //      //
667        OrbitalInfotrclone->Clear();
668      OrbitalInfotrclone->Delete("all");      OrbitalInfotrclone->Delete("all");
669      //      //
670      if (verbose) printf(" ...done!\n");      if (verbose) printf(" ...done!\n");
# Line 413  int OrbitalInfoCore(UInt_t run, TFile *f Line 679  int OrbitalInfoCore(UInt_t run, TFile *f
679    orbitalinfo->Set();//ELENA **TEMPORANEO?**    orbitalinfo->Set();//ELENA **TEMPORANEO?**
680    OrbitalInfotr->Branch("OrbitalInfo","OrbitalInfo",&orbitalinfo);    OrbitalInfotr->Branch("OrbitalInfo","OrbitalInfo",&orbitalinfo);
681    //    //
682      // create new branches for new tracking algorithms
683      //
684      if ( hasNucleiTrk ){
685        torbNucleiTrk = new TClonesArray("OrbitalInfoTrkVar",1);
686        OrbitalInfotr->Branch("TrackNuclei",&torbNucleiTrk);
687      }
688      if ( hasExtNucleiTrk ){
689        torbExtNucleiTrk = new TClonesArray("OrbitalInfoTrkVar",1);
690        OrbitalInfotr->Branch("RecoveredTrackNuclei",&torbExtNucleiTrk);
691      }
692      if ( hasExtTrk ){
693        torbExtTrk = new TClonesArray("OrbitalInfoTrkVar",1);
694        OrbitalInfotr->Branch("RecoveredTrack",&torbExtTrk);
695      }
696    
697      //
698    if ( reproc && !reprocall ){    if ( reproc && !reprocall ){
699      //      //
700      //  open new file and retrieve also tree informations      //  open new file and retrieve also tree informations
# Line 424  int OrbitalInfoCore(UInt_t run, TFile *f Line 706  int OrbitalInfoCore(UInt_t run, TFile *f
706      //            //      
707      if ( nobefrun > 0 ){      if ( nobefrun > 0 ){
708        if (verbose){        if (verbose){
709          printf("\n Pre-processing: copying events from the old tree before the processed run\n");            printf("\n Pre-processing: copying events from the old tree before the processed run\n");  
710          printf(" Copying %u events in the file which are before the beginning of the run %u \n",nobefrun,run);          printf(" Copying %u events in the file which are before the beginning of the run %u \n",nobefrun,run);
711          printf(" Start copying at event number 0, end copying at event number %u \n",nobefrun);          printf(" Start copying at event number 0, end copying at event number %u \n",nobefrun);
712        }        }
713        for (UInt_t j = 0; j < nobefrun; j++){        for (UInt_t j = 0; j < nobefrun; j++){
714          //          //
715          OrbitalInfotrclone->GetEntry(j);                    if ( OrbitalInfotrclone->GetEntry(j) <= 0 ) throw -36;    
716          //          //
717          // copy orbitalinfoclone to mydec          // copy orbitalinfoclone to mydec
718          //          //
719          orbitalinfo->Clear();          //  orbitalinfo->Clear();
720          //          //
721          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));
722          //          //
723          // Fill entry in the new tree          // Fill entry in the new tree
724          //          //
725          OrbitalInfotr->Fill();          OrbitalInfotr->Fill();
726          //          //
727        };        };
728        if (verbose) printf(" Finished successful copying!\n");        if (verbose) printf(" Finished successful copying!\n");
729      };                };
730    };    };
731    //    //
732      //
733    // Get the list of run to be processed, if only one run has to be processed the list will contain one entry only.    // Get the list of run to be processed, if only one run has to be processed the list will contain one entry only.
734    //    //
735    runlist = runinfo->GetRunList();    runlist = runinfo->GetRunList();
736      if ( debug ){
737        printf("BEFORE LOOP ON RUN\n");
738        gObjectTable->Print();
739      }
740    //    //
741    // Loop over the run to be processed    // Loop over the run to be processed
742    //    //
743    for (UInt_t irun=0; irun < numbofrun; irun++){    for (UInt_t irun=0; irun < numbofrun; irun++){ //===>
744    
745        L_QQ_Q_l_lower = new Quaternions();
746        RYPang_lower = new InclinationInfo();
747        L_QQ_Q_l_upper = new Quaternions();
748        RYPang_upper = new InclinationInfo();
749    
750      //      //
751      // retrieve the first run ID to be processed using the RunInfo list      // retrieve the first run ID to be processed using the RunInfo list
752      //      //
# Line 502  int OrbitalInfoCore(UInt_t run, TFile *f Line 795  int OrbitalInfoCore(UInt_t run, TFile *f
795      fname = ftmpname.str().c_str();      fname = ftmpname.str().c_str();
796      ftmpname.str("");      ftmpname.str("");
797      //      //
798      // print out informations      // print nout informations
799      //      //
800      totevent = runinfo->NEVENTS;      totevent = runinfo->NEVENTS;
801      evfrom = runinfo->EV_FROM;      evfrom = runinfo->EV_FROM;
# Line 516  int OrbitalInfoCore(UInt_t run, TFile *f Line 809  int OrbitalInfoCore(UInt_t run, TFile *f
809      //      //
810      //    if ( !totevent ) goto closeandexit;      //    if ( !totevent ) goto closeandexit;
811      // Open Level0 file      // Open Level0 file
812        if ( l0File ) l0File->Close();
813      l0File = new TFile(fname.Data());      l0File = new TFile(fname.Data());
814      if ( !l0File ) {      if ( !l0File ) {
815        if ( debug ) printf(" OrbitalInfo - ERROR: problems opening Level0 file\n");        if ( debug ) printf(" OrbitalInfo - ERROR: problems opening Level0 file\n");
# Line 554  int OrbitalInfoCore(UInt_t run, TFile *f Line 848  int OrbitalInfoCore(UInt_t run, TFile *f
848        code = -12;        code = -12;
849        goto closeandexit;        goto closeandexit;
850      };      };
851      //  
 //     TTree *tp = (TTree*)l0File->Get("RunHeader");  
 //     tp->SetBranchAddress("Header", &eH);  
 //     tp->SetBranchAddress("RunHeader", &reh);  
 //     tp->GetEntry(0);  
 //     ph = eH->GetPscuHeader();  
 //     ULong_t TimeSync = reh->LAST_TIME_SYNC_INFO;  
 //     ULong_t ObtSync = reh->OBT_TIME_SYNC;      
 //     if ( debug ) printf(" 1 TimeSync %lu ObtSync %lu DeltaOBT %lu\n",TimeSync,ObtSync,TimeSync-ObtSync);  
 //  
852      ULong_t TimeSync = (ULong_t)dbtime->GetTimesync();      ULong_t TimeSync = (ULong_t)dbtime->GetTimesync();
853      ULong_t ObtSync = (ULong_t)(dbtime->GetObt0()/1000);      ULong_t ObtSync = (ULong_t)(dbtime->GetObt0()/1000);
854      ULong_t DeltaOBT = TimeSync - ObtSync;      ULong_t DeltaOBT = TimeSync - ObtSync;
855    
856      if ( debug ) printf(" 2 TimeSync %lu ObtSync %lu DeltaOBT %lu\n",(ULong_t)(dbtime->GetTimesync()/1000),(ULong_t)dbtime->GetObt0(),TimeSync-ObtSync);      if ( debug ) printf(" 2 TimeSync %lu ObtSync %lu DeltaOBT %lu\n",(ULong_t)(dbtime->GetTimesync()/1000),(ULong_t)dbtime->GetObt0(),TimeSync-ObtSync);
       
     l0trm = (TTree*)l0File->Get("Mcmd");  
     neventsm = l0trm->GetEntries();  
     //    neventsm = 0;  
857      //      //
858      if (neventsm == 0){      // Read MCMDs from up to 11 files, 5 before and 5 after the present one in order to have some kind of inclination information
859        if ( debug ) printf("InclinationInfo - WARNING: No quaternions in this File");      //
860        //      l0File->Close();      ch = new TChain("Mcmd","Mcmd");
861        code = 900;      //
862        //      goto closeandexit;      // look in the DB to find the closest files to this run
863        //
864        TSQLResult *pResult = 0;
865        TSQLRow *Row = 0;
866        stringstream myquery;
867        UInt_t l0fid[10];
868        Int_t i = 0;
869        memset(l0fid,0,10*sizeof(Int_t));
870        //
871        myquery.str("");
872        myquery << "select ID_ROOT_L0 from GL_RUN where RUNHEADER_TIME<=" << runinfo->RUNHEADER_TIME << " group by ID_ROOT_L0 order by RUNHEADER_TIME desc limit 5;";
873        //
874        pResult = dbc->Query(myquery.str().c_str());
875        //
876        i = 9;
877        if( pResult ){
878          //
879          Row = pResult->Next();
880          //
881          while ( Row ){
882            //
883            // store infos and exit
884            //
885            l0fid[i] = (UInt_t)atoll(Row->GetField(0));
886            i--;
887            if (Row){  // memleak!
888              delete Row;
889              Row = 0;
890            }
891            Row = pResult->Next();  
892          //
893          }
894          if (Row) delete Row;
895          pResult->Delete();
896      }      }
897      //      //
898            myquery.str("");
899      l0trm->SetBranchAddress("Mcmd", &mcmdev);      myquery << "select ID_ROOT_L0 from GL_RUN where RUNHEADER_TIME>" << runinfo->RUNHEADER_TIME << " group by ID_ROOT_L0 order by RUNHEADER_TIME asc limit 5;";
     //    l0trm->SetBranchAddress("Header", &eh);  
900      //      //
901        pResult = dbc->Query(myquery.str().c_str());
902      //      //
903        i = 0;
904        if( pResult ){
905          //
906          Row = pResult->Next();
907          //
908          while ( Row ){
909            //
910            // store infos and exit
911            //
912            l0fid[i] = (UInt_t)atoll(Row->GetField(0));
913            i++;
914            if (Row){  // memleak!
915              delete Row;
916              Row = 0;
917            }
918            Row = pResult->Next();  
919            //
920          }
921          if (Row) delete Row;
922          pResult->Delete();
923        }
924      //      //
925      UInt_t mctren = 0;          i = 0;
926      UInt_t mcreen = 0;        UInt_t previd = 0;
927      UInt_t numrec = 0;      while ( i < 10 ){
928          if ( l0fid[i] && previd != l0fid[i] ){
929            previd = l0fid[i];
930            myquery.str("");
931            myquery << "select PATH,NAME from GL_ROOT where ID=" << l0fid[i] << " ;";
932            //
933            pResult = dbc->Query(myquery.str().c_str());
934            //
935            if( pResult ){
936              //
937              Row = pResult->Next();
938              //
939              if ( debug ) printf(" Using inclination informations from file: %s \n",(((TString)gSystem->ExpandPathName(Row->GetField(0)))+"/"+(TString)Row->GetField(1)).Data());
940              ch->Add(((TString)gSystem->ExpandPathName(Row->GetField(0)))+"/"+(TString)Row->GetField(1));
941              //
942              if (Row) delete Row;
943              pResult->Delete();
944            }
945          }
946          i++;
947        }
948      //      //
949      Double_t upperqtime = 0;      ch->SetBranchAddress("Mcmd",&mcmdev);
950      Double_t lowerqtime = 0;      neventsm = ch->GetEntries();
951            if ( debug ) printf(" entries %u \n", neventsm);
     Double_t incli = 0;  
     oi = 0;  
     UInt_t ooi = 0;  
952      //      //
953      // init quaternions sync      if (neventsm == 0){
954          if ( debug ) printf("InclinationInfo - WARNING: No quaternions in this File");
955          code = 900;
956        }
957        //
958        Double_t lowerqtime = 0;    
959        //
960        // init quaternions information from mcmd-packets
961      //      //
962      Bool_t isf = true;      Bool_t isf = true;
963      Int_t fgh = 0;  
964        vector<Float_t> q0;
965        vector<Float_t> q1;
966        vector<Float_t> q2;
967        vector<Float_t> q3;
968        vector<Double_t> qtime;
969        vector<Float_t> qPitch;
970        vector<Float_t> qRoll;
971        vector<Float_t> qYaw;
972        vector<Int_t> qmode;
973    
974        q0.reserve(4096);
975        q1.reserve(4096);
976        q2.reserve(4096);
977        q3.reserve(4096);
978        qtime.reserve(4096);
979        qPitch.reserve(4096);
980        qRoll.reserve(4096);
981        qYaw.reserve(4096);
982        qmode.reserve(4096);
983        if ( debug ) printf(" q0 capa %i \n",(int)q0.capacity());
984        Int_t nt = 0;
985        UInt_t must = 0;
986    
987        Int_t currentYear = 0;
988        Int_t previousYear = 0;
989    
990      //      //
991      // run over all the events of the run      // run over all the events of the run
992      //      //
993      if (verbose) printf("\n Ready to start! \n\n Processed events: \n\n");      if (verbose) printf("\n Ready to start! \n\n Processed events: \n\n");
994        if ( debug ){
995          printf("BEFORE LOOP ON EVENTS\n");
996          gObjectTable->Print();
997        }
998        //
999      //      //
      //  
1000      for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+runinfo->NEVENTS); re++){      for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+runinfo->NEVENTS); re++){
1001              //for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+10); re++){
1002    
1003        //        //
1004        if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);          if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);  
1005        if ( debug ) printf(" %i \n",procev);              if ( debug ) printf(" %i \n",procev);      
1006        //        //
1007        l0head->GetEntry(re);        if ( l0head->GetEntry(re) <= 0 ) throw -36;
1008        //        //
1009        // absolute time of this event        // absolute time of this event
1010        //        //
1011        ph = eh->GetPscuHeader();        ph = eh->GetPscuHeader();
1012        atime = dbtime->DBabsTime(ph->GetOrbitalTime());        atime = dbtime->DBabsTime(ph->GetOrbitalTime());
1013          if ( debug ) printf(" %i absolute time \n",procev);      
1014        //        //
1015        // paranoid check        // paranoid check
1016        //        //
1017        if ( (atime > (runinfo->RUNTRAILER_TIME+1)) || (atime < (runinfo->RUNHEADER_TIME-1))  ) {        if ( (atime > (runinfo->RUNTRAILER_TIME+1)) || (atime < (runinfo->RUNHEADER_TIME-1))  ) {
1018          if (verbose) printf(" OrbitalInfo - WARNING: event at time outside the run time window, skipping it\n");          if (verbose) printf(" OrbitalInfo - WARNING: event at time outside the run time window, skipping it\n");
1019          jumped++;          jumped++;
1020  //      debug = true;          //  debug = true;
1021          continue;          continue;
1022        }        }
1023    
1024          // just for testing:
1025          //      if (re >= 5+runinfo->EV_FROM) atime += anni5;
1026          //      if (re >= 7+runinfo->EV_FROM) atime += anni5;
1027          //      if (re >= 9+runinfo->EV_FROM) atime += anni5;
1028    
1029          //
1030          // open IGRF files and do it only once if we are processing a full level2 file
1031          //
1032          Float_t kkyear;
1033          UInt_t kyear, kmonth, kday, khour, kmin, ksec;
1034          //
1035          TTimeStamp kt = TTimeStamp(atime, kTRUE);
1036          kt.GetDate(kTRUE, 0, &kyear, &kmonth, &kday);
1037          kt.GetTime(kTRUE, 0, &khour, &kmin, &ksec);
1038          kkyear = (float) kyear
1039            + (kmonth*31.+ (float) kday)/365.
1040            + (khour*3600.+kmin*60.+(float)ksec)/(24.*3600.*365.);
1041          currentYear = int(kkyear/5.) * 5;
1042          if ( debug ) printf(" prevy %i curry %i igrfloaded %i \n",previousYear,currentYear,igrfloaded);
1043          if ( currentYear != previousYear ) igrfloaded = false;
1044          previousYear = currentYear;
1045          if ( debug ) printf(" prevy %i curry %i igrfloaded %i \n",previousYear,currentYear,igrfloaded);
1046          //
1047          if ( !igrfloaded ){
1048            
1049            igrfloaded = true;
1050            
1051            parerror=glparam->Query_GL_PARAM(atime,302,dbc); // parameters stored in DB in GL_PRAM table  
1052            if ( parerror<0 ) {
1053              code = parerror;
1054              goto closeandexit;
1055            }
1056            ltp1 = (Int_t)(glparam->PATH+glparam->NAME).Length();
1057            if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
1058            //
1059            if ( glparam->NAME.EndsWith("s.txt") || glparam->NAME.EndsWith("s.dat") ){
1060              if ( verbose ) printf("ERROR: Current date is beyond the latest secular variation file time span. Please update IGRF files to process data\n");
1061              throw -906;
1062            }
1063            //
1064            int isSecular = false;
1065            //
1066            parerror=glparam2->Query_GL_PARAM(atime+anni5,302,dbc); // parameters stored in DB in GL_PRAM table  
1067            if ( parerror<0 ) {
1068              code = parerror;
1069              goto closeandexit;
1070            }
1071            ltp2 = (Int_t)(glparam2->PATH+glparam2->NAME).Length();
1072            if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam2->PATH+glparam2->NAME).Data());
1073            if ( glparam2->NAME.EndsWith("s.txt") || glparam2->NAME.EndsWith("s.dat") ){
1074              isSecular = true;
1075              if ( verbose ) printf(" Using secular variation file and hence fortran subroutine 'extrapolation'\n");
1076            } else {
1077              if ( verbose ) printf(" Using two field measurement files and hence fortran subroutine 'interpolation'\n");
1078            }
1079            //
1080            initize_(&isSecular,(char *)(glparam->PATH+glparam->NAME).Data(),&ltp1,(char *)(glparam2->PATH+glparam2->NAME).Data(),&ltp2);
1081            //
1082            if (debug) cout<<"initize: "<<(char *)(glparam->PATH+glparam->NAME).Data()<<"\t"<<(char *)(glparam2->PATH+glparam2->NAME).Data()<<"\t isSecular? "<<isSecular<<endl;  
1083    
1084            //        GM_ScanIGRF(dbc, &G0, &G1, &H1);
1085            TString igrfFile1 = glparam->PATH+glparam->NAME;
1086            TString igrfFile2 = glparam2->PATH+glparam2->NAME;
1087            GM_SetIGRF(isSecular,igrfFile1,igrfFile2, &G0, &G1, &H1);
1088          }
1089          //
1090          // End IGRF stuff//
1091          //
1092    
1093        //        //
1094        // retrieve tof informations        // retrieve tof informations
1095        //        //
1096        if ( !reprocall ){        if ( !reprocall ){
1097          itr = nobefrun + (re - evfrom - jumped);          itr = nobefrun + (re - evfrom - jumped);
1098          //itr = re-(46438+200241);          //itr = re-(46438+200241);
1099        } else {        } else {
1100          itr = runinfo->GetFirstEntry() + (re - evfrom - jumped);          itr = runinfo->GetFirstEntry() + (re - evfrom - jumped);
1101        };        };
1102        //        //
1103        if ( !standalone ){        if ( !standalone ){
1104          if ( itr > nevtofl2 ){            if ( itr > nevtofl2 ){  
1105            if ( verbose ) printf(" OrbitalInfo - ERROR: no tof events with entry = %i in Level2 file\n",itr);            if ( verbose ) printf(" OrbitalInfo - ERROR: no tof events with entry = %i in Level2 file\n",itr);
1106            if ( debug ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);            if ( debug ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);
1107            l0File->Close();            l0File->Close();
1108            code = -901;            code = -904;
1109            goto closeandexit;            goto closeandexit;
1110          };          };
1111          //          //
1112          tof->Clear();          tof->Clear();
1113          //          //
1114          ttof->GetEntry(itr);          // Clones array must be cleared before going on
1115          //          //
1116        };          if ( hasNucleiTof ){
1117              tcNucleiTof->Delete();
1118            }
1119            if ( hasExtNucleiTof ){
1120              tcExtNucleiTof->Delete();
1121            }          
1122            if ( hasExtTof ){
1123              tcExtTof->Delete();
1124            }
1125            //
1126            if ( verbose ) printf(" get tof tree entries... entry = %i in Level2 file\n",itr);
1127            if ( ttof->GetEntry(itr) <= 0 ){
1128              if ( verbose ) printf(" problems with tof tree entries... entry = %i in Level2 file\n",itr);
1129              if ( verbose ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);
1130              throw -36;
1131            }
1132            if ( verbose ) printf(" gat0\n");
1133            //
1134          }
1135          //
1136          // retrieve tracker informations
1137          //
1138          if ( !standalone ){
1139            if ( itr > nevtrkl2 ){  
1140              if ( verbose ) printf(" OrbitalInfo - ERROR: no trk events with entry = %i in Level2 file\n",itr);
1141              if ( debug ) printf(" nobefrun %u re %u evfrom %u jumped %u reprocall %i \n",nobefrun,re,evfrom,jumped,reprocall);
1142              l0File->Close();
1143              code = -905;
1144              goto closeandexit;
1145            }
1146            //
1147            if ( verbose ) printf(" gat1\n");
1148            trke->Clear();
1149            //
1150            // Clones array must be cleared before going on
1151            //
1152            if ( hasNucleiTrk ){
1153              if ( verbose ) printf(" gat2\n");
1154              tcNucleiTrk->Delete();
1155              if ( verbose ) printf(" gat3\n");
1156              torbNucleiTrk->Delete();
1157            }
1158            if ( hasExtNucleiTrk ){
1159              if ( verbose ) printf(" gat4\n");
1160              tcExtNucleiTrk->Delete();
1161              if ( verbose ) printf(" gat5\n");
1162              torbExtNucleiTrk->Delete();
1163            }          
1164            if ( hasExtTrk ){
1165              if ( verbose ) printf(" gat6\n");
1166              tcExtTrk->Delete();
1167              if ( verbose ) printf(" gat7\n");
1168              torbExtTrk->Delete();
1169            }
1170            //
1171            if ( verbose ) printf(" get trk tree entries... entry = %i in Level2 file\n",itr);
1172            if ( ttrke->GetEntry(itr) <= 0 ) throw -36;
1173            //
1174          }
1175    
1176        //        //
1177        procev++;        procev++;
1178        //        //
1179        // start processing        // start processing
1180        //        //
1181          if ( debug ) printf(" %i start processing \n",procev);      
1182        orbitalinfo->Clear();        orbitalinfo->Clear();
1183    
1184        //        //
1185        OrbitalInfoTrkVar *t_orb = new OrbitalInfoTrkVar();        OrbitalInfoTrkVar *t_orb = new OrbitalInfoTrkVar();
1186        if( !(orbitalinfo->OrbitalInfoTrk) ) orbitalinfo->OrbitalInfoTrk = new TClonesArray("OrbitalInfoTrkVar",2);        if( !(orbitalinfo->OrbitalInfoTrk) ) orbitalinfo->OrbitalInfoTrk = new TClonesArray("OrbitalInfoTrkVar",2);
1187        TClonesArray &tor = *orbitalinfo->OrbitalInfoTrk;        TClonesArray &tor = *orbitalinfo->OrbitalInfoTrk;
1188    
1189          // Geomagnetic coordinates calculation variables
1190          GMtype_CoordSpherical CoordSpherical, DipoleSpherical;
1191          GMtype_CoordCartesian CoordCartesian, DipoleCartesian;
1192          GMtype_Model Model;
1193          GMtype_Pole Pole;
1194    
1195        //        //
1196        // Fill OBT, pkt_num and absTime        // Fill OBT, pkt_num and absTime
1197        //              //      
1198        orbitalinfo->pkt_num = ph->GetCounter();        orbitalinfo->pkt_num = ph->GetCounter();
1199        orbitalinfo->OBT = ph->GetOrbitalTime();        orbitalinfo->OBT = ph->GetOrbitalTime();
1200        orbitalinfo->absTime = atime;        orbitalinfo->absTime = atime;
1201          if ( debug ) printf(" %i pktnum obt abstime \n",procev);      
1202        //        //
1203        // Propagate the orbit from the tle time to atime, using SGP(D)4.        // Propagate the orbit from the tle time to atime, using SGP(D)4.
1204        //        //
1205          if ( debug ) printf(" %i sgp4 \n",procev);      
1206        cCoordGeo coo;        cCoordGeo coo;
1207        float jyear=0;            Float_t jyear=0.;
1208        //        //
1209        if(atime >= gltle->GetToTime()) {        if(atime >= gltle->GetToTime() || atime < gltle->GetFromTime() ) {  // AGH! bug when reprocessing??
1210          if ( !gltle->Query(atime, dbc) ){  
1211            //                if ( !gltle->Query(atime, dbc) ){
1212            // Compute the magnetic dipole moment.            //    
1213            //            // Compute the magnetic dipole moment.
1214            UInt_t year, month, day, hour, min, sec;            //
1215            //            if ( debug ) printf(" %i compute magnetic dipole moment \n",procev);      
1216            TTimeStamp t = TTimeStamp(atime, kTRUE);            UInt_t year, month, day, hour, min, sec;
1217            t.GetDate(kTRUE, 0, &year, &month, &day);            //
1218            t.GetTime(kTRUE, 0, &hour, &min, &sec);            TTimeStamp t = TTimeStamp(atime, kTRUE);
1219            jyear = (float) year            t.GetDate(kTRUE, 0, &year, &month, &day);
1220              + (month*31.+ (float) day)/365.            t.GetTime(kTRUE, 0, &hour, &min, &sec);
1221              + (hour*3600.+min*60.+(float)sec)/(24*3600*365.);            jyear = (float) year
1222            //              + (month*31.+ (float) day)/365.
1223            feldcof_(&jyear, &dimo); // get dipole moment for year              + (hour*3600.+min*60.+(float)sec)/(24.*3600.*365.);
1224          } else {            //
1225            code = -56;            if ( debug ) printf(" %i compute magnetic dipole moment get dipole moment for year\n",procev);            
1226            goto closeandexit;            if ( debug ) printf(" %i jyear %f dimo %f \n",procev,jyear,dimo);
1227          };            feldcof_(&jyear, &dimo); // get dipole moment for year
1228              if ( debug ) printf(" %i compute magnetic dipole moment end\n",procev);
1229    
1230              //    GM_TimeAdjustCoefs(year, jyear, G0, G1, H1, &Model);
1231              GM_TimeAdjustCoefs(GM_STARTYEAR, (jyear-currentYear+GM_STARTYEAR), G0, G1, H1, &Model);  // EM: input this way due to the new way of storing data into Gn,H1 and to avoid changing GM_Time...
1232              GM_PoleLocation(Model, &Pole);
1233            } else {
1234              code = -56;
1235              goto closeandexit;
1236            };
1237        }        }
1238        coo = getCoo(atime, gltle->GetFromTime(), gltle->GetTle());        coo = getCoo(atime, gltle->GetFromTime(), gltle->GetTle());
1239        //        //
1240        cOrbit orbits(*gltle->GetTle());        cOrbit orbits(*gltle->GetTle());
1241        //        //
       if ( debug ) printf(" I am Here \n");  
       //  
1242        // synchronize with quaternions data        // synchronize with quaternions data
1243        //        //
1244        if ( isf && neventsm>0 ){        if ( isf && neventsm>0 ){
1245          if ( debug ) printf(" I am here \n");          //
1246          //          // First event
1247          // First event          //
1248          //          isf = false;
1249          isf = false;          //  upperqtime = atime;
1250          upperqtime = atime;          lowerqtime = runinfo->RUNHEADER_TIME;
1251          lowerqtime = runinfo->RUNHEADER_TIME;          for ( ik = 0; ik < neventsm; ik++){  //number of macrocommad packets
1252          for ( ik = 0; ik < neventsm; ik++){            if ( ch->GetEntry(ik) <= 0 ) throw -36;
1253            l0trm->GetEntry(ik);            tmpSize = mcmdev->Records->GetEntries();
1254            tmpSize = mcmdev->Records->GetEntries();            //    numrec = tmpSize;
1255            numrec = tmpSize;            if ( debug ) cout << "packet number " << ik <<"\tnumber of subpackets is " << tmpSize << endl;
1256            for (Int_t j3 = 0;j3<tmpSize;j3++){              for (Int_t j3 = 0;j3<tmpSize;j3++){  //number of subpackets
1257              if ( debug ) printf(" eh eh eh \n");                mcmdrc = (pamela::McmdRecord*)mcmdev->Records->At(j3);
1258              mcmdrc = (pamela::McmdRecord*)mcmdev->Records->At(j3);                if ( mcmdrc ){ // missing inclination bug [8RED 090116]
1259              if ((int)mcmdrc->ID1 == 226){                  if ( debug ) printf(" pluto \n");
1260                L_QQ_Q_l_upper->fill(mcmdrc->McmdData);                  if ((int)mcmdrc->ID1 == 226 && mcmdrc->Mcmd_Block_crc_ok == 1){ //Check that it is Inclination Packet
1261                for (UInt_t ui = 0; ui < 6; ui++){                    L_QQ_Q_l_upper->fill(mcmdrc->McmdData);
1262                  if (ui>0){                    for (UInt_t ui = 0; ui < 6; ui++){
1263                    if (L_QQ_Q_l_upper->time[ui]>L_QQ_Q_l_upper->time[0]){                      if (ui>0){
1264                      if (dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000))<atime){                        if (L_QQ_Q_l_upper->time[ui]>L_QQ_Q_l_upper->time[0]){
1265                        upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000));                          Double_t u_time = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000));
1266                        orbits.getPosition((double) (upperqtime - gltle->GetFromTime())/60., &eCi);                          Int_t recSize = recqtime.size();
1267                        RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[ui][0],L_QQ_Q_l_upper->quat[ui][1],L_QQ_Q_l_upper->quat[ui][2],L_QQ_Q_l_upper->quat[ui][3]);                          if(lowerqtime > recqtime[recSize-1]){
1268                      }else {                            // to avoid interpolation between bad quaternions arrays
1269                        lowerqtime = upperqtime;                            if(sqrt(pow(L_QQ_Q_l_upper->quat[ui][0],2)+pow(L_QQ_Q_l_upper->quat[ui][1],2)+pow(L_QQ_Q_l_upper->quat[ui][2],2)+pow(L_QQ_Q_l_upper->quat[ui][3],2))>0.99999){
1270                        upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000));                              Int_t sizeqmcmd = qtime.size();
1271                        orbits.getPosition((double) (upperqtime - gltle->GetFromTime())/60., &eCi);                              inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1272                        RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[ui][0],L_QQ_Q_l_upper->quat[ui][1],L_QQ_Q_l_upper->quat[ui][2],L_QQ_Q_l_upper->quat[ui][3]);                              qtime[sizeqmcmd]=u_time;
1273                        mcreen = j3;                              q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][0];
1274                        mctren = ik;                              q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][1];
1275                        if(fgh==0){                              q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][2];
1276                          CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);                              q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][3];
1277                          CopyAng(RYPang_lower,RYPang_upper);                              qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1278                        }                              lowerqtime = u_time;
1279                        oi=ui;                              orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1280                        goto closethisloop;                              RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[ui][0],L_QQ_Q_l_upper->quat[ui][1],L_QQ_Q_l_upper->quat[ui][2],L_QQ_Q_l_upper->quat[ui][3]);
1281                      }                              qRoll[sizeqmcmd]=RYPang_upper->Kren;
1282                      fgh++;                              qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1283                      CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);                              qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1284                      CopyAng(RYPang_lower,RYPang_upper);                            }
1285                    }                          }
1286                  }else{                          for(Int_t mu = nt;mu<recSize;mu++){
1287                    if (dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))<atime){                            if(recqtime[mu]>lowerqtime && recqtime[mu]<u_time){
1288                      upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                              if(sqrt(pow(recq0[mu],2)+pow(recq1[mu],2)+pow(recq2[mu],2)+pow(recq3[mu],2))>0.99999){
1289                      orbits.getPosition((double) (upperqtime - gltle->GetFromTime())/60., &eCi);                                nt=mu;
1290                      RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[0][0],L_QQ_Q_l_upper->quat[0][1],L_QQ_Q_l_upper->quat[0][2],L_QQ_Q_l_upper->quat[0][3]);                                Int_t sizeqmcmd = qtime.size();
1291                    }                                inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1292                    else {                                qtime[sizeqmcmd]=recqtime[mu];
1293                      lowerqtime = upperqtime;                                q0[sizeqmcmd]=recq0[mu];
1294                      upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                                q1[sizeqmcmd]=recq1[mu];
1295                      orbits.getPosition((double) (upperqtime - gltle->GetFromTime())/60., &eCi);                                q2[sizeqmcmd]=recq2[mu];
1296                      RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[0][0],L_QQ_Q_l_upper->quat[0][1],L_QQ_Q_l_upper->quat[0][2],L_QQ_Q_l_upper->quat[0][3]);                                q3[sizeqmcmd]=recq3[mu];
1297                      mcreen = j3;                                qmode[sizeqmcmd]=-10;
1298                      mctren = ik;                                orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);
1299                      if(fgh==0){                                RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,recq0[mu],recq1[mu],recq2[mu],recq3[mu]);
1300                        CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);                                qRoll[sizeqmcmd]=RYPang_upper->Kren;
1301                        CopyAng(RYPang_lower,RYPang_upper);                                qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1302                        lowerqtime = atime-1;                                qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1303                      }                              }
1304                      oi=ui;                            }
1305                      goto closethisloop;                            if(recqtime[mu]>=u_time){
1306                      //_0 = true;                              if(sqrt(pow(L_QQ_Q_l_upper->quat[ui][0],2)+pow(L_QQ_Q_l_upper->quat[ui][1],2)+pow(L_QQ_Q_l_upper->quat[ui][2],2)+pow(L_QQ_Q_l_upper->quat[ui][3],2))>0.99999){
1307                    }                                Int_t sizeqmcmd = qtime.size();
1308                    fgh++;                                inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1309                    CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);                                qtime[sizeqmcmd]=u_time;
1310                    CopyAng(RYPang_lower,RYPang_upper);                                q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][0];
1311                    //_0 = true;                                q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][1];
1312                  };                                q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][2];
1313                  //cin>>grib;                                q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[ui][3];
1314                };                                qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1315              };                                lowerqtime = u_time;
1316            };                                orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1317          };                                RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[ui][0],L_QQ_Q_l_upper->quat[ui][1],L_QQ_Q_l_upper->quat[ui][2],L_QQ_Q_l_upper->quat[ui][3]);
1318        };                                qRoll[sizeqmcmd]=RYPang_upper->Kren;
1319      closethisloop:                                qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1320        //                                qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1321        if ( debug ) printf(" I am There \n");                                break;
1322        //                              }
1323        if (((atime>(UInt_t)upperqtime)||(atime<(UInt_t)lowerqtime)) && neventsm>0 ){                            }
1324          if ( debug ) printf(" I am there \n");                          }
1325          //                        }
1326          lowerqtime = upperqtime;                      }else{
1327          Long64_t maxloop = 100000000LL;                        //if ( debug ) printf(" here2 %i \n",ui);
1328          Long64_t mn = 0;                        Double_t u_time = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
1329          bool gh=false;                        if(lowerqtime>u_time)nt=0;
1330          ooi=oi;                        Int_t recSize = recqtime.size();
1331          if ( verbose ) printf(" OrbitalInfoCore: sync with quaternions data upperqtime %u lowerqtime %u atime %u \n",(UInt_t)upperqtime,(UInt_t)lowerqtime,atime);                        if(lowerqtime > recqtime[recSize-1]){
1332          while (!gh){                                if(sqrt(pow(L_QQ_Q_l_upper->quat[ui][0],2)+pow(L_QQ_Q_l_upper->quat[ui][1],2)+pow(L_QQ_Q_l_upper->quat[ui][2],2)+pow(L_QQ_Q_l_upper->quat[ui][3],2))>0.99999){
1333            if ( mn > maxloop ){                            Int_t sizeqmcmd = qtime.size();
1334              if ( verbose ) printf(" OrbitalInfoCore: quaternions sync out of range! exiting\n");                            inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1335              gh = true;                            qtime[sizeqmcmd]=u_time;
1336              neventsm = 0;                            q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][0];
1337            };                            q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][1];
1338            mn++;                            q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][2];
1339            if (oi<5) oi++;                            q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][3];
1340            else oi=0;                            qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1341            if (oi==0 && numrec > 0){                            lowerqtime = u_time;
1342              if ( debug ) printf(" mumble \n");                            orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1343              mcreen++;                            RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[0][0],L_QQ_Q_l_upper->quat[0][1],L_QQ_Q_l_upper->quat[0][2],L_QQ_Q_l_upper->quat[0][3]);
1344              if (mcreen == numrec){                            qRoll[sizeqmcmd]=RYPang_upper->Kren;
1345                mctren++;                            qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1346                mcreen = 0;                            qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1347                l0trm->GetEntry(mctren);                          }
1348                numrec = mcmdev->Records->GetEntries();                        }
1349              }                        for(Int_t mu = nt;mu<recSize;mu++){
1350              CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);                          if(recqtime[mu]>lowerqtime && recqtime[mu]<u_time){
1351              CopyAng(RYPang_lower,RYPang_upper);                           if(sqrt(pow(recq0[mu],2)+pow(recq1[mu],2)+pow(recq2[mu],2)+pow(recq3[mu],2))>0.99999){
1352              mcmdrc = (pamela::McmdRecord*)mcmdev->Records->At(mcreen);                             Int_t sizeqmcmd = qtime.size();
1353              if ((int)mcmdrc->ID1 == 226){                             inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1354                L_QQ_Q_l_upper->fill(mcmdrc->McmdData);                             qtime[sizeqmcmd]=recqtime[mu];
1355                upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                             q0[sizeqmcmd]=recq0[mu];
1356                if (upperqtime<lowerqtime){                             q1[sizeqmcmd]=recq1[mu];
1357                  upperqtime=runinfo->RUNTRAILER_TIME;                             q2[sizeqmcmd]=recq2[mu];
1358                  CopyQ(L_QQ_Q_l_upper,L_QQ_Q_l_lower);                             q3[sizeqmcmd]=recq3[mu];
1359                  CopyAng(RYPang_upper,RYPang_lower);                             qmode[sizeqmcmd]=-10;
1360                }else{                             orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);
1361                  orbits.getPosition((double) (upperqtime - gltle->GetFromTime())/60., &eCi);                             RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,recq0[mu],recq1[mu],recq2[mu],recq3[mu]);
1362                  RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[0][0],L_QQ_Q_l_upper->quat[0][1],L_QQ_Q_l_upper->quat[0][2],L_QQ_Q_l_upper->quat[0][3]);                             qRoll[sizeqmcmd]=RYPang_upper->Kren;
1363                }                             qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1364                //              re--;                             qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1365                gh=true;                           }
1366              }                          }
1367            }else{                          if(recqtime[mu]>=u_time){
1368              if ((Int_t)L_QQ_Q_l_upper->time[oi]>(Int_t)L_QQ_Q_l_upper->time[0]){                            if(sqrt(pow(L_QQ_Q_l_upper->quat[0][0],2)+pow(L_QQ_Q_l_upper->quat[0][1],2)+pow(L_QQ_Q_l_upper->quat[0][2],2)+pow(L_QQ_Q_l_upper->quat[0][3],2))>0.99999){
1369                upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                              Int_t sizeqmcmd = qtime.size();
1370                orbits.getPosition((double) (upperqtime - gltle->GetFromTime())/60., &eCi);                              inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1371                RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[oi][0],L_QQ_Q_l_upper->quat[oi][1],L_QQ_Q_l_upper->quat[oi][2],L_QQ_Q_l_upper->quat[oi][3]);                              qtime[sizeqmcmd]=u_time;
1372                orbits.getPosition((double) (lowerqtime - gltle->GetFromTime())/60., &eCi);                              q0[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][0];
1373                RYPang_lower->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[oi-1][0],L_QQ_Q_l_upper->quat[oi-1][1],L_QQ_Q_l_upper->quat[oi-1][2],L_QQ_Q_l_upper->quat[oi-1][3]);                              q1[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][1];
1374                //              re--;                              q2[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][2];
1375                gh=true;                              q3[sizeqmcmd]=L_QQ_Q_l_upper->quat[0][3];
1376              };                              qmode[sizeqmcmd]=holeq(lowerqtime,qtime[sizeqmcmd],L_QQ_Q_l_lower,L_QQ_Q_l_upper,ui);
1377            };                              lowerqtime = u_time;
1378          };                              orbits.getPosition((double) (u_time - gltle->GetFromTime())/60., &eCi);
1379          if ( verbose ) printf(" OrbitalInfoCore: sync with quaternions data now we have upperqtime %u lowerqtime %u atime %u \n",(UInt_t)upperqtime,(UInt_t)lowerqtime,atime);                              RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,L_QQ_Q_l_upper->quat[0][0],L_QQ_Q_l_upper->quat[0][1],L_QQ_Q_l_upper->quat[0][2],L_QQ_Q_l_upper->quat[0][3]);
1380        };                              qRoll[sizeqmcmd]=RYPang_upper->Kren;
1381        //                              qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1382        if ( debug ) printf(" I am THIS \n");                              qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1383        //                              CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);
1384        // Fill in quaternions and angles                              break;
1385        //                            }
1386        if ((atime<=(UInt_t)upperqtime)&&(atime>=(UInt_t)lowerqtime)&& neventsm>0){                                }
1387          if ( debug ) printf(" I am this \n");                        }
1388          UInt_t tut = holeq(lowerqtime, upperqtime, L_QQ_Q_l_lower, L_QQ_Q_l_upper, oi);                      }
1389          if (oi == 0){                    }
1390            if ((tut!=5)||(tut!=6)){                  }
1391              incli = (L_QQ_Q_l_upper->quat[0][0]-L_QQ_Q_l_lower->quat[ooi][0])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));                }
1392              orbitalinfo->q0 =  incli*atime+L_QQ_Q_l_upper->quat[0][0]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));              }
1393              incli =     (L_QQ_Q_l_upper->quat[0][1]-L_QQ_Q_l_lower->quat[ooi][1])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));            }
1394              orbitalinfo->q1 =  incli*atime+L_QQ_Q_l_upper->quat[0][1]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));    
1395              incli = (L_QQ_Q_l_upper->quat[0][2]-L_QQ_Q_l_lower->quat[ooi][2])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));            if(qtime.size()==0){        // in case if no orientation information in data
1396              orbitalinfo->q2 =  incli*atime+L_QQ_Q_l_upper->quat[0][2]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));              if ( debug ) cout << "qtime.size() = 0" << endl;
1397              incli = (L_QQ_Q_l_upper->quat[0][3]-L_QQ_Q_l_lower->quat[ooi][3])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));              for(UInt_t my=0;my<recqtime.size();my++){
1398              orbitalinfo->q3 =  incli*atime+L_QQ_Q_l_upper->quat[0][3]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                if(sqrt(pow(recq0[my],2)+pow(recq1[my],2)+pow(recq2[my],2)+pow(recq3[my],2))>0.99999){
1399                            Int_t sizeqmcmd = qtime.size();
1400              incli = (RYPang_upper->Tangazh-RYPang_lower->Tangazh)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));                  inclresize(qtime,q0,q1,q2,q3,qmode,qRoll,qPitch,qYaw);
1401              orbitalinfo->theta =  incli*atime+RYPang_upper->Tangazh-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                  qtime[sizeqmcmd]=recqtime[my];
1402              incli = (RYPang_upper->Ryskanie-RYPang_lower->Ryskanie)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));                  q0[sizeqmcmd]=recq0[my];
1403              orbitalinfo->phi =  incli*atime+RYPang_upper->Ryskanie-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                  q1[sizeqmcmd]=recq1[my];
1404              incli = (RYPang_upper->Kren-RYPang_lower->Kren)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000)));                  q2[sizeqmcmd]=recq2[my];
1405              orbitalinfo->etha =  incli*atime+RYPang_upper->Kren-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                  q3[sizeqmcmd]=recq3[my];
1406            }                  qmode[sizeqmcmd]=-10;
1407            if (tut==6){                  orbits.getPosition((double) (qtime[sizeqmcmd] - gltle->GetFromTime())/60., &eCi);
1408              if (fabs(RYPang_lower->Kren-RYPang_upper->Kren)<0.1){                  RYPang_upper->TransAngle(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,recq0[my],recq1[my],recq2[my],recq3[my]);
1409                incli = (L_QQ_Q_l_upper->quat[0][0]-L_QQ_Q_l_lower->quat[ooi][0])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));                  qRoll[sizeqmcmd]=RYPang_upper->Kren;
1410                orbitalinfo->q0 =  incli*atime+L_QQ_Q_l_upper->quat[0][0]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                  qYaw[sizeqmcmd]=RYPang_upper->Ryskanie;
1411                incli =           (L_QQ_Q_l_upper->quat[0][1]-L_QQ_Q_l_lower->quat[ooi][1])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));                  qPitch[sizeqmcmd]=RYPang_upper->Tangazh;
1412                orbitalinfo->q1 =  incli*atime+L_QQ_Q_l_upper->quat[0][1]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));                }
1413                incli = (L_QQ_Q_l_upper->quat[0][2]-L_QQ_Q_l_lower->quat[ooi][2])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));              }
1414                orbitalinfo->q2 =  incli*atime+L_QQ_Q_l_upper->quat[0][2]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));            }
1415                incli = (L_QQ_Q_l_upper->quat[0][3]-L_QQ_Q_l_lower->quat[ooi][3])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));            //if ( debug ) printf(" puffi \n");
1416                orbitalinfo->q3 =  incli*atime+L_QQ_Q_l_upper->quat[0][3]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));            Double_t tmin = 9999999999.;
1417                      Double_t tmax = 0.;
1418                incli = (RYPang_upper->Tangazh-RYPang_lower->Tangazh)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));            for(UInt_t tre = 0;tre<qtime.size();tre++){
1419                orbitalinfo->theta =  incli*atime+RYPang_upper->Tangazh-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));              if(qtime[tre]>tmax)tmax = qtime[tre];
1420                incli = (RYPang_upper->Ryskanie-RYPang_lower->Ryskanie)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));              if(qtime[tre]<tmin)tmin = qtime[tre];
1421                orbitalinfo->phi =  incli*atime+RYPang_upper->Ryskanie-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));            }
1422                //cout<<"upper = "<<RYPang_upper->Ryskanie<<" lower = "<<RYPang_lower->Ryskanie<<" timeupper[0] = "<<L_QQ_Q_l_upper->time[0]-5500000<<" timelower["<<ooi<<"] = "<<L_QQ_Q_l_lower->time[ooi]-5500000<<" Ryscanie = "<<orbitalinfo->phi<<" incli = "<<incli<<" upper-lower = "<<RYPang_upper->Ryskanie-RYPang_lower->Ryskanie<<" Dtime = "<<dbtime->DBabsTime((UInt_t)L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000)<<"-"<<dbtime->DBabsTime((UInt_t)L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)<<" atime = "<<atime<<"\n";            // sorting quaternions by time
1423                //cin>>grib;            Bool_t t = true;
1424                incli = (RYPang_upper->Kren-RYPang_lower->Kren)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_lower->time[ooi]*1000-DeltaOBT*1000)));            while(t){
1425                orbitalinfo->etha =  incli*atime+RYPang_upper->Kren-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));              t=false;
1426              }              for(UInt_t i=0;i<qtime.size()-1;i++){
1427            }                if(qtime[i]>qtime[i+1]){
1428          } else {                  Double_t tmpr = qtime[i];
1429            if((tut!=6)||(tut!=7)||(tut!=9)){                  qtime[i]=qtime[i+1];
1430              incli = (L_QQ_Q_l_upper->quat[oi][0]-L_QQ_Q_l_upper->quat[oi-1][0])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));                  qtime[i+1] = tmpr;
1431              orbitalinfo->q0 =  incli*atime+L_QQ_Q_l_upper->quat[oi][0]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                  tmpr = q0[i];
1432              incli = (L_QQ_Q_l_upper->quat[oi][1]-L_QQ_Q_l_upper->quat[oi-1][1])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));                  q0[i]=q0[i+1];
1433              orbitalinfo->q1 =  incli*atime+L_QQ_Q_l_upper->quat[oi][1]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                  q0[i+1] = tmpr;
1434              incli = (L_QQ_Q_l_upper->quat[oi][2]-L_QQ_Q_l_upper->quat[oi-1][2])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));                  tmpr = q1[i];
1435              orbitalinfo->q2 =  incli*atime+L_QQ_Q_l_upper->quat[oi][2]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                  q1[i]=q1[i+1];
1436              incli = (L_QQ_Q_l_upper->quat[oi][3]-L_QQ_Q_l_upper->quat[oi-1][3])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));                  q1[i+1] = tmpr;
1437              orbitalinfo->q3 =  incli*atime+L_QQ_Q_l_upper->quat[oi][3]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                  tmpr = q2[i];
1438                            q2[i]=q2[i+1];
1439              incli = (RYPang_upper->Tangazh-RYPang_lower->Tangazh)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));                  q2[i+1] = tmpr;
1440              orbitalinfo->theta =  incli*atime+RYPang_upper->Tangazh-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                  tmpr = q3[i];
1441              incli = (RYPang_upper->Ryskanie-RYPang_lower->Ryskanie)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));                  q3[i]=q3[i+1];
1442              orbitalinfo->phi =  incli*atime+RYPang_upper->Ryskanie-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                  q3[i+1] = tmpr;
1443              //cout<<"upper = "<<RYPang_upper->Ryskanie<<" lower = "<<RYPang_lower->Ryskanie<<" timeupper["<<oi<<"] = "<<L_QQ_Q_l_upper->time[oi]-5500000<<" timelower["<<oi-1<<"] = "<<L_QQ_Q_l_lower->time[oi-1]-5500000<<" Ryscanie = "<<orbitalinfo->phi<<" incli = "<<incli<<" upper-lower = "<<RYPang_upper->Ryskanie-RYPang_lower->Ryskanie<<" Dtime = "<<dbtime->DBabsTime((UInt_t)L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000)<<"-"<<dbtime->DBabsTime((UInt_t)L_QQ_Q_l_lower->time[oi-1]*1000-DeltaOBT*1000)<<" atime = "<<atime<<"\n";                  tmpr = qRoll[i];
1444              //cin>>grib;                  qRoll[i]=qRoll[i+1];
1445              incli = (RYPang_upper->Kren-RYPang_lower->Kren)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));                  qRoll[i+1] = tmpr;
1446              orbitalinfo->etha =  incli*atime+RYPang_upper->Kren-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                  tmpr = qYaw[i];
1447            }                  qYaw[i]=qYaw[i+1];
1448            if (tut==6){                  qYaw[i+1] = tmpr;
1449              if (fabs(RYPang_lower->Kren-RYPang_upper->Kren)<0.1){                  tmpr = qPitch[i];
1450                incli = (L_QQ_Q_l_upper->quat[oi][0]-L_QQ_Q_l_upper->quat[oi-1][0])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));                  qPitch[i]=qPitch[i+1];
1451                orbitalinfo->q0 =  incli*atime+L_QQ_Q_l_upper->quat[oi][0]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                  qPitch[i+1] = tmpr;
1452                incli = (L_QQ_Q_l_upper->quat[oi][1]-L_QQ_Q_l_upper->quat[oi-1][1])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));                  t=true;
1453                orbitalinfo->q1 =  incli*atime+L_QQ_Q_l_upper->quat[oi][1]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));                }
1454                incli = (L_QQ_Q_l_upper->quat[oi][2]-L_QQ_Q_l_upper->quat[oi-1][2])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));              }
1455                orbitalinfo->q2 =  incli*atime+L_QQ_Q_l_upper->quat[oi][2]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));            }
1456                incli = (L_QQ_Q_l_upper->quat[oi][3]-L_QQ_Q_l_upper->quat[oi-1][3])/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));            if ( debug ){
1457                orbitalinfo->q3 =  incli*atime+L_QQ_Q_l_upper->quat[oi][3]-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));              cout << "we have loaded quaternions: size of quaternions set is "<< qtime.size() << endl;
1458                        for(UInt_t i=0;i<qtime.size();i++) cout << qtime[i] << "\t";
1459                incli = (RYPang_upper->Tangazh-RYPang_lower->Tangazh)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));              cout << endl << endl;
1460                orbitalinfo->theta =  incli*atime+RYPang_upper->Tangazh-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));              Int_t lopu;
1461                incli = (RYPang_upper->Ryskanie-RYPang_lower->Ryskanie)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));              cin >> lopu;
1462                orbitalinfo->phi =  incli*atime+RYPang_upper->Ryskanie-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));            }
1463                //cout<<"upper = "<<RYPang_upper->Ryskanie<<" lower = "<<RYPang_lower->Ryskanie<<" timeupper["<<oi<<"] = "<<L_QQ_Q_l_upper->time[oi]-5500000<<" timelower["<<oi-1<<"] = "<<L_QQ_Q_l_lower->time[oi-1]-5500000<<" Ryscanie = "<<orbitalinfo->phi<<" incli = "<<incli<<" upper-lower = "<<RYPang_upper->Ryskanie-RYPang_lower->Ryskanie<<" Dtime = "<<dbtime->DBabsTime((UInt_t)L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000)<<"-"<<dbtime->DBabsTime((UInt_t)L_QQ_Q_l_lower->time[oi-1]*1000-DeltaOBT*1000)<<" atime = "<<atime<<"\n";        } // if we processed first event
1464                //cin>>grib;        
1465                incli = (RYPang_upper->Kren-RYPang_lower->Kren)/(dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000))-dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi-1]*1000-DeltaOBT*1000)));        //Filling Inclination information
1466                orbitalinfo->etha =  incli*atime+RYPang_upper->Kren-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));        Double_t incli = 0;
1467              }        if ( qtime.size() > 1 ){
1468            }                      if(atime<qtime[0]){
1469          }            for(UInt_t mu = 1;mu<qtime.size()-1;mu++){
1470          //              if(qtime[mu]>qtime[0]){
1471          orbitalinfo->mode = holeq(lowerqtime, upperqtime, L_QQ_Q_l_lower, L_QQ_Q_l_upper, oi);                incli = (qPitch[mu]-qPitch[0])/(qtime[mu]-qtime[0]);
1472          //                orbitalinfo->theta =  incli*atime+qPitch[mu]-incli*qtime[mu];
1473        } else {                incli = (qRoll[mu]-qRoll[0])/(qtime[mu]-qtime[0]);
1474          if ( debug ) printf(" ops no incl! \n");                orbitalinfo->etha =  incli*atime+qRoll[mu]-incli*qtime[mu];
1475          orbitalinfo->mode = 10;                incli = (qYaw[mu]-qYaw[0])/(qtime[mu]-qtime[0]);
1476        };                orbitalinfo->phi =  incli*atime+qYaw[mu]-incli*qtime[mu];
1477                  
1478                  incli = (q0[mu]-q0[0])/(qtime[mu]-qtime[0]);
1479                  orbitalinfo->q0 =  incli*atime+q0[mu]-incli*qtime[mu];
1480                  incli = (q1[mu]-q1[0])/(qtime[mu]-qtime[0]);
1481                  orbitalinfo->q1 =  incli*atime+q1[mu]-incli*qtime[mu];
1482                  incli = (q2[mu]-q2[0])/(qtime[mu]-qtime[0]);
1483                  orbitalinfo->q2 =  incli*atime+q2[mu]-incli*qtime[mu];
1484                  incli = (q3[mu]-q3[0])/(qtime[mu]-qtime[0]);
1485                  orbitalinfo->q3 =  incli*atime+q3[mu]-incli*qtime[mu];
1486                  orbitalinfo->TimeGap=qtime[0]-atime;
1487                  break;
1488                }
1489              }
1490            }
1491            Float_t eend=qtime.size()-1;
1492            if(atime>qtime[eend]){
1493              for(UInt_t mu=eend-1;mu>=0;mu--){
1494                if(qtime[mu]<qtime[eend]){
1495                  incli = (qPitch[eend]-qPitch[mu])/(qtime[eend]-qtime[mu]);
1496                  orbitalinfo->theta =  incli*atime+qPitch[eend]-incli*qtime[eend];
1497                  incli = (qRoll[eend]-qRoll[mu])/(qtime[eend]-qtime[mu]);
1498                  orbitalinfo->etha =  incli*atime+qRoll[eend]-incli*qtime[eend];
1499                  incli = (qYaw[eend]-qYaw[mu])/(qtime[eend]-qtime[mu]);
1500                  orbitalinfo->phi =  incli*atime+qYaw[eend]-incli*qtime[eend];
1501              
1502                  incli = (q0[eend]-q0[mu])/(qtime[eend]-qtime[mu]);
1503                  orbitalinfo->q0 =  incli*atime+q0[eend]-incli*qtime[eend];
1504                  incli = (q1[eend]-q1[mu])/(qtime[eend]-qtime[mu]);
1505                  orbitalinfo->q1 =  incli*atime+q1[eend]-incli*qtime[eend];
1506                  incli = (q2[eend]-q2[mu])/(qtime[eend]-qtime[mu]);
1507                  orbitalinfo->q2 =  incli*atime+q2[eend]-incli*qtime[eend];
1508                  incli = (q3[eend]-q3[mu])/(qtime[eend]-qtime[mu]);
1509                  orbitalinfo->q3 =  incli*atime+q3[eend]-incli*qtime[eend];
1510                  break;
1511                }
1512              }
1513            }
1514            for(UInt_t mu = must;mu<qtime.size()-1;mu++){
1515              if ( debug ) printf(" ??grfuffi %i sixe %i must %i \n",mu,qtime.size()-1,must);
1516              if(qtime[mu+1]>qtime[mu]){
1517                if ( debug ) cout << "qtime[" << mu << "] = " << qtime[mu] << "\tqtime[" << mu+1 << "] = " << qtime[mu+1] << "\tatime = " << atime << endl;
1518                if(atime<=qtime[mu+1] && atime>=qtime[mu]){
1519                  if ( debug ) cout << "here we have found proper quaternions for interpolation: mu = "<<mu<<endl;
1520                  must = mu;
1521                  incli = (qPitch[mu+1]-qPitch[mu])/(qtime[mu+1]-qtime[mu]);
1522                  orbitalinfo->theta =  incli*atime+qPitch[mu+1]-incli*qtime[mu+1];
1523                  incli = (qRoll[mu+1]-qRoll[mu])/(qtime[mu+1]-qtime[mu]);
1524                  orbitalinfo->etha =  incli*atime+qRoll[mu+1]-incli*qtime[mu+1];
1525                  incli = (qYaw[mu+1]-qYaw[mu])/(qtime[mu+1]-qtime[mu]);
1526                  orbitalinfo->phi =  incli*atime+qYaw[mu+1]-incli*qtime[mu+1];
1527                  
1528                  incli = (q0[mu+1]-q0[mu])/(qtime[mu+1]-qtime[mu]);
1529                  orbitalinfo->q0 =  incli*atime+q0[mu+1]-incli*qtime[mu+1];
1530                  incli = (q1[mu+1]-q1[mu])/(qtime[mu+1]-qtime[mu]);
1531                  orbitalinfo->q1 =  incli*atime+q1[mu+1]-incli*qtime[mu+1];
1532                  incli = (q2[mu+1]-q2[mu])/(qtime[mu+1]-qtime[mu]);
1533                  orbitalinfo->q2 =  incli*atime+q2[mu+1]-incli*qtime[mu+1];
1534                  incli = (q3[mu+1]-q3[mu])/(qtime[mu+1]-qtime[mu]);
1535                  orbitalinfo->q3 =  incli*atime+q3[mu+1]-incli*qtime[mu+1];
1536                  Float_t tg = (qtime[mu+1]-qtime[mu])/1000.0;
1537                  if(tg>=1) tg=0.00;
1538                  orbitalinfo->TimeGap = TMath::Min(TMath::Abs(qtime[mu+1]-atime),TMath::Abs(atime-qtime[mu]))+tg;//qtime[mu+1]-qtime[mu];
1539                  orbitalinfo->mode = qmode[mu+1];
1540                  //if(atime==qtime[mu] || atime==qtime[mu+1]) orbitalinfo->qkind = 0; else orbitalinfo->qkind=1;
1541                  //if(qmode[mu+1]==-10) orbitalinfo->R10r = true;else orbitalinfo->R10r = false;
1542                  if ( debug ) printf(" grfuffi4 %i \n",mu);
1543                  break;
1544                }
1545              }
1546            }
1547          }
1548          if ( debug ) printf(" grfuffi5  \n");
1549        //        //
1550        // ops no inclination information        // ops no inclination information
1551        //        //
1552          
1553        if ( orbitalinfo->q0< -999 || orbitalinfo->q1 < -999 || orbitalinfo->q2 < -999 || orbitalinfo->q3 < -999 || orbitalinfo->q0 != orbitalinfo->q0 || orbitalinfo->q1 != orbitalinfo->q1 || orbitalinfo->q2 != orbitalinfo->q2 || orbitalinfo->q3 != orbitalinfo->q3 ){        if ( orbitalinfo->q0< -999 || orbitalinfo->q1 < -999 || orbitalinfo->q2 < -999 || orbitalinfo->q3 < -999 || orbitalinfo->q0 != orbitalinfo->q0 || orbitalinfo->q1 != orbitalinfo->q1 || orbitalinfo->q2 != orbitalinfo->q2 || orbitalinfo->q3 != orbitalinfo->q3 ){
1554          orbitalinfo->mode = 10;          if (debug) cout << "Warning: no iclination information "<< endl;
1555          orbitalinfo->q0 = -1000.;            orbitalinfo->mode = 10;
1556          orbitalinfo->q1 = -1000.;            orbitalinfo->q0 = -1000.;
1557          orbitalinfo->q2 = -1000.;            orbitalinfo->q1 = -1000.;
1558          orbitalinfo->q3 = -1000.;            orbitalinfo->q2 = -1000.;
1559          orbitalinfo->etha = -1000.;            orbitalinfo->q3 = -1000.;
1560          orbitalinfo->phi = -1000.;            orbitalinfo->etha = -1000.;
1561          orbitalinfo->theta = -1000.;            orbitalinfo->phi = -1000.;
1562        };            orbitalinfo->theta = -1000.;
1563              orbitalinfo->TimeGap = -1000.;
1564              TMatrixD Iij(3,3);
1565              Iij(0,0)=0; Iij(0,1)=0; Iij(0,2)=0;
1566              Iij(1,0)=0; Iij(1,1)=0; Iij(1,2)=0;
1567              Iij(2,0)=0; Iij(2,1)=0; Iij(2,2)=0;
1568              Iij.Zero();
1569              orbitalinfo->Iij.ResizeTo(Iij);
1570              orbitalinfo->Iij = Iij;
1571              //orbitalinfo->qkind = -1000;
1572            
1573              //  if ( debug ){
1574              //    Int_t lopu;
1575              //         cin >> lopu;
1576              //  }
1577              if ( debug ) printf(" grfuffi6 \n");
1578            }
1579            //
1580            if ( debug ) printf(" filling \n");
1581            // #########################################################################################################################  
1582            //
1583            // fill orbital positions
1584            //        
1585            // Build coordinates in the right range.  We want to convert,
1586            // longitude from (0, 2*pi) to (-180deg, 180deg).  Altitude is
1587            // in meters.
1588            lon = (coo.m_Lon > M_PI) ? rad2deg(coo.m_Lon - 2*M_PI) : rad2deg(coo.m_Lon);
1589            lat = rad2deg(coo.m_Lat);
1590            alt = coo.m_Alt;
1591    
1592            cOrbit orbits2(*gltle->GetTle());
1593            orbits2.getPosition((double) (atime - gltle->GetFromTime())/60., &eCi);
1594            //      Float_t x=eCi.getPos().m_x;
1595            //      Float_t y=eCi.getPos().m_y;
1596            //      Float_t z=eCi.getPos().m_z;
1597            
1598            TVector3 V(eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z);
1599            TVector3 Pos(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z);
1600            
1601            Float_t dlon=Pos.Phi()*TMath::RadToDeg()-lon;
1602            
1603            Pos.RotateZ(-dlon*TMath::DegToRad());
1604            V.RotateZ(-dlon*TMath::DegToRad());
1605            Float_t diro;
1606            if(V.Z()>0) diro=1; else diro=-1;
1607            
1608            // 10REDNEW
1609            Int_t errq=0;
1610            Int_t azim=0;
1611            Int_t qual=0;
1612            Int_t MU=0;
1613            for(UInt_t mu = 0;mu<RTtime2.size()-1;mu++){
1614              if(atime<RTstart[mu+1] && atime>=RTstart[mu]){
1615                errq=RTerrq[mu];
1616                azim=RTazim[mu];
1617                qual=RTqual[mu];
1618                MU=mu;
1619                break;
1620              }
1621            }
1622            orbitalinfo->errq = errq;
1623            orbitalinfo->azim = azim;
1624            orbitalinfo->rtqual=qual;
1625            orbitalinfo->qkind = 0;
1626            
1627            if ( debug ) printf(" coord done \n");
1628            if( lon<180 && lon>-180 && lat<90 && lat>-90 && alt>0 ){  
1629              orbitalinfo->lon = lon;
1630              orbitalinfo->lat = lat;
1631              orbitalinfo->alt = alt;
1632              orbitalinfo->V = V;
1633    
1634              //  GMtype_CoordGeodetic  location;
1635              location.lambda = lon;
1636              location.phi = lat;
1637              location.HeightAboveEllipsoid = alt;
1638    
1639              GM_GeodeticToSpherical(Ellip, location, &CoordSpherical);
1640              GM_SphericalToCartesian(CoordSpherical,  &CoordCartesian);
1641              GM_EarthCartToDipoleCartCD(Pole, CoordCartesian, &DipoleCartesian);
1642              GM_CartesianToSpherical(DipoleCartesian, &DipoleSpherical);
1643              orbitalinfo->londip = DipoleSpherical.lambda;
1644              orbitalinfo->latdip = DipoleSpherical.phig;
1645    
1646              if(debug)cout<<"geodetic:\t"<<lon<<"\t"<<lat<<"\tgeomagnetic:\t"<<orbitalinfo->londip<<"\t"<<orbitalinfo->latdip<<endl;
1647    
1648              //
1649              // compute mag field components and L shell.
1650              //
1651              if ( debug ) printf(" call igrf feldg \n");
1652              feldg_(&lat, &lon, &alt, &bnorth, &beast, &bdown, &babs);
1653              if ( debug ) printf(" call igrf shellg \n");
1654              shellg_(&lat, &lon, &alt, &dimo, &xl, &icode, &bab1);
1655              if ( debug ) printf(" call igrf findb \n");
1656              findb0_(&stps, &bdel, &value, &bequ, &rr0);
1657              //
1658              if ( debug ) printf(" done igrf \n");
1659                orbitalinfo->Bnorth = bnorth;
1660                orbitalinfo->Beast = beast;
1661                orbitalinfo->Bdown = bdown;
1662                orbitalinfo->Babs = babs;
1663                orbitalinfo->M = dimo;
1664                orbitalinfo->BB0 = babs/bequ;
1665                orbitalinfo->L = xl;      
1666                // Set Stormer vertical cutoff using L shell.
1667                orbitalinfo->cutoffsvl = 14.295 / (xl*xl); //
1668                if(debug)cout << "L = " << xl << "\tM = " << dimo << "\tvertical cutoff:  "<< orbitalinfo->cutoffsvl << endl;
1669                        
1670                //           ---------- Forwarded message ----------
1671                //           Date: Wed, 09 May 2012 12:16:47 +0200
1672                //           From: Alessandro Bruno <alessandro.bruno@ba.infn.it>
1673                //           To: Mirko Boezio <mirko.boezio@ts.infn.it>
1674                //           Cc: Francesco S. Cafagna <Francesco.Cafagna@ba.infn.it>
1675                //           Subject: Störmer vertical cutoff
1676    
1677                //           Ciao Mirko,
1678                //           volevo segnalarti che il valore dello Störmer vertical cutoff nel Level2 è
1679                //           sovrastimato di circa il 4%.
1680                //           Dopo un'approfondita analisi con l'IGRF-05 abbiamo ricavano un valore pari
1681                //           a: 14.295 / L^2 anzichè 14.9 / L^2, valore obsoleto in quanto riferito agli
1682                //           anni '50.
1683                //        
1684                //           14.9/(xl*xl);
1685                orbitalinfo->igrf_icode = (Float_t)icode;
1686                //
1687              }  //check lon lat alt      
1688              //
1689              if ( debug ) printf(" pitch angle \n");
1690              //
1691              // pitch angles
1692              //
1693              if( orbitalinfo->TimeGap>=0){
1694                //
1695                if ( debug ) printf(" timegap %f \n",orbitalinfo->TimeGap);
1696                Float_t Bx = -orbitalinfo->Bdown;
1697                Float_t By = orbitalinfo->Beast;
1698                Float_t Bz = orbitalinfo->Bnorth;
1699    
1700              //  TMatrixD Qiji(3,3);
1701                TMatrixD Qij = PO->QuatoECI(orbitalinfo->q0,orbitalinfo->q1,orbitalinfo->q2,orbitalinfo->q3);
1702                TMatrixD Dij = PO->ECItoGEO(Qij,orbitalinfo->absTime,orbitalinfo->lat,orbitalinfo->lon);
1703    
1704                //10REDNEW
1705                // If initial orientation data have reason to be inaccurate
1706                Float_t tg = 0.00;
1707                Float_t tmptg;
1708                Bool_t tgpar=false;
1709                Bool_t tgpar0=false;
1710                if (orbitalinfo->TimeGap>10.0 || ((modf(orbitalinfo->TimeGap,&tmptg)*1000>10 || modf(orbitalinfo->TimeGap,&tmptg)*1000==0.0) && orbitalinfo->TimeGap>2.0)) tgpar=true;
1711                if (orbitalinfo->TimeGap>180.0) tgpar0=true;
1712                if(MU!=0){
1713                //  if(orbitalinfo->TimeGap>0 && errq==0 && azim==0){    // 10RED CHECK  (comparison between three metod of recovering orientation)
1714                  if((atime>=RTstart[MU] && atime<RTstart[MU+1] && RTbank1[MU]==0 && RTbank2[MU]==0 && (TMath::Abs(orbitalinfo->etha)>0.1 || tgpar0)) || ((RTbank1[MU]!=0 || RTbank2[MU]!=0) && atime>=RTstart[MU] && atime<RTstart[MU+1] && azim==0 && (errq!=0 || tgpar))){
1715                    //found in Rotation Table this data for this time interval
1716                    if(atime<RTtime1[0])
1717                      orbitalinfo->azim = 5;  //means that RotationTable no started yet
1718                    else{
1719                      // search for angle betwean velosity and direction to north in tangential to Earth surfase plane in satellite position
1720                      Double_t bank=RTstart[MU];
1721                      Double_t tlat=orbitalinfo->lat;
1722    
1723                      tg=modf(orbitalinfo->TimeGap,&tg)*1000;
1724    
1725                      if(atime>=RTpluto1[MU] && atime<=RTpluto2[MU]){
1726                        Double_t kar=(RTbank2[MU]-RTbank1[MU])/(RTtime2[MU]-RTtime1[MU]);
1727                        Double_t bak=RTbank1[MU]-kar*RTtime1[MU];
1728                        bank=kar*atime+bak;
1729                      }
1730                      if(atime>=RTstart[MU] && atime<RTpluto1[MU]){
1731                        Double_t s_dBdt2=(RTbpluto1[MU]-RTbank1[MU])/(Int_t)(RTpluto1[MU]-RTstart[MU]);
1732                        Double_t s_t2=((Double_t)RTpluto1[MU]+(Double_t)RTstart[MU])/2. - RTstart[MU];
1733                        Double_t s_t1=RTstart[MU]-RTstart[MU];
1734                        Double_t s_k=s_dBdt2/(s_t2-s_t1);
1735                        Double_t s_b=-s_k*s_t1;
1736                        Double_t s_t3=RTpluto1[MU]-RTstart[MU];
1737                        Double_t s_b3=RTbpluto1[MU];
1738                        Double_t s_c=s_b3-0.5*s_k*s_t3*s_t3 -s_b*s_t3;
1739                        bank=0.5*s_k*(atime-RTstart[MU])*(atime-RTstart[MU]) + s_b*(atime-RTstart[MU]) + s_c;
1740                      }
1741                      if(atime>RTpluto2[MU] && atime<=RTstart[MU+1]){
1742                        Double_t s_dBdt2=(RTbpluto2[MU] - RTbank2[MU])/(Int_t)(RTpluto2[MU]-RTstart[MU+1]);
1743                        Double_t s_t2=((Double_t)RTpluto2[MU]+(Double_t)RTstart[MU+1])/2. - RTstart[MU];
1744                        Double_t s_t1=RTstart[MU+1]-RTstart[MU];
1745                        Double_t s_k=s_dBdt2/(s_t2-s_t1);
1746                        Double_t s_b=-s_k*s_t1;
1747                        Double_t s_t3=RTpluto2[MU]-RTstart[MU];
1748                        Double_t s_b3=RTbpluto2[MU];
1749                        Double_t s_c=s_b3-0.5*s_k*s_t3*s_t3 -s_b*s_t3;
1750                        bank=0.5*s_k*(atime-RTstart[MU])*(atime-RTstart[MU]) + s_b*(atime-RTstart[MU]) + s_c;
1751                      }
1752                      if(TMath::Abs(orbitalinfo->etha-bank)>0.1){
1753                        orbitalinfo->etha=bank;
1754                        Double_t spitch = 0.00001;  // temprary not zero to avoid problem with tranzition from Euler angles to orientation matrix
1755    
1756                        //Estimations of pitch angle of satellite
1757                        if(TMath::Abs(bank)>0.7){
1758                          Float_t spitch1=TMath::DegToRad()*0.7*diro;//RTdir1[MU];
1759                          Float_t spitch2=TMath::DegToRad()*0.7*diro;//RTdir2[MU];
1760                          Float_t kva=(spitch2-spitch1)/(RTtime2[MU]-RTtime1[MU]);
1761                          Float_t bva=spitch1-kva*RTtime1[MU];
1762                          spitch=kva*atime+bva;
1763                        }
1764    
1765                        //Calculate Yaw angle accordingly with fit, see picture FitYaw.jpg
1766                        Double_t yaw=0.00001;  // temprary not zero to avoid problem with tranzition from Euler angles to orientation matrix
1767                        if(TMath::Abs(tlat)<70)
1768                          yaw = -3.7e-8*tlat*tlat*tlat*tlat + 1.4e-7*tlat*tlat*tlat - 0.0005*tlat*tlat - 0.00025*tlat + 3.6;
1769                        yaw = diro*yaw;  //because should be different sign for ascending and descending orbits!
1770                        orbitalinfo->phi=yaw;
1771    
1772                        if(TMath::Abs(bank)>0.5 && TMath::Abs(yaw-orbitalinfo->phi)<3.0) yaw=orbitalinfo->phi;
1773    
1774                        //Qiji = PO->EulertoEci(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,bank,yaw,spitch);    // 10RED CHECK
1775                        Qij = PO->EulertoEci(eCi.getPos().m_x,eCi.getPos().m_y,eCi.getPos().m_z,eCi.getVel().m_x,eCi.getVel().m_y,eCi.getVel().m_z,bank,yaw,spitch);    // STANDARD
1776                        orbitalinfo->qkind = 1;
1777                      }
1778                      //Qij = PO->GEOtoECI(Dij,orbitalinfo->absTime,orbitalinfo->lat,orbitalinfo->lon); // to convert from Dij to Qij
1779                    } // end of if(atime<RTtime1[0]
1780                  } // end of (((orbitalinfo->TimeGap>60.0 && TMath...
1781                } // end of MU~=0
1782    
1783                TMatrixD qij = PO->ColPermutation(Qij);
1784                TMatrixD Fij = PO->ECItoGreenwich(Qij,orbitalinfo->absTime);
1785                TMatrixD Gij = PO->ColPermutation(Fij);
1786                Dij = PO->ECItoGEO(Qij,orbitalinfo->absTime,orbitalinfo->lat,orbitalinfo->lon);
1787                TMatrixD Iij = PO->ColPermutation(Dij);
1788    
1789                TVector3 SP = PO->GetSunPosition(orbitalinfo->absTime);
1790                // go to Pamela reference frame from Resurs reference frame
1791                Float_t tmpy = SP.Y();
1792                SP.SetY(SP.Z());
1793                SP.SetZ(-tmpy);
1794                TVector3 SunZenith;
1795                SunZenith.SetMagThetaPhi(1,23.439281*TMath::DegToRad(),TMath::Pi()/2.);
1796                TVector3 SunMag = -SP;
1797                SunMag.Rotate(-45*TMath::DegToRad(),SunZenith);
1798                tmpy=SunMag.Y();
1799                SunMag.SetY(SunMag.Z());
1800                SunMag.SetZ(-tmpy);
1801    
1802                orbitalinfo->Iij.ResizeTo(Iij);
1803                orbitalinfo->Iij = Iij;
1804    
1805                Bool_t saso=true;
1806                if (orbitalinfo->qkind==1) saso=true;
1807                if (orbitalinfo->qkind==0 && orbitalinfo->azim>0 && orbitalinfo->azim!=5 && tgpar) saso=false;
1808                if (orbitalinfo->qkind==0 && orbitalinfo->azim==5 && TMath::Abs(orbitalinfo->etha)>0.1 && tgpar) saso=false;
1809                if (orbitalinfo->qkind==0 && orbitalinfo->azim==5 && TMath::Abs(orbitalinfo->etha)<=0.1 && tgpar0) saso=false;
1810                if (saso) orbitalinfo->mode=orbitalinfo->rtqual; else orbitalinfo->mode=2;
1811    
1812      //
1813            //  A1 = Iij(0,2);
1814            //  A2 = Iij(1,2);
1815            //  A3 = Iij(2,2);
1816      //
1817      //  orbitalinfo->pamzenitangle = (Float_t)PO->GetPitchAngle(1,0,0,A1,A2,A3);            // Angle between zenit and Pamela's main axiz
1818      //  orbitalinfo->pamBangle = (Float_t)PO->GetPitchAngle(A1,A2,A3,Bx,By,Bz);      // Angle between Pamela's main axiz and B
1819      //
1820            if ( debug ) printf(" matrixes done  \n");
1821      if ( !standalone ){
1822              if ( debug ) printf(" !standalone \n");
1823        //
1824              // Standard tracking algorithm
1825              //
1826        Int_t nn = 0;
1827              if ( verbose ) printf(" standard tracking \n");
1828        for(Int_t nt=0; nt < tof->ntrk(); nt++){  
1829          //
1830          ToFTrkVar *ptt = tof->GetToFTrkVar(nt);
1831          if (debug) cout<<"tof->ntrk() = "<<tof->ntrk()<<"\tptt->trkseqno = "<<ptt->trkseqno<<"\ttrke->ntrk() = "<<trke->ntrk()<<endl;
1832          Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];
1833          Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];
1834          Double_t E11z = zin[0];
1835          Double_t E22x = ptt->xtr_tof[3];//tr->x[3];
1836          Double_t E22y = ptt->ytr_tof[3];//tr->y[3];
1837          Double_t E22z = zin[3];
1838          if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){
1839            TrkTrack *mytrack = trke->GetStoredTrack(ptt->trkseqno);
1840            Float_t rig=1/mytrack->GetDeflection();
1841            Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));
1842                  //
1843            Px = (E22x-E11x)/norm;
1844            Py = (E22y-E11y)/norm;
1845            Pz = (E22z-E11z)/norm;
1846            //
1847            t_orb->trkseqno = ptt->trkseqno;
1848            //
1849            TMatrixD Eij = PO->PamelatoGEO(Iij,Px,Py,Pz);
1850            t_orb->Eij.ResizeTo(Eij);  
1851            t_orb->Eij = Eij;  
1852            //
1853            TMatrixD Sij = PO->PamelatoGEO(Gij,Px,Py,Pz);
1854            t_orb->Sij.ResizeTo(Sij);
1855            t_orb->Sij = Sij;
1856            //      
1857            t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);
1858            //
1859                  // SunPosition in instrumental reference frame
1860            TMatrixD Kij = PO->PamelatoGEO(qij,Px,Py,Pz);
1861            TMatrixD Lij = PO->PamelatoGEO(qij,0,0,1);
1862            t_orb->sunangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),-SP.X(),-SP.Y(),-SP.Z());
1863            t_orb->sunmagangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),SunMag.X(),SunMag.Y(),SunMag.Z());
1864            //
1865            //
1866            Double_t omega = PO->GetPitchAngle(-Eij(0,0),-Eij(1,0),-Eij(2,0),1,0,0) * TMath::DegToRad();
1867            TVector3 Bxy(0,By,Bz);
1868            TVector3 Exy(0,-Eij(1,0),-Eij(2,0));
1869            Double_t dzeta=Bxy.Angle(Exy);
1870            if (-Eij(1,0) < 0) dzeta=2.0*TMath::Pi() - dzeta;
1871                  
1872                  if(debug) cout << "omega = "<<omega*TMath::RadToDeg()<<"\tdzeta = "<<dzeta*TMath::RadToDeg()<<endl;
1873    
1874                  // Formula from D.F. Smart *, M.A. Shea [2005]; A review of geomagnetic cutoff rigidities for earth-orbiting spacecraft
1875            if(rig>=0) t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1876            else       t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(TMath::Pi()+dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1877            if (debug) cout << "R = " << rig << "\tcutoff = " << t_orb->cutoff << endl;
1878    
1879            //
1880            if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;
1881            if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;
1882            if ( t_orb->sunangle != t_orb->sunangle ) t_orb->sunangle = -1000.;
1883            if ( t_orb->sunmagangle != t_orb->sunmagangle ) t_orb->sunmagangle = -1000.;
1884            //
1885            if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);
1886             //
1887             new(tor[nn]) OrbitalInfoTrkVar(*t_orb);
1888            nn++;
1889             //
1890             t_orb->Clear();
1891            //
1892          }
1893        //        //
1894        // #########################################################################################################################        } // end standard tracking algorithm
1895    
1896              //
1897              // Code for extended tracking algorithm:
1898              //
1899              if ( hasNucleiTrk ){
1900                Int_t ttentry = 0;
1901                if ( verbose ) printf(" hasNucleiTrk \n");
1902                for(Int_t nt=0; nt < tcNucleiTof->GetEntries() ; nt++){  
1903                  //
1904                  if ( verbose ) printf(" got1\n");
1905                  ToFTrkVar *ptt = (ToFTrkVar*)(tcNucleiTof->At(nt));
1906                  if (verbose) cout<<" tcNucleiTof->GetEntries() = "<<tcNucleiTof->GetEntries()<<"\tptt->trkseqno = "<<ptt->trkseqno<<endl;
1907                  Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];
1908                  Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];
1909                  Double_t E11z = zin[0];
1910                  Double_t E22x = ptt->xtr_tof[3];//tr->x[3];
1911                  Double_t E22y = ptt->ytr_tof[3];//tr->y[3];
1912                  Double_t E22z = zin[3];
1913                  if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){
1914                    TrkTrack *mytrack = (TrkTrack*)(tcNucleiTrk->At(ptt->trkseqno));
1915                    if ( verbose ) printf(" got tcNucleiTrk \n");
1916                    Float_t rig=1/mytrack->GetDeflection();
1917                    Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));
1918                    //
1919                    Px = (E22x-E11x)/norm;
1920                    Py = (E22y-E11y)/norm;
1921                    Pz = (E22z-E11z)/norm;
1922                    //
1923                    t_orb->trkseqno = ptt->trkseqno;
1924                    //
1925                    TMatrixD Eij = PO->PamelatoGEO(Iij,Px,Py,Pz);
1926                    t_orb->Eij.ResizeTo(Eij);  
1927                    t_orb->Eij = Eij;  
1928                    //
1929                    TMatrixD Sij = PO->PamelatoGEO(Gij,Px,Py,Pz);
1930                    t_orb->Sij.ResizeTo(Sij);
1931                    t_orb->Sij = Sij;
1932                    //      
1933                    t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);
1934                    //
1935                    // SunPosition in instrumental reference frame
1936                    TMatrixD Kij = PO->PamelatoGEO(qij,Px,Py,Pz);
1937                    TMatrixD Lij = PO->PamelatoGEO(qij,0,0,1);
1938                    t_orb->sunangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),-SP.X(),-SP.Y(),-SP.Z());
1939                    t_orb->sunmagangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),SunMag.X(),SunMag.Y(),SunMag.Z());
1940                    //
1941                    //
1942                    Double_t omega = PO->GetPitchAngle(-Eij(0,0),-Eij(1,0),-Eij(2,0),1,0,0) * TMath::DegToRad();
1943                    TVector3 Bxy(0,By,Bz);
1944                    TVector3 Exy(0,-Eij(1,0),-Eij(2,0));
1945                    Double_t dzeta=Bxy.Angle(Exy);
1946                    if (-Eij(1,0) < 0) dzeta=2.0*TMath::Pi() - dzeta;
1947                    
1948                    if(debug) cout << "omega = "<<omega*TMath::RadToDeg()<<"\tdzeta = "<<dzeta*TMath::RadToDeg()<<endl;
1949                    
1950                    // Formula from D.F. Smart *, M.A. Shea [2005]; A review of geomagnetic cutoff rigidities for earth-orbiting spacecraft
1951                    if(rig>=0) t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1952                    else       t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(TMath::Pi()+dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
1953                    if (debug) cout << "R = " << rig << "\tcutoff = " << t_orb->cutoff << endl;
1954                    
1955                    //
1956                    if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;
1957                    if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;
1958                    if ( t_orb->sunangle != t_orb->sunangle ) t_orb->sunangle = -1000.;
1959                    if ( t_orb->sunmagangle != t_orb->sunmagangle ) t_orb->sunmagangle = -1000.;
1960                    //
1961                    if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);
1962                    //
1963                    TClonesArray &tt1 = *torbNucleiTrk;
1964                    new(tt1[ttentry]) OrbitalInfoTrkVar(*t_orb);
1965                    ttentry++;
1966                    //
1967                    t_orb->Clear();
1968                    //
1969                  }
1970                  //
1971                }
1972              } // end standard tracking algorithm: nuclei
1973              if ( hasExtNucleiTrk ){
1974                Int_t ttentry = 0;
1975                if ( verbose ) printf(" hasExtNucleiTrk \n");
1976                for(Int_t nt=0; nt < tcExtNucleiTof->GetEntries() ; nt++){  
1977                  //
1978                  if ( verbose ) printf(" got2\n");
1979                  ToFTrkVar *ptt = (ToFTrkVar*)(tcExtNucleiTof->At(nt));
1980                  if (verbose) cout<<" tcExtNucleiTof->GetEntries() = "<<tcExtNucleiTof->GetEntries()<<"\tptt->trkseqno = "<<ptt->trkseqno<<endl;
1981                  Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];
1982                  Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];
1983                  Double_t E11z = zin[0];
1984                  Double_t E22x = ptt->xtr_tof[3];//tr->x[3];
1985                  Double_t E22y = ptt->ytr_tof[3];//tr->y[3];
1986                  Double_t E22z = zin[3];
1987                  if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){
1988                    ExtTrack *mytrack = (ExtTrack*)(tcExtNucleiTrk->At(ptt->trkseqno));
1989                    if ( verbose ) printf(" got tcExtNucleiTrk \n");
1990                    Float_t rig=1/mytrack->GetDeflection();
1991                    Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));
1992                    //
1993                    Px = (E22x-E11x)/norm;
1994                    Py = (E22y-E11y)/norm;
1995                    Pz = (E22z-E11z)/norm;
1996                    //
1997                    t_orb->trkseqno = ptt->trkseqno;
1998                    //
1999                    TMatrixD Eij = PO->PamelatoGEO(Iij,Px,Py,Pz);
2000                    t_orb->Eij.ResizeTo(Eij);  
2001                    t_orb->Eij = Eij;  
2002                    //
2003                    TMatrixD Sij = PO->PamelatoGEO(Gij,Px,Py,Pz);
2004                    t_orb->Sij.ResizeTo(Sij);
2005                    t_orb->Sij = Sij;
2006                    //      
2007                    t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);
2008                    //
2009                    // SunPosition in instrumental reference frame
2010                    TMatrixD Kij = PO->PamelatoGEO(qij,Px,Py,Pz);
2011                    TMatrixD Lij = PO->PamelatoGEO(qij,0,0,1);
2012                    t_orb->sunangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),-SP.X(),-SP.Y(),-SP.Z());
2013                    t_orb->sunmagangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),SunMag.X(),SunMag.Y(),SunMag.Z());
2014                    //
2015                    //
2016                    Double_t omega = PO->GetPitchAngle(-Eij(0,0),-Eij(1,0),-Eij(2,0),1,0,0) * TMath::DegToRad();
2017                    TVector3 Bxy(0,By,Bz);
2018                    TVector3 Exy(0,-Eij(1,0),-Eij(2,0));
2019                    Double_t dzeta=Bxy.Angle(Exy);
2020                    if (-Eij(1,0) < 0) dzeta=2.0*TMath::Pi() - dzeta;
2021                    
2022                    if(debug) cout << "omega = "<<omega*TMath::RadToDeg()<<"\tdzeta = "<<dzeta*TMath::RadToDeg()<<endl;
2023                    
2024                    // Formula from D.F. Smart *, M.A. Shea [2005]; A review of geomagnetic cutoff rigidities for earth-orbiting spacecraft
2025                    if(rig>=0) t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
2026                    else       t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(TMath::Pi()+dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
2027                    if (debug) cout << "R = " << rig << "\tcutoff = " << t_orb->cutoff << endl;
2028                    
2029                    //
2030                    if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;
2031                    if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;
2032                    if ( t_orb->sunangle != t_orb->sunangle ) t_orb->sunangle = -1000.;
2033                    if ( t_orb->sunmagangle != t_orb->sunmagangle ) t_orb->sunmagangle = -1000.;
2034                    //
2035                    if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);
2036                    //
2037                    TClonesArray &tt2 = *torbExtNucleiTrk;
2038                    new(tt2[ttentry]) OrbitalInfoTrkVar(*t_orb);
2039                    ttentry++;
2040                    //
2041                    t_orb->Clear();
2042                    //
2043                  }
2044                  //
2045                }
2046              } // end standard tracking algorithm: nuclei extended
2047             if ( hasExtTrk ){
2048                Int_t ttentry = 0;
2049                if ( verbose ) printf(" hasExtTrk \n");
2050                for(Int_t nt=0; nt < tcExtTof->GetEntries() ; nt++){  
2051                  //
2052                  if ( verbose ) printf(" got3\n");
2053                  ToFTrkVar *ptt = (ToFTrkVar*)(tcExtTof->At(nt));
2054                  if (verbose) cout<<" tcExtTof->GetEntries() = "<<tcExtTof->GetEntries()<<"\tptt->trkseqno = "<<ptt->trkseqno<<endl;
2055                  Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];
2056                  Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];
2057                  Double_t E11z = zin[0];
2058                  Double_t E22x = ptt->xtr_tof[3];//tr->x[3];
2059                  Double_t E22y = ptt->ytr_tof[3];//tr->y[3];
2060                  Double_t E22z = zin[3];
2061                  if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){
2062                    ExtTrack *mytrack = (ExtTrack*)(tcExtTrk->At(ptt->trkseqno));
2063                    if ( verbose ) printf(" got tcExtTrk \n");
2064                    Float_t rig=1/mytrack->GetDeflection();
2065                    Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));
2066                    //
2067                    Px = (E22x-E11x)/norm;
2068                    Py = (E22y-E11y)/norm;
2069                    Pz = (E22z-E11z)/norm;
2070                    //
2071                    t_orb->trkseqno = ptt->trkseqno;
2072                    //
2073                    TMatrixD Eij = PO->PamelatoGEO(Iij,Px,Py,Pz);
2074                    t_orb->Eij.ResizeTo(Eij);  
2075                    t_orb->Eij = Eij;  
2076                    //
2077                    TMatrixD Sij = PO->PamelatoGEO(Gij,Px,Py,Pz);
2078                    t_orb->Sij.ResizeTo(Sij);
2079                    t_orb->Sij = Sij;
2080                    //      
2081                    t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);
2082                    //
2083                    // SunPosition in instrumental reference frame
2084                    TMatrixD Kij = PO->PamelatoGEO(qij,Px,Py,Pz);
2085                    TMatrixD Lij = PO->PamelatoGEO(qij,0,0,1);
2086                    t_orb->sunangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),-SP.X(),-SP.Y(),-SP.Z());
2087                    t_orb->sunmagangle=(Float_t)PO->GetPitchAngle(Kij(0,0),Kij(1,0),Kij(2,0),SunMag.X(),SunMag.Y(),SunMag.Z());
2088                    //
2089                    //
2090                    Double_t omega = PO->GetPitchAngle(-Eij(0,0),-Eij(1,0),-Eij(2,0),1,0,0) * TMath::DegToRad();
2091                    TVector3 Bxy(0,By,Bz);
2092                    TVector3 Exy(0,-Eij(1,0),-Eij(2,0));
2093                    Double_t dzeta=Bxy.Angle(Exy);
2094                    if (-Eij(1,0) < 0) dzeta=2.0*TMath::Pi() - dzeta;
2095                    
2096                    if(debug) cout << "omega = "<<omega*TMath::RadToDeg()<<"\tdzeta = "<<dzeta*TMath::RadToDeg()<<endl;
2097                    
2098                    // Formula from D.F. Smart *, M.A. Shea [2005]; A review of geomagnetic cutoff rigidities for earth-orbiting spacecraft
2099                    if(rig>=0) t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
2100                    else       t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow(1+sqrt(1-sin(omega)*sin(TMath::Pi()+dzeta)*pow(cos(orbitalinfo->lat*TMath::DegToRad()),3)),2));
2101                    if (debug) cout << "R = " << rig << "\tcutoff = " << t_orb->cutoff << endl;
2102                    
2103                    //
2104                    if ( t_orb->pitch != t_orb->pitch ) t_orb->pitch = -1000.;
2105                    if ( t_orb->cutoff != t_orb->cutoff ) t_orb->cutoff = -1000.;
2106                    if ( t_orb->sunangle != t_orb->sunangle ) t_orb->sunangle = -1000.;
2107                    if ( t_orb->sunmagangle != t_orb->sunmagangle ) t_orb->sunmagangle = -1000.;
2108                    //
2109                    if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);
2110                    //
2111                    TClonesArray &tt3 = *torbExtTrk;
2112                    new(tt3[ttentry]) OrbitalInfoTrkVar(*t_orb);
2113                    ttentry++;
2114                    //
2115                    t_orb->Clear();
2116                    //
2117                  }
2118                  //
2119                }
2120              } // end standard tracking algorithm: extended
2121    
2122      } else {
2123        if ( debug ) printf(" mmm... mode %u standalone  \n",orbitalinfo->mode);
2124      }
2125      //
2126          } else { // HERE IT MISS ALL CODE FOR EXTENDED TRACKING!
2127      if ( !standalone ){
2128        //
2129              if ( verbose ) printf(" no orb info for tracks \n");
2130        Int_t nn = 0;
2131        for(Int_t nt=0; nt < tof->ntrk(); nt++){  
2132          //
2133          ToFTrkVar *ptt = tof->GetToFTrkVar(nt);
2134          if ( ptt->trkseqno != -1  ){
2135            //
2136            t_orb->trkseqno = ptt->trkseqno;
2137            //
2138            TMatrixD Iij(3,1);
2139            Iij(0,0)=0.; Iij(1,0)=0.; Iij(2,0)=1.;
2140            //Iij(1,0)=0; Iij(1,1)=0; Iij(1,2)=0;
2141            //Iij(2,0)=0; Iij(2,1)=0; Iij(2,2)=0;
2142            //Iij.Zero();
2143            t_orb->Eij.ResizeTo(Iij);
2144            t_orb->Sij.ResizeTo(Iij);
2145            t_orb->Eij = Iij;
2146            //
2147            t_orb->Sij = Iij;
2148            //      
2149            t_orb->pitch = -1000.;
2150            //
2151            t_orb->sunangle = -1000.;
2152            //
2153            t_orb->sunmagangle = -1000;
2154            //
2155            t_orb->cutoff = -1000.;
2156            //
2157             new(tor[nn]) OrbitalInfoTrkVar(*t_orb);
2158            nn++;
2159             //
2160             t_orb->Clear();
2161            //
2162          }
2163        //        //
2164        // fill orbital positions      }
2165        //                    //
2166        // Build coordinates in the right range.  We want to convert,            // Code for extended tracking algorithm:
2167        // longitude from (0, 2*pi) to (-180deg, 180deg).  Altitude is            //
2168        // in meters.            if ( hasNucleiTrk ){
2169        lon = (coo.m_Lon > M_PI) ? rad2deg(coo.m_Lon - 2*M_PI) : rad2deg(coo.m_Lon);              Int_t ttentry = 0;
2170        lat = rad2deg(coo.m_Lat);              if ( verbose ) printf(" hasNucleiTrk \n");
2171        alt = coo.m_Alt;              for(Int_t nt=0; nt < tcNucleiTof->GetEntries() ; nt++){  
2172        //                //  
2173        if( lon<180 && lon>-180 && lat<90 && lat>-90 && alt>0 ){                  ToFTrkVar *ptt = (ToFTrkVar*)(tcNucleiTof->At(nt));
2174          //                      if ( ptt->trkseqno != -1  ){
2175          orbitalinfo->lon = lon;                  //
2176          orbitalinfo->lat = lat;                  t_orb->trkseqno = ptt->trkseqno;
2177          orbitalinfo->alt = alt ;                  //
2178          //                  TMatrixD Iij(3,1);
2179          // compute mag field components and L shell.                  Iij(0,0)=0.; Iij(1,0)=0.; Iij(2,0)=1.;
2180          //                  //Iij(1,0)=0; Iij(1,1)=0; Iij(1,2)=0;
2181          feldg_(&lat, &lon, &alt, &bnorth, &beast, &bdown, &babs);                  //Iij(2,0)=0; Iij(2,1)=0; Iij(2,2)=0;
2182          shellg_(&lat, &lon, &alt, &dimo, &xl, &icode, &bab1);                  //Iij.Zero();
2183          findb0_(&stps, &bdel, &value, &bequ, &rr0);                  t_orb->Eij.ResizeTo(Iij);
2184          //                  t_orb->Sij.ResizeTo(Iij);
2185          orbitalinfo->Bnorth = bnorth;                  t_orb->Eij = Iij;  
2186          orbitalinfo->Beast = beast;                  //
2187          orbitalinfo->Bdown = bdown;                  t_orb->Sij = Iij;
2188          orbitalinfo->Babs = babs;                  //      
2189          orbitalinfo->BB0 = babs/bequ;                  t_orb->pitch = -1000.;
2190          orbitalinfo->L = xl;                        //
2191          // Set Stormer vertical cutoff using L shell.                  t_orb->sunangle = -1000.;
2192          orbitalinfo->cutoffsvl = 14.9/(xl*xl);                  //
2193          //                  t_orb->sunmagangle = -1000;
2194        };                        //
2195        //                  t_orb->cutoff = -1000.;
2196        // pitch angles                  //
2197        //                  TClonesArray &tz1 = *torbNucleiTrk;
2198        if ( orbitalinfo->mode != 10 && orbitalinfo->mode != 5 && orbitalinfo->mode !=7 && orbitalinfo->mode != 9 ){                  new(tz1[ttentry]) OrbitalInfoTrkVar(*t_orb);
2199          //                  ttentry++;
2200          Float_t Bx = -orbitalinfo->Bdown;                       //don't need for PamExp ExpOnly for all geography areas                  //
2201          Float_t By = orbitalinfo->Beast;                        //don't need for PamExp ExpOnly for all geography areas                  t_orb->Clear();
2202          Float_t Bz = orbitalinfo->Bnorth;                       //don't need for PamExp ExpOnly for all geography areas                  //
2203          //                }
2204          TMatrixD Fij = PO->ECItoGreenwich(PO->QuatoECI(orbitalinfo->q0,orbitalinfo->q1,orbitalinfo->q2,orbitalinfo->q3),orbitalinfo->absTime);                //
2205          TMatrixD Dij = PO->GreenwichtoGEO(orbitalinfo->lat,orbitalinfo->lon,Fij);              }
2206          TMatrixD Iij = PO->ColPermutation(Dij);            }
2207          //            if ( hasExtNucleiTrk ){
2208          orbitalinfo->Iij.ResizeTo(Iij);              Int_t ttentry = 0;
2209          orbitalinfo->Iij = Iij;              if ( verbose ) printf(" hasExtNucleiTrk \n");
2210          //              for(Int_t nt=0; nt < tcExtNucleiTof->GetEntries() ; nt++){  
2211          A1 = Iij(0,2);                //
2212          A2 = Iij(1,2);                if ( verbose ) printf(" got2\n");
2213          A3 = Iij(2,2);                ToFTrkVar *ptt = (ToFTrkVar*)(tcExtNucleiTof->At(nt));
2214          //                      if ( ptt->trkseqno != -1  ){
2215          //      orbitalinfo->pamzenitangle = (Float_t)PO->GetPitchAngle(1,0,0,A1,A2,A3);                        // Angle between zenit and Pamela's main axiz                  //
2216          //      orbitalinfo->pamBangle = (Float_t)PO->GetPitchAngle(A1,A2,A3,Bx,By,Bz);                 // Angle between Pamela's main axiz and B                  t_orb->trkseqno = ptt->trkseqno;
2217          //                  //
2218          if ( !standalone && tof->ntrk() > 0 ){                  TMatrixD Iij(3,1);
2219            //                  Iij(0,0)=0.; Iij(1,0)=0.; Iij(2,0)=1.;
2220            Int_t nn = 0;                  //Iij(1,0)=0; Iij(1,1)=0; Iij(1,2)=0;
2221            for(Int_t nt=0; nt < tof->ntrk(); nt++){                    //Iij(2,0)=0; Iij(2,1)=0; Iij(2,2)=0;
2222              //                  //Iij.Zero();
2223              ToFTrkVar *ptt = tof->GetToFTrkVar(nt);                  t_orb->Eij.ResizeTo(Iij);
2224              Double_t E11x = ptt->xtr_tof[0]; // tr->x[0];                  t_orb->Sij.ResizeTo(Iij);
2225              Double_t E11y = ptt->ytr_tof[0]; //tr->y[0];                  t_orb->Eij = Iij;  
2226              Double_t E11z = zin[0];                  //
2227              Double_t E22x = ptt->xtr_tof[3];//tr->x[3];                  t_orb->Sij = Iij;
2228              Double_t E22y = ptt->ytr_tof[3];//tr->y[3];                  //      
2229              Double_t E22z = zin[3];                  t_orb->pitch = -1000.;
2230              if ( (E11x < 100. && E11y < 100. && E22x < 100. && E22y < 100.) || ptt->trkseqno != -1  ){                  //
2231                Double_t norm = sqrt(pow(E22x-E11x,2)+pow(E22y-E11y,2)+pow(E22z-E11z,2));                  t_orb->sunangle = -1000.;
2232                Double_t MyAzim = TMath::RadToDeg()*atan(TMath::Abs(E22y-E11y)/TMath::Abs(E22x-E11x));                  //
2233                if(E22x-E11x>=0 && E22y-E11y <0) MyAzim =  360. - MyAzim;                  t_orb->sunmagangle = -1000;
2234                if(E22x-E11x>=0 && E22y-E11y >=0) MyAzim = MyAzim;                  //
2235                if(E22x-E11x<0 && E22y-E11y >0) MyAzim = 180. - MyAzim;                  t_orb->cutoff = -1000.;
2236                if(E22x-E11x<0 && E22y-E11y <0) MyAzim = 180. + MyAzim;                  //
2237                Px = (E22x-E11x)/norm;                  TClonesArray &tz2 = *torbExtNucleiTrk;
2238                Py = (E22y-E11y)/norm;                  new(tz2[ttentry]) OrbitalInfoTrkVar(*t_orb);
2239                Pz = (E22z-E11z)/norm;                  ttentry++;
2240                //                  //
2241                t_orb->trkseqno = ptt->trkseqno;                  t_orb->Clear();
2242                //                  //
2243                TMatrixD Eij = PO->PamelatoGEO(Iij,Px,Py,Pz);                }
2244                t_orb->Eij.ResizeTo(Eij);                //
2245                t_orb->Eij = Eij;              }
2246                //            }
2247                TMatrixD Sij = PO->PamelatoGEO(Fij,Px,Py,Pz);            if ( hasExtTrk ){
2248                t_orb->Sij.ResizeTo(Sij);              Int_t ttentry = 0;
2249                t_orb->Sij = Sij;              if ( verbose ) printf(" hasExtTrk \n");
2250                //                          for(Int_t nt=0; nt < tcExtTof->GetEntries() ; nt++){  
2251                t_orb->pitch = (Float_t)PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),Bx,By,Bz);                //
2252                //                if ( verbose ) printf(" got3\n");
2253                //                ToFTrkVar *ptt = (ToFTrkVar*)(tcExtTof->At(nt));
2254                Double_t omega = PO->GetPitchAngle(Eij(0,0),Eij(1,0),Eij(2,0),cos(orbitalinfo->lon+TMath::Pi()/2)-sin(orbitalinfo->lon+TMath::Pi()/2),cos(orbitalinfo->lon+TMath::Pi()/2)+sin(orbitalinfo->lon+TMath::Pi()/2),1);                if ( ptt->trkseqno != -1  ){
2255                //                  //
2256                t_orb->cutoff = 59.3/(pow(orbitalinfo->L,2)*pow((1+sqrt(1-pow(orbitalinfo->L,-3/2)*cos(omega))),2));                  t_orb->trkseqno = ptt->trkseqno;
2257                //                  //
2258                if ( debug ) printf(" orbitalinfo->cutoffsvl %f vitaly %f \n",orbitalinfo->cutoffsvl,t_orb->cutoff);                  TMatrixD Iij(3,1);
2259                //                  Iij(0,0)=0.; Iij(1,0)=0.; Iij(2,0)=1.;
2260                new(tor[nn]) OrbitalInfoTrkVar(*t_orb);                  //Iij(1,0)=0; Iij(1,1)=0; Iij(1,2)=0;
2261                nn++;                  //Iij(2,0)=0; Iij(2,1)=0; Iij(2,2)=0;
2262                //                  //Iij.Zero();
2263                t_orb->Clear();                  t_orb->Eij.ResizeTo(Iij);
2264                //                  t_orb->Sij.ResizeTo(Iij);
2265              };                  t_orb->Eij = Iij;  
2266              //                  //
2267            };                  t_orb->Sij = Iij;
2268          } else {                  //      
2269            if ( debug ) printf(" mmm... mode %u standalone %i ntrk %i \n",orbitalinfo->mode,standalone,tof->ntrk());                  t_orb->pitch = -1000.;
2270          };                  //
2271          //                  t_orb->sunangle = -1000.;
2272        } else {                  //
2273          if ( !standalone && tof->ntrk() > 0 ){                  t_orb->sunmagangle = -1000;
2274            //                  //
2275            Int_t nn = 0;                  t_orb->cutoff = -1000.;
2276            for(Int_t nt=0; nt < tof->ntrk(); nt++){                    //
2277              //                  TClonesArray &tz3 = *torbExtTrk;
2278              ToFTrkVar *ptt = tof->GetToFTrkVar(nt);                  new(tz3[ttentry]) OrbitalInfoTrkVar(*t_orb);
2279              if ( ptt->trkseqno != -1  ){                  ttentry++;
2280                //                  //
2281                t_orb->trkseqno = ptt->trkseqno;                  t_orb->Clear();
2282                //                  //
2283                t_orb->Eij = 0;                  }
2284                //                //
2285                t_orb->Sij = 0;              }
2286                //                        }
2287                t_orb->pitch = -1000.;          }
2288                //        }  // if( orbitalinfo->TimeGap>0){
               t_orb->cutoff = -1000.;  
               //  
               new(tor[nn]) OrbitalInfoTrkVar(*t_orb);  
               nn++;  
               //  
               t_orb->Clear();  
               //  
             };  
             //  
           };      
         };  
       };  
2289        //        //
2290        // Fill the class        // Fill the class
2291        //        //
2292        OrbitalInfotr->Fill();        OrbitalInfotr->Fill();
2293        //        //
2294          //      tor.Clear("C"); // memory leak?
2295          tor.Delete(); // memory leak?      
2296        delete t_orb;        delete t_orb;
2297        //        //
2298      }; // loop over the events in the run        //      printf(" q0 size %i q0 capacity %i \n",(int)q0.size(),(int)q0.capacity());
2299        } // loop over the events in the run
2300    
2301    
2302      //      //
2303      // Here you may want to clear some variables before processing another run        // Here you may want to clear some variables before processing another run  
2304      //      //
2305    
2306        //    OrbitalInfotr->FlushBaskets();
2307    
2308        if ( verbose ) printf(" Clear before new run \n");
2309      delete dbtime;      delete dbtime;
2310      if ( L_QQ_Q_l_upper ) delete L_QQ_Q_l_upper;  
2311        if ( mcmdrc ) mcmdrc->Clear();
2312        mcmdrc = 0;
2313        
2314        if ( verbose ) printf(" Clear before new run1 \n");
2315      if ( L_QQ_Q_l_lower ) delete L_QQ_Q_l_lower;      if ( L_QQ_Q_l_lower ) delete L_QQ_Q_l_lower;
2316        if ( verbose ) printf(" Clear before new run2 \n");
2317        if ( L_QQ_Q_l_upper ) delete L_QQ_Q_l_upper;
2318        if ( verbose ) printf(" Clear before new run3 \n");
2319      if ( RYPang_upper ) delete RYPang_upper;      if ( RYPang_upper ) delete RYPang_upper;
2320        if ( verbose ) printf(" Clear before new run4 \n");
2321      if ( RYPang_lower ) delete RYPang_lower;      if ( RYPang_lower ) delete RYPang_lower;
2322    }; // process all the runs  
2323      
2324        if ( l0tr ){
2325          if ( verbose ) printf(" delete l0tr\n");
2326          l0tr->Delete();
2327          l0tr = 0;
2328        }
2329        //    if ( l0head ){
2330        //      printf(" delete l0head\n");
2331        //  l0head->Reset();
2332        //  delete l0head;
2333        //  printf(" delete l0head done\n");
2334        //  l0head = 0;
2335        // }
2336        if (eh) {
2337          if ( verbose ) printf(" delete eh\n");
2338          delete eh;
2339          eh = 0;
2340        }
2341    
2342        if ( verbose ) printf(" close file \n");
2343        if ( l0File ) l0File->Close("R");
2344        if ( verbose ) printf(" End run \n");
2345    
2346        q0.clear();
2347        q1.clear();
2348        q2.clear();
2349        q3.clear();
2350        qtime.clear();
2351        qPitch.clear();
2352        qRoll.clear();
2353        qYaw.clear();
2354        qmode.clear();
2355    
2356        if (ch){
2357          if ( verbose ) printf(" delete ch\n");
2358          ch->Delete();
2359          ch = 0;
2360        }
2361      } // process all the runs    <===
2362      if ( debug ){
2363        printf("AFTER LOOP ON RUNs\n");
2364        gObjectTable->Print();
2365      }
2366      //  
2367    if (verbose) printf("\n Finished processing data \n");    if (verbose) printf("\n Finished processing data \n");
2368    //    //
2369   closeandexit:   closeandexit:
# Line 1117  int OrbitalInfoCore(UInt_t run, TFile *f Line 2373  int OrbitalInfoCore(UInt_t run, TFile *f
2373    if ( !reprocall && reproc && code >= 0 ){    if ( !reprocall && reproc && code >= 0 ){
2374      if ( totfileentries > noaftrun ){      if ( totfileentries > noaftrun ){
2375        if (verbose){        if (verbose){
2376          printf("\n Post-processing: copying events from the old tree after the processed run\n");      printf("\n Post-processing: copying events from the old tree after the processed run\n");  
2377          printf(" Copying %i events in the file which are after the end of the run %i \n",(int)(totfileentries-noaftrun),(int)run);    printf(" Copying %i events in the file which are after the end of the run %i \n",(int)(totfileentries-noaftrun),(int)run);
2378          printf(" Start copying at event number %i end copying at event number %i \n",(int)noaftrun,(int)totfileentries);    printf(" Start copying at event number %i end copying at event number %i \n",(int)noaftrun,(int)totfileentries);
2379        }        }
2380        for (UInt_t j = noaftrun; j < totfileentries; j++ ){        for (UInt_t j = noaftrun; j < totfileentries; j++ ){
2381          //    //
2382          // Get entry from old tree    // Get entry from old tree
2383          //    //
2384          OrbitalInfotrclone->GetEntry(j);              if ( OrbitalInfotrclone->GetEntry(j) <= 0 ) throw -36;    
2385          //    //
2386          // copy orbitalinfoclone to OrbitalInfo    // copy orbitalinfoclone to OrbitalInfo
2387          //    //
2388          orbitalinfo->Clear();          //  orbitalinfo->Clear();
2389          //    //
2390          memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));    memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));
2391          //    //
2392          // Fill entry in the new tree    // Fill entry in the new tree
2393          //    //
2394          OrbitalInfotr->Fill();    OrbitalInfotr->Fill();
2395        };        };
2396        if (verbose) printf(" Finished successful copying!\n");        if (verbose) printf(" Finished successful copying!\n");
2397      };      };
2398        //if ( OrbitalInfotrclone )    OrbitalInfotrclone->Clear();        
2399        //if ( OrbitalInfotrclone )    OrbitalInfotrclone->Delete();        
2400    };    };
2401    //    //
2402    // Close files, delete old tree(s), write and close level2 file    // Close files, delete old tree(s), write and close level2 file
2403    //    //
2404    
2405    if ( l0File ) l0File->Close();    if ( l0File ) l0File->Close();
   if ( tempfile ) tempfile->Close();              
2406    if ( myfold ) gSystem->Unlink(tempname.str().c_str());    if ( myfold ) gSystem->Unlink(tempname.str().c_str());
2407    //    //
   if ( runinfo ) runinfo->Close();      
2408    if ( OrbitalInfotr ) OrbitalInfotr->SetName("OrbitalInfo");        if ( OrbitalInfotr ) OrbitalInfotr->SetName("OrbitalInfo");    
   if ( tof ) tof->Delete();  
   if ( ttof ) ttof->Delete();  
2409    //    //
2410    if ( file ){    if ( file ){
2411      file->cd();      file->cd();
2412      file->Write();      if ( OrbitalInfotr ) OrbitalInfotr->Write("OrbitalInfo", TObject::kOverwrite); // 10 RED bug fixed
2413    };    };
2414    //    //
2415      if (verbose) printf("\n Exiting...\n");
2416    
2417    if ( myfold ) gSystem->Unlink(OrbitalInfofolder.str().c_str());    if ( myfold ) gSystem->Unlink(OrbitalInfofolder.str().c_str());
2418    //    //
2419    // the end    // the end
# Line 1165  int OrbitalInfoCore(UInt_t run, TFile *f Line 2422  int OrbitalInfoCore(UInt_t run, TFile *f
2422      dbc->Close();      dbc->Close();
2423      delete dbc;      delete dbc;
2424    };    };
   if (verbose) printf("\n Exiting...\n");  
   if(OrbitalInfotr)OrbitalInfotr->Delete();  
2425    //    //
2426      if (verbose) printf("\n Exiting...\n");
2427      if ( tempfile ) tempfile->Close();            
2428      
2429    if ( PO ) delete PO;    if ( PO ) delete PO;
2430    if ( orbitalinfo ) delete orbitalinfo;    if ( gltle ) delete gltle;
2431    if ( orbitalinfoclone ) delete orbitalinfoclone;    if ( glparam ) delete glparam;
2432      if ( glparam2 ) delete glparam2;
2433      if (verbose) printf("\n Exiting3...\n");
2434    if ( glroot ) delete glroot;    if ( glroot ) delete glroot;
2435      if (verbose) printf("\n Exiting4...\n");
2436      if ( runinfo ) runinfo->Close();    
2437    if ( runinfo ) delete runinfo;    if ( runinfo ) delete runinfo;
2438    
2439      if ( tcNucleiTrk ){
2440        tcNucleiTrk->Delete();
2441        delete tcNucleiTrk;
2442        tcNucleiTrk = NULL;
2443      }
2444      if ( tcExtNucleiTrk ){
2445        tcExtNucleiTrk->Delete();
2446        delete tcExtNucleiTrk;
2447        tcExtNucleiTrk = NULL;
2448      }
2449      if ( tcExtTrk ){
2450        tcExtTrk->Delete();
2451        delete tcExtTrk;
2452        tcExtTrk = NULL;
2453      }
2454    
2455      if ( tcNucleiTof ){
2456        tcNucleiTof->Delete();
2457        delete tcNucleiTof;
2458        tcNucleiTof = NULL;
2459      }
2460      if ( tcExtNucleiTof ){
2461        tcExtNucleiTof->Delete();
2462        delete tcExtNucleiTof;
2463        tcExtNucleiTof = NULL;
2464      }
2465      if ( tcExtTof ){
2466        tcExtTof->Delete();
2467        delete tcExtTof;
2468        tcExtTrk = NULL;
2469      }
2470    
2471    
2472      if ( tof ) delete tof;
2473      if ( trke ) delete trke;
2474    
2475      if ( debug ){  
2476      cout << "1   0x" << OrbitalInfotr << endl;
2477      cout << "2   0x" << OrbitalInfotrclone << endl;
2478      cout << "3   0x" << l0tr << endl;
2479      cout << "4   0x" << tempOrbitalInfo << endl;
2480      cout << "5   0x" << ttof << endl;
2481      }
2482      //
2483      if ( debug )  file->ls();
2484    //    //
2485      if ( debug ){
2486        printf("BEFORE EXITING\n");
2487        gObjectTable->Print();
2488      }
2489    if(code < 0)  throw code;    if(code < 0)  throw code;
2490    return(code);    return(code);
2491  }  }
# Line 1217  void CopyAng(InclinationInfo *A1, Inclin Line 2529  void CopyAng(InclinationInfo *A1, Inclin
2529  UInt_t holeq(Double_t lower,Double_t upper,Quaternions *Qlower, Quaternions *Qupper, UInt_t f){  UInt_t holeq(Double_t lower,Double_t upper,Quaternions *Qlower, Quaternions *Qupper, UInt_t f){
2530        
2531    UInt_t hole = 10;    UInt_t hole = 10;
2532    bool R10l = false;     // Sign of R10 mode in lower quaternions array    Bool_t R10l = false;     // Sign of R10 mode in lower quaternions array
2533    bool R10u = false;     // Sign of R10 mode in upper quaternions array    Bool_t R10u = false;     // Sign of R10 mode in upper quaternions array
2534    bool insm = false;     // Sign that we inside quaternions array    Bool_t insm = false;     // Sign that we inside quaternions array
2535    bool mxtml = false;    // Sign of mixt mode in lower quaternions array    //  Bool_t mxtml = false;    // Sign of mixt mode in lower quaternions array
2536    bool mxtmu = false;    // Sign of mixt mode in upper quaternions array    //  Bool_t mxtmu = false;    // Sign of mixt mode in upper quaternions array
2537    bool npasm = false;     // Sign of normall pass between R10 and non R10 or between non R10 and R10    Bool_t npasm = false;     // Sign of normall pass between R10 and non R10 or between non R10 and R10
2538    UInt_t NCQl = 6;       // Number of correct quaternions in lower array    UInt_t NCQl = 6;       // Number of correct quaternions in lower array
2539    UInt_t NCQu = 6;       // Number of correct quaternions in upper array    //  UInt_t NCQu = 6;       // Number of correct quaternions in upper array
2540    if (f>0){    if (f>0){
2541      insm = true;      insm = true;
2542      if(Qupper->time[f]-Qupper->time[f-1]==30) R10u = false;      if(Qupper->time[f]-Qupper->time[f-1]==30) R10u = false;
# Line 1236  UInt_t holeq(Double_t lower,Double_t upp Line 2548  UInt_t holeq(Double_t lower,Double_t upp
2548      if((Qlower->time[5]-Qlower->time[0]==150)&&(Qlower->time[1]-Qlower->time[0]==30)) R10l = false;      if((Qlower->time[5]-Qlower->time[0]==150)&&(Qlower->time[1]-Qlower->time[0]==30)) R10l = false;
2549      if((Qupper->time[5]-Qupper->time[0]==150)&&(Qupper->time[1]-Qupper->time[0]==30)) R10u = false;      if((Qupper->time[5]-Qupper->time[0]==150)&&(Qupper->time[1]-Qupper->time[0]==30)) R10u = false;
2550      if((Qlower->time[5]-Qlower->time[0]<2)&&(Qlower->time[1]-Qlower->time[0]==30)){      if((Qlower->time[5]-Qlower->time[0]<2)&&(Qlower->time[1]-Qlower->time[0]==30)){
2551        mxtml = true;        //      mxtml = true;
2552        for(UInt_t i = 1; i < 6; i++){        for(UInt_t i = 1; i < 6; i++){
2553          if(Qlower->time[i]-Qlower->time[0]==30*i) NCQl=i;    if(Qlower->time[i]-Qlower->time[0]==30*i) NCQl=i;
       }  
     }  
     if((Qupper->time[5]-Qupper->time[0]<2)&&(Qupper->time[1]-Qupper->time[0]==30)){  
       mxtmu = true;  
       for(UInt_t i = 1; i < 6; i++){  
         if(Qupper->time[i]-Qupper->time[0]==30*i) NCQu=i;  
2554        }        }
2555      }      }
2556        //    if((Qupper->time[5]-Qupper->time[0]<2)&&(Qupper->time[1]-Qupper->time[0]==30)){
2557          //      mxtmu = true;
2558          //      for(UInt_t i = 1; i < 6; i++){
2559          //  if(Qupper->time[i]-Qupper->time[0]==30*i) NCQu=i;
2560          //      }
2561        //    }
2562    }    }
2563        
2564    if(((upper-lower==1.5)||(upper-lower==3.)||(upper-lower==30.)||(upper-lower==31.5)||(upper-lower==33.)||(upper-lower==181.5)||(upper-lower==210.)||(upper-lower==211.5))&&!insm) npasm = true;    if(((upper-lower==1.5)||(upper-lower==3.)||(upper-lower==30.)||(upper-lower==31.5)||(upper-lower==33.)||(upper-lower==181.5)||(upper-lower==210.)||(upper-lower==211.5))&&!insm) npasm = true;
# Line 1265  UInt_t holeq(Double_t lower,Double_t upp Line 2577  UInt_t holeq(Double_t lower,Double_t upp
2577    return hole;    return hole;
2578  }  }
2579    
2580    void inclresize(vector<Double_t>& t,vector<Float_t>& q0,vector<Float_t>& q1,vector<Float_t>& q2,vector<Float_t>& q3,vector<Int_t>& mode,vector<Float_t>& Roll,vector<Float_t>& Pitch,vector<Float_t>& Yaw){
2581      Int_t sizee = t.size()+1;
2582      t.resize(sizee);
2583      q0.resize(sizee);
2584      q1.resize(sizee);
2585      q2.resize(sizee);
2586      q3.resize(sizee);
2587      mode.resize(sizee);
2588      Roll.resize(sizee);
2589      Pitch.resize(sizee);
2590      Yaw.resize(sizee);
2591    }
2592    
2593    // geomagnetic calculation staff
2594    
2595    void GM_ScanIGRF(TSQLServer *dbc, GMtype_Data *G0, GMtype_Data *G1, GMtype_Data *H1)
2596    {
2597      GL_PARAM *glp = new GL_PARAM();
2598      Int_t parerror=glp->Query_GL_PARAM(1,304,dbc); // parameters stored in DB in GL_PRAM table  
2599      if ( parerror<0 ) {
2600        throw -902;
2601      }
2602      /*This function scans inputs G0, G1, and H1 of the IGRF table into 3 data arrays*/
2603      //  TString SATH="/data03/Malakhov/pam9Malakhov/installed10/calib/orb-param/";
2604      int i;
2605      double temp;
2606      char buffer[200];
2607      FILE *IGRF;
2608      IGRF = fopen((glp->PATH+glp->NAME).Data(), "r");
2609            //  IGRF = fopen(PATH+"IGRF.tab", "r");
2610      G0->size = 25;
2611      G1->size = 25;
2612      H1->size = 25;
2613      for( i = 0; i < 4; i++)
2614      {
2615        fgets(buffer, 200, IGRF);
2616      }
2617      fscanf(IGRF, "g 1 0 %lf ", &G0->element[0]);
2618      for(i = 1; i <= 22; i++)
2619      {
2620        fscanf(IGRF ,"%lf ", &G0->element[i]);
2621      }
2622      fscanf(IGRF ,"%lf\n", &temp);
2623      G0->element[23] = temp * 5 + G0->element[22];
2624      G0->element[24] = G0->element[23] + 5 * temp;
2625      fscanf(IGRF, "g 1 1 %lf ", &G1->element[0]);
2626      for(i = 1; i <= 22; i++)
2627      {
2628        fscanf( IGRF, "%lf ", &G1->element[i]);
2629      }
2630      fscanf(IGRF, "%lf\n", &temp);
2631      G1->element[23] = temp * 5 + G1->element[22];
2632      G1->element[24] = temp * 5 + G1->element[23];
2633      fscanf(IGRF, "h 1 1 %lf ", &H1->element[0]);
2634      for(i = 1; i <= 22; i++)
2635      {
2636        fscanf( IGRF, "%lf ", &H1->element[i]);
2637      }
2638      fscanf(IGRF, "%lf\n", &temp);
2639      H1->element[23] = temp * 5 + H1->element[22];
2640      H1->element[24] = temp * 5 + H1->element[23];
2641      if ( glp ) delete glp;
2642      /*
2643      printf("############################## SCAN IGRF ######################################\n");
2644      printf("       G0      G1     H1\n");
2645      printf(" size  %10i %10i %10i \n",G0->size,G1->size,H1->size);
2646      for ( i = 0; i < 30; i++){
2647        printf("%5i  %10.2f %10.2f %10.2f \n",i,G0->element[i],G1->element[i],H1->element[i]);
2648      }  
2649      printf("###############################################################################\n");
2650      */
2651    } /*GM_ScanIGRF*/
2652    
2653    
2654    
2655    
2656    void GM_SetIGRF(Int_t isSecular, TString ifile1, TString ifile2, GMtype_Data *G0, GMtype_Data *G1, GMtype_Data *H1)
2657    {
2658      /*This function scans inputs G0, G1, and H1 of the IGRF table into 3 data arrays*/
2659      int i;
2660      double temp,temp2;
2661      int it1,it2;
2662      char buffer[200];
2663      FILE *IGRF;
2664      G0->size = 2;
2665      G1->size = 2;
2666      H1->size = 2;
2667    
2668      for( i = 0; i < 30; i++){
2669        G0->element[i] = 0.;
2670        G1->element[i] = 0.;
2671        H1->element[i] = 0.;
2672      }
2673    
2674      IGRF = fopen(ifile1.Data(), "r");
2675      for( i = 0; i < 2; i++){
2676        fgets(buffer, 200, IGRF);
2677      }
2678      fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2, &G0->element[0],&temp);
2679      fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2, &G1->element[0],&H1->element[0]);
2680      fclose(IGRF);
2681    
2682      IGRF = fopen(ifile2.Data(), "r");
2683      for( i = 0; i < 2; i++){
2684        fgets(buffer, 200, IGRF);
2685      }
2686      if ( isSecular ){
2687        fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2,&temp,&temp2);
2688        G0->element[1] = temp * 5. + G0->element[0];
2689        fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2,&temp,&temp2);
2690        G1->element[1] = temp * 5. + G1->element[0];
2691        H1->element[1] = temp2 * 5. + H1->element[0];
2692      } else {
2693        fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2, &G0->element[1],&temp);
2694        fscanf(IGRF, "%3i%3i%12lf%11lf",&it1,&it2, &G1->element[1],&H1->element[1]);
2695      }
2696      fclose(IGRF);
2697      /*
2698      printf("############################## SCAN IGRF ######################################\n");
2699      printf("       G0      G1     H1\n");
2700      printf(" size  %10i %10i %10i \n",G0->size,G1->size,H1->size);
2701      for ( i = 0; i < 30; i++){
2702        printf("%5i  %10.2f %10.2f %10.2f \n",i,G0->element[i],G1->element[i],H1->element[i]);
2703      }  
2704      printf("###############################################################################\n");
2705      */
2706    } /*GM_ScanIGRF*/
2707    
2708    void GM_SetEllipsoid(GMtype_Ellipsoid *Ellip)
2709    {
2710      /*This function sets the WGS84 reference ellipsoid to its default values*/
2711      Ellip->a  =      6378.137; /*semi-major axis of the ellipsoid in */
2712      Ellip->b  =      6356.7523142;/*semi-minor axis of the ellipsoid in */
2713      Ellip->fla  =      1/298.257223563;/* flattening */
2714      Ellip->eps  =      sqrt(1- ( Ellip->b *  Ellip->b) / (Ellip->a * Ellip->a ));  /*first eccentricity */
2715      Ellip->epssq  =      (Ellip->eps * Ellip->eps);   /*first eccentricity squared */
2716      Ellip->re  =      6371.2;/* Earth's radius */
2717    } /*GM_SetEllipsoid*/
2718    
2719    
2720    void GM_EarthCartToDipoleCartCD(GMtype_Pole Pole, GMtype_CoordCartesian EarthCoord, GMtype_CoordCartesian *DipoleCoords)
2721    {
2722      /*This function converts from Earth centered cartesian coordinates to dipole centered cartesian coordinates*/
2723      double X, Y, Z, CosPhi, SinPhi, CosLambda, SinLambda;
2724      CosPhi = cos(TMath::DegToRad()*Pole.phi);
2725      SinPhi = sin(TMath::DegToRad()*Pole.phi);
2726      CosLambda = cos(TMath::DegToRad()*Pole.lambda);
2727      SinLambda = sin(TMath::DegToRad()*Pole.lambda);
2728      X = EarthCoord.x;
2729      Y = EarthCoord.y;
2730      Z = EarthCoord.z;
2731      
2732      /*These equations are taken from a document by Wallace H. Campbell*/
2733      DipoleCoords->x = X * CosPhi * CosLambda + Y * CosPhi * SinLambda - Z * SinPhi;
2734      DipoleCoords->y = -X * SinLambda + Y * CosLambda;
2735      DipoleCoords->z = X * SinPhi * CosLambda + Y * SinPhi * SinLambda + Z * CosPhi;
2736    } /*GM_EarthCartToDipoleCartCD*/
2737    
2738    void GM_GeodeticToSpherical(GMtype_Ellipsoid Ellip, GMtype_CoordGeodetic CoordGeodetic, GMtype_CoordSpherical *CoordSpherical)
2739    {
2740      double CosLat, SinLat, rc, xp, zp; /*all local variables */
2741      /*
2742      ** Convert geodetic coordinates, (defined by the WGS-84
2743      ** reference ellipsoid), to Earth Centered Earth Fixed Cartesian
2744      ** coordinates, and then to spherical coordinates.
2745      */
2746    
2747      CosLat = cos(TMath::DegToRad()*CoordGeodetic.phi);
2748      SinLat = sin(TMath::DegToRad()*CoordGeodetic.phi);
2749    
2750      /* compute the local radius of curvature on the WGS-84 reference ellipsoid */
2751    
2752      rc = Ellip.a / sqrt(1.0 - Ellip.epssq * SinLat * SinLat);
2753    
2754      /* compute ECEF Cartesian coordinates of specified point (for longitude=0) */
2755    
2756      xp = (rc + CoordGeodetic.HeightAboveEllipsoid) * CosLat;
2757      zp = (rc*(1.0 - Ellip.epssq) + CoordGeodetic.HeightAboveEllipsoid) * SinLat;
2758    
2759      /* compute spherical radius and angle lambda and phi of specified point */
2760    
2761      CoordSpherical->r = sqrt(xp * xp + zp * zp);
2762      CoordSpherical->phig = TMath::RadToDeg()*asin(zp / CoordSpherical->r);     /* geocentric latitude */
2763      CoordSpherical->lambda = CoordGeodetic.lambda;                   /* longitude */
2764    } /*GM_GeodeticToSpherical*/
2765    
2766    void GM_PoleLocation(GMtype_Model Model, GMtype_Pole *Pole)
2767    {
2768      /*This function finds the location of the north magnetic pole in spherical coordinates.  The equations are
2769      **from Wallace H. Campbell's Introduction to Geomagnetic Fields*/
2770    
2771      Pole->phi = TMath::RadToDeg()*-atan(sqrt(Model.h1 * Model.h1 + Model.g1 * Model.g1)/Model.g0);
2772      Pole->lambda = TMath::RadToDeg()*atan(Model.h1/Model.g1);
2773    } /*GM_PoleLocation*/
2774    
2775    void GM_SphericalToCartesian(GMtype_CoordSpherical CoordSpherical, GMtype_CoordCartesian *CoordCartesian)
2776    {
2777      /*This function converts spherical coordinates into Cartesian coordinates*/
2778      double CosPhi = cos(TMath::DegToRad()*CoordSpherical.phig);
2779      double SinPhi = sin(TMath::DegToRad()*CoordSpherical.phig);
2780      double CosLambda = cos(TMath::DegToRad()*CoordSpherical.lambda);
2781      double SinLambda = sin(TMath::DegToRad()*CoordSpherical.lambda);
2782      
2783      CoordCartesian->x = CoordSpherical.r * CosPhi * CosLambda;
2784      CoordCartesian->y = CoordSpherical.r * CosPhi * SinLambda;
2785      CoordCartesian->z = CoordSpherical.r * SinPhi;
2786    } /*GM_SphericalToCartesian*/
2787    
2788    void GM_TimeAdjustCoefs(Float_t year, Float_t jyear, GMtype_Data g0d, GMtype_Data g1d, GMtype_Data h1d, GMtype_Model *Model)
2789    {
2790      /*This function calls GM_LinearInterpolation for the coefficients to estimate the value of the
2791      **coefficient for the given date*/
2792      int index;
2793      double x;
2794      index = (year - GM_STARTYEAR) / 5;
2795      x = (jyear - GM_STARTYEAR) / 5.;
2796      Model->g0 = GM_LinearInterpolation(index, index+1, g0d.element[index], g0d.element[index+1], x);
2797      Model->g1 = GM_LinearInterpolation(index, index+1, g1d.element[index], g1d.element[index+1], x);
2798      Model->h1 = GM_LinearInterpolation(index, index+1, h1d.element[index], h1d.element[index+1], x);
2799    } /*GM_TimeAdjustCoefs*/
2800    
2801    double GM_LinearInterpolation(double x1, double x2, double y1, double y2, double x)
2802    {
2803      /*This function takes a linear interpolation between two given points for x*/
2804      double weight, y;
2805      weight  = (x - x1) / (x2 - x1);
2806      y = y1 * (1. - weight) + y2 * weight;
2807            //        printf(" x1 %f x2 %f y1 %f y2 %f x %f ==> y %f \n",x1,x2,y1,y2,x,y);
2808      return y;
2809    }/*GM_LinearInterpolation*/
2810    
2811    void GM_CartesianToSpherical(GMtype_CoordCartesian CoordCartesian, GMtype_CoordSpherical *CoordSpherical)
2812    {
2813      /*This function converts a point from Cartesian coordinates into spherical coordinates*/
2814      double X, Y, Z;
2815      
2816      X = CoordCartesian.x;
2817      Y = CoordCartesian.y;
2818      Z = CoordCartesian.z;
2819    
2820      CoordSpherical->r = sqrt(X * X + Y * Y + Z * Z);
2821      CoordSpherical->phig = TMath::RadToDeg()*asin(Z / (CoordSpherical->r));
2822      CoordSpherical->lambda = TMath::RadToDeg()*atan2(Y, X);
2823    } /*GM_CartesianToSpherical*/

Legend:
Removed from v.1.35  
changed lines
  Added in v.1.93

  ViewVC Help
Powered by ViewVC 1.1.23