//
// C/C++ headers
//
#include <fstream>
#include <string.h>
#include <iostream>
#include <cstring>
#include <stdio.h>
//
// ROOT headers
//
#include <TTree.h>
#include <TClassEdit.h>
#include <TObject.h>
#include <TList.h>
#include <TArrayI.h>
#include <TSystem.h>
#include <TSystemDirectory.h>
#include <TString.h>
#include <TFile.h>
#include <TClass.h>
#include <TSQLServer.h>
#include <TSQLRow.h>
#include <TSQLResult.h>
//
// RunInfo header
//
#include <RunInfo.h>
#include <GLTables.h>
//
// YODA headers
//
#include <PamelaRun.h>
#include <PscuHeader.h>
#include <PscuEvent.h>
#include <EventHeader.h>
#include <mcmd/McmdEvent.h>
#include <mcmd/McmdRecord.h>
//
// This program headers
//
#include <OrbitalInfo.h>
#include <OrbitalInfoVerl2.h>
#include <OrbitalInfoCore.h>
#include <InclinationInfo.h>

using namespace std;

//
// CORE ROUTINE
//
//
int OrbitalInfoCore(UInt_t run, TFile *file, TSQLServer *dbc, Int_t OrbitalInfoargc, char *OrbitalInfoargv[]){
  //
  Int_t i = 0;
  //
  TString processFolder = Form("OrbitalInfoFolder_%u",run);
  //
  // Set these to true to have a very verbose output.
  //
  Bool_t debug = false;
  //
  Bool_t verbose = false;

  if ( OrbitalInfoargc > 0 ){
    i = 0;
    while ( i < OrbitalInfoargc ){
      if ( !strcmp(OrbitalInfoargv[i],"-processFolder") ) {
	if ( OrbitalInfoargc < i+1 ){
	  throw -3;
	};
	processFolder = (TString)OrbitalInfoargv[i+1];
	i++;
      };
      if ( (!strcmp(OrbitalInfoargv[i],"--debug")) || (!strcmp(OrbitalInfoargv[i],"-g")) ) {
	verbose = true;
	debug = true;
      };
      if ( (!strcmp(OrbitalInfoargv[i],"--verbose")) || (!strcmp(OrbitalInfoargv[i],"-v")) ) {
	verbose = true;
      };
      i++;
    };
  };
  //
  const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));
  //
  TTree *OrbitalInfotr = 0;
  UInt_t nevents = 0;
  UInt_t neventsm = 0;
  //
  // variables needed to reprocess data
  //
  Long64_t maxsize = 10000000000LL;  
  TTree::SetMaxTreeSize(maxsize);
  //
  TString OrbitalInfoversion;
  ItoRunInfo *runinfo = 0;
  TArrayI *runlist = 0;
  TTree *OrbitalInfotrclone = 0;
  Bool_t reproc = false;
  Bool_t reprocall = false;
  UInt_t nobefrun = 0;
  UInt_t noaftrun = 0;
  UInt_t numbofrun = 0;
  stringstream ftmpname;
  TString fname;
  UInt_t totfileentries = 0;
  UInt_t idRun = 0;
  //
  // My variables. Vitaly.
  //
  //  UInt_t iev = 0;
  //  UInt_t j3 = 0;
  UInt_t oi = 0;
  Int_t tmpSize = 0; 
  //
  // variables needed to handle error signals
  //
  Int_t code = 0;
  Int_t sgnl;
  //
  // OrbitalInfo  classes
  //
  OrbitalInfo *orbitalinfo = new OrbitalInfo();
  OrbitalInfo *orbitalinfoclone = new OrbitalInfo();
  //
  // define variables for opening and reading level0 file
  //
  TFile *l0File = 0;
  TTree *l0tr = 0;
  TTree *l0trm = 0;
  // EM: open also header branch
  TBranch *l0head = 0;
  pamela::EventHeader *eh = 0;
  pamela::PscuHeader *ph = 0;
  pamela::McmdEvent *mcmdev = 0;
  pamela::McmdRecord *mcmdrc = 0;
  // end EM
  
  //  pamela::RunHeaderEvent *reh = new pamela::RunHeaderEvent;
  //  pamela::EventHeader    *eH  = new pamela::EventHeader;
  
  //
  // Define other basic variables
  // 
  UInt_t procev = 0;
  stringstream file2;
  stringstream file3;
  stringstream qy;
  Int_t totevent = 0;
  UInt_t atime = 0;
  UInt_t re = 0;
  UInt_t ik = 0;

  // Position
  Float_t lon, lat, alt;

  //
  // IGRF stuff
  //
  float dimo = 0.0; // dipole moment (computed from dat files)
  float bnorth, beast, bdown, babs;
  float xl; // L value
  float icode; // code value for L accuracy (see fortran code)
  float bab1; // What's  the difference with babs?
  float stps = 0.005; // step size for field line tracing
  float bdel = 0.01; // required accuracy
  float bequ;  // equatorial b value (also called b_0)
  bool value = 0; // false if bequ is not the minimum b value
  float rr0; // equatorial radius normalized to earth radius

  //
  // Working filename
  //
  TString outputfile;
  stringstream name;
  name.str("");
  name << outDir << "/";
  //
  // temporary file and folder
  //
  TFile *tempfile = 0;
  TTree *tempOrbitalInfo = 0;
  stringstream tempname;
  stringstream OrbitalInfofolder;
  tempname.str("");
  tempname << outDir;
  tempname << "/" << processFolder.Data();
  OrbitalInfofolder.str("");
  OrbitalInfofolder << tempname.str().c_str();
  gSystem->MakeDirectory(OrbitalInfofolder.str().c_str());
  tempname << "/OrbitalInfotree_run";
  tempname << run << ".root";  
  //
  // DB classes
  //
  GL_ROOT *glroot = new GL_ROOT();
  GL_TIMESYNC *dbtime = 0;
  GL_TLE *gltle = new GL_TLE();
  //
  //Quaternions classes
  //
  Quaternions *L_QQ_Q_l_lower = new Quaternions();
  InclinationInfo *RYPang_lower = new InclinationInfo();
  Quaternions *L_QQ_Q_l_upper = new Quaternions();
  InclinationInfo *RYPang_upper = new InclinationInfo();
  
  cEci eCi;
  
  // Initialize fortran routines!!!
  Int_t ltp2 = 0;
  Int_t ltp3 = 0;
  Int_t uno = 1;
  char *niente = " ";
  GL_PARAM *glparam = new GL_PARAM();
  GL_PARAM *glparam2 = new GL_PARAM();
  Int_t parerror=glparam->Query_GL_PARAM(1,301,dbc); // parameters stored in DB in GL_PRAM table
  
  if ( parerror<0 ) {
    code = parerror;
    goto closeandexit;
  };
  ltp2 = (Int_t)(glparam->PATH+glparam->NAME).Length();
  if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
  //
  parerror=glparam2->Query_GL_PARAM(1,302,dbc); // parameters stored in DB in GL_PRAM table
  if ( parerror<0 ) {
    code = parerror;
    goto closeandexit;
  };
  ltp3 = (Int_t)(glparam2->PATH+glparam2->NAME).Length();
  if ( verbose ) printf(" Reading Earth's Magnetic Field parameter file: %s \n",(glparam2->PATH+glparam2->NAME).Data());
  //
  initize_((char *)niente,&uno,(char *)(glparam->PATH+glparam->NAME).Data(),&ltp2,(char *)(glparam2->PATH+glparam2->NAME).Data(),&ltp3); 
  //
  // End IGRF stuff//
  //

  //
  // Let's start!
  //
  // As a first thing we must check what we have to do: if run = 0 we must process all events in the file has been passed
  // if run != 0 we must process only that run but first we have to check if the tree MyDetector2 already exist in the file
  // if it exists we are reprocessing data and we must delete that entries, if not we must create it.
  // 
  if ( run == 0 )  reproc = true;
  //
  //
  // Output file is "outputfile"
  //
  if ( !file->IsOpen() ){
    //printf(" OrbitalInfo - ERROR: cannot open file for writing\n");
    throw -901;    
  };
  //
  // Retrieve GL_RUN variables from the level2 file
  //  
  OrbitalInfoversion = OrbitalInfoInfo(false); // we should decide how to handle versioning system
  //
  // create an interface to RunInfo called "runinfo"
  //
  runinfo = new ItoRunInfo(file);
  //
  // open "Run" tree in level2 file, if not existing return an error (sngl != 0)
  //
  sgnl = 0;
  sgnl = runinfo->Update(run, "ORB", OrbitalInfoversion);
  //sgnl = runinfo->Read(run);

  if ( sgnl ){
    //printf("OrbitalInfo - ERROR: RunInfo exited with non-zero status\n");
    code = sgnl;
    goto closeandexit;
  } else {
    sgnl = 0;
  };
  //
  // number of events in the file BEFORE the first event of our run
  //
  nobefrun = runinfo->GetFirstEntry();
  //
  // total number of events in the file 
  //
  totfileentries = runinfo->GetFileEntries();
  //
  // first file entry AFTER the last event of our run
  //
  noaftrun = runinfo->GetLastEntry() + 1;
  //
  // number of run to be processed
  //
  numbofrun = runinfo->GetNoRun();
  //
  // Try to access the OrbitalInfo tree in the file, if it exists we are reprocessing data if not we are processing a new run
  //
  OrbitalInfotrclone = (TTree*)file->Get("OrbitalInfo");
  //
  if ( !OrbitalInfotrclone ){
    //
    // tree does not exist, we are not reprocessing
    //
    reproc = false;
    if ( run == 0 ){
      if (verbose) printf(" OrbitalInfo - WARNING: you are reprocessing data but OrbitalInfo tree does not exist!\n");
    }
    if ( runinfo->IsReprocessing() && run != 0 ) {
      if (verbose) printf(" OrbitalInfo - WARNING: it seems you are not reprocessing data but OrbitalInfo\n versioning information already exists in RunInfo.\n");
    }
  } else {
    //
    // tree exists, we are reprocessing data. Are we reprocessing a single run or all the file?
    //
    OrbitalInfotrclone->SetAutoSave(900000000000000LL);
    reproc = true;
    //
    //
    if (verbose) printf("\n Preparing the pre-processing...\n");
    //
    if ( run == 0 ){
      //
      // we are reprocessing all the file
      // if we are reprocessing everything we don't need to copy any old event and we can just work with the new tree and delete the old one immediately
      //
      reprocall = true;
      //
      if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing all runs\n");
      //
    } else {
      //
      // we are reprocessing a single run, we must copy to the new tree the events in the file which preceed the first event of the run
      //
      reprocall = false;
      //
      if (verbose) printf("\n OrbitalInfo - WARNING: Reprocessing run number %u \n",run);
      //
      // copying old tree to a new file
      //
      tempfile = new TFile(tempname.str().c_str(),"RECREATE");
      tempOrbitalInfo = OrbitalInfotrclone->CloneTree(-1,"fast");
      tempOrbitalInfo->SetName("OrbitalInfo-old");
      tempfile->Write();
      tempfile->Close();  
    }
    //
    // Delete the old tree from old file and memory
    //
    OrbitalInfotrclone->Delete("all");
    //
    if (verbose) printf(" ...done!\n");
    //
  };
  //
  // create mydetector tree mydect
  // 
  file->cd();
  OrbitalInfotr = new TTree("OrbitalInfo-new","PAMELA OrbitalInfo data");
  OrbitalInfotr->SetAutoSave(900000000000000LL);
  OrbitalInfotr->Branch("OrbitalInfo","OrbitalInfo",&orbitalinfo);
  //
  if ( reproc && !reprocall ){
    //
    //  open new file and retrieve also tree informations
    //
    tempfile = new TFile(tempname.str().c_str(),"READ");
    OrbitalInfotrclone = (TTree*)tempfile->Get("OrbitalInfo-old");
    OrbitalInfotrclone->SetAutoSave(900000000000000LL);
    OrbitalInfotrclone->SetBranchAddress("OrbitalInfo",&orbitalinfoclone);
    //      
    if ( nobefrun > 0 ){
      if (verbose){
	printf("\n Pre-processing: copying events from the old tree before the processed run\n");   
	printf(" Copying %u events in the file which are before the beginning of the run %u \n",nobefrun,run);
	printf(" Start copying at event number 0, end copying at event number %u \n",nobefrun);
      }
      for (UInt_t j = 0; j < nobefrun; j++){
	//
	OrbitalInfotrclone->GetEntry(j);	  
	//
	// copy orbitalinfoclone to mydec
	//
	orbitalinfo->Clear();
	//
	memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));
	//
	// Fill entry in the new tree
	//
	OrbitalInfotr->Fill();
	//
      };
      if (verbose) printf(" Finished successful copying!\n");
    };          
  };
  //
  // Get the list of run to be processed, if only one run has to be processed the list will contain one entry only.
  //
  runlist = runinfo->GetRunList();
  //
  // Loop over the run to be processed
  //
  
  for (UInt_t irun=0; irun < numbofrun; irun++){
    //
    // retrieve the first run ID to be processed using the RunInfo list
    //
    
    idRun = runlist->At(irun);
    if (verbose){
      printf("\n\n\n ####################################################################### \n");
      printf("                    PROCESSING RUN NUMBER %i \n",(int)idRun);
      printf(" ####################################################################### \n\n\n");
    }
    //
    runinfo->ID_ROOT_L0 = 0;
    //
    // store in the runinfo class the GL_RUN variables for our run
    //
    sgnl = 0;
    sgnl = runinfo->GetRunInfo(idRun);
    if ( sgnl ){
      if ( debug ) printf("\n OrbitalInfo - ERROR: RunInfo exited with non-zero status\n");
      code = sgnl;
      goto closeandexit;
    } else {
      sgnl = 0;
    };
    //
    // now you can access that variables using the RunInfo class this way runinfo->ID_REG_RUN
    //
    if ( runinfo->ID_ROOT_L0 == 0 ){
      if ( debug ) printf("\n OrbitalInfo - ERROR: no run with ID_RUN = %u \n\n Exiting... \n\n",idRun);
      code = -5;
      goto closeandexit;    
    };
    //
    // prepare the timesync for the db
    //
    dbtime = new GL_TIMESYNC(runinfo->ID_ROOT_L0,"ID",dbc);
   
    //
    // Search in the DB the path and name of the LEVEL0 file to be processed.
    //
    glroot->Query_GL_ROOT(runinfo->ID_ROOT_L0,dbc);
    //
    ftmpname.str("");
    ftmpname << glroot->PATH.Data() << "/";
    ftmpname << glroot->NAME.Data();
    fname = ftmpname.str().c_str();
    ftmpname.str("");
    //
    // print out informations
    //
    totevent = runinfo->NEVENTS;
    //cout<<"totevents = "<<totevent<<"\n";
    if (verbose){
      printf("\n LEVEL0 data file: %s \n",fname.Data());
      printf(" RUN HEADER absolute time is:  %u \n",runinfo->RUNHEADER_TIME);
      printf(" RUN TRAILER absolute time is: %u \n",runinfo->RUNTRAILER_TIME);
      printf(" %i events to be processed for run %u: from %i to %i \n\n",totevent,idRun,runinfo->EV_FROM+1,runinfo->EV_FROM+totevent);
    }//
    // Open Level0 file
    l0File = new TFile(fname.Data());
    if ( !l0File ) {
      if ( debug ) printf(" OrbitalInfo - ERROR: problems opening Level0 file\n");
      code = -6;
      goto closeandexit;
    };
    l0tr = (TTree*)l0File->Get("Physics");
    if ( !l0tr ) {
      if ( debug ) printf(" OrbitalInfo - ERROR: no Physics tree in Level0 file\n");
      l0File->Close();
      code = -7;
      goto closeandexit;
    };
    // EM: open header branch as well
    l0head = l0tr->GetBranch("Header");
    if ( !l0head ) {
      if ( debug ) printf(" OrbitalInfo - ERROR: no Header branch in Level0 tree\n");
      l0File->Close();
      code = -8;
      goto closeandexit;    
    };
    l0tr->SetBranchAddress("Header", &eh);
    // end EM
    nevents = l0head->GetEntries();
    //
    if ( nevents < 1 ) {
      if ( debug ) printf(" OrbitalInfo - ERROR: Level0 file is empty\n\n");
      l0File->Close();
      code = -11;
      goto closeandexit;
    };
    // 
    if ( runinfo->EV_TO > nevents-1 ) {
      if ( debug ) printf(" OrbitalInfo - ERROR: too few entries in the registry tree\n");
      l0File->Close();
      code = -12;
      goto closeandexit;
    };
    //
//     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);
//
    ULong_t TimeSync = (ULong_t)dbtime->GetTimesync();
    ULong_t ObtSync = (ULong_t)(dbtime->GetObt0()/1000);
    ULong_t DeltaOBT = 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;
    //
    if (neventsm == 0){
      if ( debug ) printf("InclinationInfo - WARNING: No quaternions in this File");
      //      l0File->Close();
      code = 900;
      //      goto closeandexit;
    }
    //
    
    l0trm->SetBranchAddress("Mcmd", &mcmdev);
    //    l0trm->SetBranchAddress("Header", &eh);
    //
    //
    //
    UInt_t mctren = 0;    
    UInt_t mcreen = 0;	
    UInt_t numrec = 0;
    //
    Double_t upperqtime = 0;
    Double_t lowerqtime = 0;
    
    Double_t incli = 0;
    oi = 0;
    UInt_t ooi = 0;
    //
    // init quaternions sync
    //
    Bool_t isf = true;
    Int_t fgh = 0;
    //
    // run over all the events of the run
    //
    if (verbose) printf("\n Ready to start! \n\n Processed events: \n\n");
    //
    for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+runinfo->NEVENTS); re++){
    
      //
      if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);	
      if ( debug ) printf(" %i \n",procev);      
      //
      l0head->GetEntry(re);
      //
      // absolute time of this event
      //
      ph = eh->GetPscuHeader();
      atime = dbtime->DBabsTime(ph->GetOrbitalTime());
      //
      // paranoid check
      //
      if ( (atime > runinfo->RUNTRAILER_TIME) || (atime < runinfo->RUNHEADER_TIME)  ) {
	if (verbose) printf(" OrbitalInfo - WARNING: event at time outside the run time window, skipping it\n");
//	debug = true;
	continue;
      }
      //
      procev++;
      //
      // start processing
      //
      orbitalinfo->Clear();
      //
      // Fill OBT, pkt_num and absTime
      //      
      //      ph = eh->GetPscuHeader();
      orbitalinfo->pkt_num = ph->GetCounter();
      orbitalinfo->OBT = ph->GetOrbitalTime();
      orbitalinfo->absTime = atime;
      //
      // Propagate the orbit from the tle time to atime, using SGP(D)4.
      //
      cCoordGeo coo;
      float jyear=0;     
      //
      if(atime >= gltle->GetToTime()) {
	if ( !gltle->Query(atime, dbc) ){
	  //	  
	  // Compute the magnetic dipole moment.
	  //
	  UInt_t year, month, day, hour, min, sec;
	  //
	  TTimeStamp t = TTimeStamp(atime, kTRUE);
	  t.GetDate(kTRUE, 0, &year, &month, &day);
	  t.GetTime(kTRUE, 0, &hour, &min, &sec);
	  jyear = (float) year 
	    + (month*31.+ (float) day)/365. 
	    + (hour*3600.+min*60.+(float)sec)/(24*3600*365.);
	  //
	  feldcof_(&jyear, &dimo); // get dipole moment for year
	} else {
	  code = -56;
	  goto closeandexit;
	};
      }
      coo = getCoo(atime, gltle->GetFromTime(), gltle->GetTle());
      //
      cOrbit orbits(*gltle->GetTle());
      //
      if ( debug ) printf(" I am Here \n");
      //
      // synchronize with quaternions data
      //
      if ( isf && neventsm>0 ){
	if ( debug ) printf(" I am here \n");
	//
	// First event
	//
	isf = false;
	upperqtime = atime;
	lowerqtime = runinfo->RUNHEADER_TIME;
	for ( ik = 0; ik < neventsm; ik++){
	  l0trm->GetEntry(ik);
	  tmpSize = mcmdev->Records->GetEntries();
	  numrec = tmpSize;
	  for (Int_t j3 = 0;j3<tmpSize;j3++){
	    mcmdrc = (pamela::McmdRecord*)mcmdev->Records->At(j3);
	    if ((int)mcmdrc->ID1 == 226){
	      L_QQ_Q_l_upper->fill(mcmdrc->McmdData);
	      for (UInt_t ui = 0; ui < 6; ui++){
		if (ui>0){
		  if (L_QQ_Q_l_upper->time[ui]>L_QQ_Q_l_upper->time[0]){
		    if (dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000))<atime){
		      upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000));
		      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,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]);
		    }else {
		      lowerqtime = upperqtime;
		      upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[ui]*1000-DeltaOBT*1000));
		      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,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]);
		      mcreen = j3;
		      mctren = ik;
		      if(fgh==0){
			CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);
			CopyAng(RYPang_lower,RYPang_upper);
		      }
		      oi=ui;
		      goto closethisloop;
		    }
		    fgh++;
		    CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);
		    CopyAng(RYPang_lower,RYPang_upper);
		  }
		}else{
		  if (dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000))<atime){
		    upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
		    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,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]);
		  }
		  else {
		    lowerqtime = upperqtime;
		    upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
		    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,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]);
		    mcreen = j3;
		    mctren = ik;
		    if(fgh==0){
		      CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);
		      CopyAng(RYPang_lower,RYPang_upper);
		      lowerqtime = atime-1;
		    }
		    oi=ui;
		    goto closethisloop;
		    //_0 = true;
		  }
		  fgh++;
		  CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);
		  CopyAng(RYPang_lower,RYPang_upper);
		  //_0 = true;
		};
		//cin>>grib;
	      };
	    };
	  };
	};
      };
    closethisloop:
      //
      if ( debug ) printf(" I am There \n");
      //
      if (((atime>(UInt_t)upperqtime)||(atime<(UInt_t)lowerqtime)) && neventsm>0 ){
	if ( debug ) printf(" I am there \n");
	//
    	lowerqtime = upperqtime;
	Long64_t maxloop = 100000000LL;	
	Long64_t mn = 0;
	bool gh=false;
	ooi=oi;
	if ( verbose ) printf(" OrbitalInfoCore: sync with quaternions data upperqtime %u lowerqtime %u atime %u \n",(UInt_t)upperqtime,(UInt_t)lowerqtime,atime);
	while (!gh){	  
	  if ( mn > maxloop ){
	    if ( verbose ) printf(" OrbitalInfoCore: quaternions sync out of range! exiting\n");
	    gh = true;
	    neventsm = 0;
	  };
	  mn++;
	  if (oi<5) oi++;
	  else oi=0;
	  if (oi==0){
	    mcreen++;
	    if (mcreen == numrec){
	      mctren++;
	      mcreen = 0;
	      l0trm->GetEntry(mctren);
	      numrec = mcmdev->Records->GetEntries();
	    }
	    CopyQ(L_QQ_Q_l_lower,L_QQ_Q_l_upper);
	    CopyAng(RYPang_lower,RYPang_upper);
	    mcmdrc = (pamela::McmdRecord*)mcmdev->Records->At(mcreen);
	    if ((int)mcmdrc->ID1 == 226){
	      L_QQ_Q_l_upper->fill(mcmdrc->McmdData);
	      upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
	      if (upperqtime<lowerqtime){
		upperqtime=runinfo->RUNTRAILER_TIME;
		CopyQ(L_QQ_Q_l_upper,L_QQ_Q_l_lower);
		CopyAng(RYPang_upper,RYPang_lower);
	      }else{
		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,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]);
	      }
	      //	      re--;
	      gh=true;
	    }
	  }else{
	    if ((Int_t)L_QQ_Q_l_upper->time[oi]>(Int_t)L_QQ_Q_l_upper->time[0]){
	      upperqtime = dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));
	      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,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]);
	      orbits.getPosition((double) (lowerqtime - gltle->GetFromTime())/60., &eCi);
	      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]);
	      //	      re--;
	      gh=true;
	    };
	  };
	};
	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);
      };
      //
      if ( debug ) printf(" I am THIS \n");
      //
      // Fill in quaternions and angles
      //
      if ((atime<=(UInt_t)upperqtime)&&(atime>=(UInt_t)lowerqtime)&& neventsm>0){	
	if ( debug ) printf(" I am this \n");
	UInt_t tut = holeq(lowerqtime, upperqtime, L_QQ_Q_l_lower, L_QQ_Q_l_upper, oi);
	if (oi == 0){
	  if ((tut!=5)||(tut!=6)){
	    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)));
	    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));
	    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)));
	    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));
	    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)));
	    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));
	    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)));
	    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));
	
	    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)));
	    orbitalinfo->theta =  incli*atime+RYPang_upper->Tangazh-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
	    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)));
	    orbitalinfo->phi =  incli*atime+RYPang_upper->Ryskanie-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
	    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)));
	    orbitalinfo->etha =  incli*atime+RYPang_upper->Kren-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
	  }
	  if (tut==6){
	    if (fabs(RYPang_lower->Kren-RYPang_upper->Kren)<0.1){
	      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)));
	      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));
	      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)));
	      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));
	      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)));
	      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));
	      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)));
	      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));
	
	      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)));
	      orbitalinfo->theta =  incli*atime+RYPang_upper->Tangazh-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
	      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)));
	      orbitalinfo->phi =  incli*atime+RYPang_upper->Ryskanie-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
	      //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";
	      //cin>>grib;
	      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)));
	      orbitalinfo->etha =  incli*atime+RYPang_upper->Kren-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[0]*1000-DeltaOBT*1000));
	    }
	  }
	} else {
	  if((tut!=6)||(tut!=7)||(tut!=9)){
	    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)));
	    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));
	    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)));
	    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));
	    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)));
	    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));
	    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)));
	    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));
	
	    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)));
	    orbitalinfo->theta =  incli*atime+RYPang_upper->Tangazh-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));
	    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)));
	    orbitalinfo->phi =  incli*atime+RYPang_upper->Ryskanie-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));
	    //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";
	    //cin>>grib;
	    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)));
	    orbitalinfo->etha =  incli*atime+RYPang_upper->Kren-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));
	  }
	  if (tut==6){
	    if (fabs(RYPang_lower->Kren-RYPang_upper->Kren)<0.1){
	      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)));
	      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));
	      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)));
	      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));
	      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)));
	      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));
	      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)));
	      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));
	
	      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)));
	      orbitalinfo->theta =  incli*atime+RYPang_upper->Tangazh-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));
	      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)));
	      orbitalinfo->phi =  incli*atime+RYPang_upper->Ryskanie-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));
	      //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";
	      //cin>>grib;
	      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)));
	      orbitalinfo->etha =  incli*atime+RYPang_upper->Kren-incli*dbtime->DBabsTime((UInt_t)(L_QQ_Q_l_upper->time[oi]*1000-DeltaOBT*1000));
	    }
	  }		
	}
	//
	orbitalinfo->mode = holeq(lowerqtime, upperqtime, L_QQ_Q_l_lower, L_QQ_Q_l_upper, oi);
	//
      } else {
	if ( debug ) printf(" ops no incl! \n");
	orbitalinfo->mode = -1;
      };
   
      //
      // fill orbital positions
      //        
      // Build coordinates in the right range.  We want to convert,
      // longitude from (0, 2*pi) to (-180deg, 180deg).  Altitude is
      // in meters.
      lon = (coo.m_Lon > M_PI) ? rad2deg(coo.m_Lon - 2*M_PI) : rad2deg(coo.m_Lon);
      lat = rad2deg(coo.m_Lat);
      alt = coo.m_Alt;
      //
      if( lon<180 && lon>-180 && lat<90 && lat>-90 && alt>0 ){	
	//      
	orbitalinfo->lon = lon;
	orbitalinfo->lat = lat;
	orbitalinfo->alt = alt ;
	//
	// compute mag field components and L shell.
	//
	feldg_(&lat, &lon, &alt, &bnorth, &beast, &bdown, &babs);
	shellg_(&lat, &lon, &alt, &dimo, &xl, &icode, &bab1);
	findb0_(&stps, &bdel, &value, &bequ, &rr0);
	//
	orbitalinfo->Bnorth = bnorth;
	orbitalinfo->Beast = beast;
	orbitalinfo->Bdown = bdown;
	orbitalinfo->Babs = babs;
	orbitalinfo->BB0 = babs/bequ;
	orbitalinfo->L = xl;      
	// Set Stormer vertical cutoff using L shell.
	orbitalinfo->cutoff[0] = 14.9/(xl*xl);
	//
      };      
      //
      // Fill the class
      //
      OrbitalInfotr->Fill();
      //
    }; // loop over the events in the run
    //
    // Here you may want to clear some variables before processing another run  
    //
    delete dbtime;
    if ( L_QQ_Q_l_upper ) delete L_QQ_Q_l_upper;
    if ( L_QQ_Q_l_lower ) delete L_QQ_Q_l_lower;
    if ( RYPang_upper ) delete RYPang_upper;
    if ( RYPang_lower ) delete RYPang_lower;
  }; // process all the runs
  
  if (verbose) printf("\n Finished processing data \n");
  //
 closeandexit:
  //
  // we have finished processing the run(s). If we processed a single run now we must copy all the events after our run from the old tree to the new one and delete the old tree.
  //
  if ( !reprocall && reproc && code >= 0 ){
    if ( totfileentries > noaftrun ){
      if (verbose){
	printf("\n Post-processing: copying events from the old tree after the processed run\n");   
	printf(" Copying %i events in the file which are after the end of the run %i \n",(int)(totfileentries-noaftrun),(int)run);
	printf(" Start copying at event number %i end copying at event number %i \n",(int)noaftrun,(int)totfileentries);
      }
      for (UInt_t j = noaftrun; j < totfileentries; j++ ){
	//
	// Get entry from old tree
	//
	OrbitalInfotrclone->GetEntry(j);	  
	//
	// copy orbitalinfoclone to OrbitalInfo
	//
	orbitalinfo->Clear();
	//
	memcpy(&orbitalinfo,&orbitalinfoclone,sizeof(orbitalinfoclone));
	//
	// Fill entry in the new tree
	//
	OrbitalInfotr->Fill();
      };
      if (verbose) printf(" Finished successful copying!\n");
    };
  };
  //
  // Close files, delete old tree(s), write and close level2 file 
  //
  if ( l0File ) l0File->Close();
  if ( tempfile ) tempfile->Close();            
  gSystem->Unlink(tempname.str().c_str());
  //
  if ( runinfo ) runinfo->Close();    
  if ( OrbitalInfotr ) OrbitalInfotr->SetName("OrbitalInfo");    
  if ( file ){
    file->cd();
    file->Write();
  };
  //
  gSystem->Unlink(OrbitalInfofolder.str().c_str());
  //
  // the end
  //
  if (verbose) printf("\n Exiting...\n");
  if(OrbitalInfotr)OrbitalInfotr->Delete();
  //
  if ( orbitalinfo ) delete orbitalinfo;
  if ( orbitalinfoclone ) delete orbitalinfoclone;
  if ( glroot ) delete glroot;
  if ( runinfo ) delete runinfo; 
  //
  if(code < 0)  throw code;
  return(code);
}


//
// Returns the cCoordGeo structure holding the geographical
// coordinates for the event (see sgp4.h).
//
// atime is the abstime of the event in UTC unix time.
// tletime is the time of the tle in UTC unix time.
// tle is the previous and nearest tle (compared to atime).
cCoordGeo getCoo(UInt_t atime, UInt_t tletime, cTle *tle)
{
  cEci eci;
  cOrbit orbit(*tle);
  orbit.getPosition((double) (atime - tletime)/60., &eci);
  
  return eci.toGeo();
}

// function of copyng of quatrnions classes

void CopyQ(Quaternions *Q1, Quaternions *Q2){
  for(UInt_t i = 0; i < 6; i++){
    Q1->time[i]=Q2->time[i];
    for (UInt_t j = 0; j < 4; j++)Q1->quat[i][j]=Q2->quat[i][j];
  }
  return;
}

// functions of copyng InclinationInfo classes

void CopyAng(InclinationInfo *A1, InclinationInfo *A2){
  A1->Tangazh = A2->Tangazh;
  A1->Ryskanie = A2->Ryskanie;
  A1->Kren = A2->Kren;
  return;
}

UInt_t holeq(Double_t lower,Double_t upper,Quaternions *Qlower, Quaternions *Qupper, UInt_t f){
  
  UInt_t hole = 10;
  bool R10l = false;     // Sign of R10 mode in lower quaternions array
  bool R10u = false;     // Sign of R10 mode in upper quaternions array
  bool insm = false;     // Sign that we inside quaternions array
  bool mxtml = false;    // Sign of mixt mode in lower quaternions array
  bool mxtmu = false;    // Sign of mixt mode in upper quaternions array
  bool npasm = false;     // Sign of normall pass between R10 and non R10 or between non R10 and R10
  UInt_t NCQl = 6;       // Number of correct quaternions in lower array
  UInt_t NCQu = 6;       // Number of correct quaternions in upper array
  if (f>0){
    insm = true;
    if(Qupper->time[f]-Qupper->time[f-1]==30) R10u = false;
    if(Qupper->time[f]-Qupper->time[f-1]<1) R10u = true;
  }else{
    insm = false;
    if((Qlower->time[5]-Qlower->time[0]<2)&&(Qlower->time[1]-Qlower->time[0]<2)) R10l = true;
    if((Qupper->time[5]-Qupper->time[0]<2)&&(Qupper->time[1]-Qupper->time[0]<2)) R10u = true;
    if((Qlower->time[5]-Qlower->time[0]==150)&&(Qlower->time[1]-Qlower->time[0]==30)) R10l = false;
    if((Qupper->time[5]-Qupper->time[0]==150)&&(Qupper->time[1]-Qupper->time[0]==30)) R10u = false;
    if((Qlower->time[5]-Qlower->time[0]<2)&&(Qlower->time[1]-Qlower->time[0]==30)){
      mxtml = true;
      for(UInt_t i = 1; i < 6; 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;
      }
    }
  }
  
  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 (R10u&&insm) hole=0; // best event R10
  if ((upper-lower<=5)&&(!insm)&&R10l&&R10u) hole = 1; // when first of 6 quaternions in array is correct
  if (((!R10u)&&insm)||((!insm)&&(!R10u)&&(!R10l)&&((upper-lower==210+(6-NCQl)*30)||(upper-lower==30)))) hole = 2; //non R10
  if (npasm&&(!insm)&&((R10l&&!R10u)||(R10u&&!R10l))) hole = 3; //normall pass from R10 to non R10 or from non R10 to R10
  if ((!npasm)&&(upper-lower<=300)&&(!insm)&&((R10l&&!R10u)||(R10u&&!R10l))) hole = 4; // eliminable hole between R10 and non R10 or between non R10 and R10
  if ((upper-lower>=300)&&(!insm)&&((R10l&&!R10u)||(R10u&&!R10l))) hole = 5; //uneliminable hole between R10 and non R10 or between non R10 and R10
  if ((upper-lower>5)&&(upper-lower<=300)&&R10u&&R10l) hole = 6; // eliminable hole inside R10
  if ((upper-lower>300)&&R10u&&R10l) hole = 7; //uneliminable hole inside R10
  if ((upper-lower>210)&&(upper-lower<=1200)&&(!R10u)&&(!R10l)) hole = 8; //eliminable hole inside non R10
  if ((upper-lower>1200)&&!R10u&&!R10l) hole = 9; // uneliminable hole inside non R10
  return hole;
}

