/**
* PyhsEndRunToXML
* author  Nagni
* version 2.0 - 14 February 2006
*
* Description: Generate an XML file starting from a PAMELA unpacked file.
*
* Parameters:
* 	base - the path where to find the PAMELA unpacked root file.
*	outDirectory - the path where to put the output file.
*	xslPath - the path where to find an XSL format for the output.
*
* version 1.0 - 03 March 2005
* First implementation
*
* version 2.0 - 14 February 2006
* Modified for new Yoda unpacking structure (one single file)
*/
#include <endrun/PhysEndRunEvent.h>
#include <endrun/CaloEndRun.h>
#include <endrun/TBEndRun.h>
#include <PscuHeader.h>
#include <EventHeader.h>
#include <fstream>

#include <TFile.h>
#include <TObjString.h>
#include <TString.h>
#include <TTree.h>

void PhysEndRunToXML(TString base, TString outDirectory = "", TString xslPath = ""){
    
  Int_t    	tmpSize;
  ofstream 	outputFile;
  stringstream 	oss;
  
  pamela::PhysEndRunEvent  *pere = 0;
  pamela::CaloEndRun       cer;
  pamela::TBEndRun         ter;
    
  pamela::EventHeader 	*eh   	  = 0;
  pamela::PscuHeader	*ph	  = 0;
  TFile   	      	*rootFile = new TFile(base);
  
  if (rootFile->IsZombie()) printf("The %s file does not exist", base.Data());
  TString fileName = ((TObjString*)base.Tokenize('\/')->Last())->GetString();
  TString filePath = base;
  filePath.ReplaceAll(fileName, "");
  fileName.ReplaceAll(".root", "");

  oss.str("");
  if (outDirectory == "") {
  	oss << fileName.Data() << "PhysEndRun.xml";
  } else {
  	oss << outDirectory.Data() << fileName.Data() << "PhysEndRun.xml";
  }
  const char* xmlFilePath = oss.str().c_str();
  
  outputFile.open(xmlFilePath, ios::trunc);
  if (!outputFile.is_open()){
  	printf("Cannot open the file %s for the output", xmlFilePath);
	exit(0);
  }
    
  
    //Takes the tree of the header file
    TTree *tr = (TTree*)rootFile->Get("PhysEndRun");
    Long64_t nevents    = tr->GetEntries();
    tr->SetBranchAddress("PhysEndRun", &pere);
    tr->SetBranchAddress("Header", &eh);
    outputFile << "<?xml version='1.0' encoding='ISO-8859-1'?>\n";
    outputFile << "<!-- Prologo XML -->\n";
    outputFile << "<?xml-stylesheet type='text/xsl' href='" << xslPath.Data() << "'?>\n";
    outputFile << "<ROOT_SOURCE>\n";
     
    //<!-- Istruzione che indica il documento XSLT da associare -->    
    for (int i = 0; i < nevents; i++){
      tr->GetEntry(i);
      ph      = eh->GetPscuHeader();
      outputFile << "<PHYSER_EVENT>\n";
      outputFile << "\t<PACKET_OBT>" << ph->GetOrbitalTime() << "</PACKET_OBT>\n";
      outputFile << "\t<PACKET_NUM>" << ph->GetCounter() << "</PACKET_NUM>\n";
      outputFile << "\t<CALOENDRUN_RECORDS>\n";
      for (int j = 0; j < 4; j++){
        cer = pere->CALO_ENDRUN[j];
	outputFile << "\t\t<CALOENDRUN_RECORD>\n";
	outputFile << "\t\t\t<BOARD_ID_HK>"       << (int)cer.CALO_BOARD_ID_HK      << "</BOARD_ID_HK>\n";
	outputFile << "\t\t\t<BOARD_ST_HK>"       << (int)cer.CALO_BOARD_STATUS_HK  << "</BOARD_ST_HK>\n";
	outputFile << "\t\t\t<HK0>\n";
	for (int k = 0; k < 11; k++){
	  outputFile << "\t\t\t\t<HK0_ITEM>"      << (int)cer.CALO_HK0[k]           << "</HK0_ITEM>\n";
	}
	outputFile << "\t\t\t</HK0>\n";
	outputFile << "\t\t\t<HK1>\n";
	for (int k = 0; k < 11; k++){
	  outputFile << "\t\t\t\t<HK1_ITEM>"      << (int)cer.CALO_HK1[k]           << "</HK1_ITEM>\n";
	}
	outputFile << "\t\t\t</HK1>\n";
	outputFile << "\t\t\t<BOARD_ID_REG>"      << (int)cer.CALO_BOARD_ID_REG     << "</BOARD_ID_REG>\n";
	outputFile << "\t\t\t<BOARD_ST_REG>"      << (int)cer.CALO_BOARD_STATUS_REG << "</BOARD_ST_REG>\n";
	outputFile << "\t\t\t<CALO_REG>\n";
	for (int k = 0; k < 7; k++){
	  outputFile << "\t\t\t\t<CALO_REG_ITEM>" << (int)cer.CALO_REG[k]           << "</CALO_REG_ITEM>\n";
	}
	outputFile << "\t\t\t</CALO_REG>\n";
	outputFile << "\t\t</CALOENDRUN_RECORD>\n";
      }
      outputFile << "\t</CALOENDRUN_RECORDS>\n";

      outputFile << "\t<TBENDRUN>\n";
      ter = pere->TB_ENDRUN;
      outputFile << "\t\t<ALARM_MASK>"   << (int)ter.TB_ALARM_MASK   << "</ALARM_MASK>\n";
      outputFile << "\t\t<PMT_MASK_S3>"  << (int)ter.TB_PMT_MASK_S3  << "</PMT_MASK_S3>\n";
      outputFile << "\t\t<PMT_MASK_S2>"  << (int)ter.TB_PMT_MASK_S2  << "</PMT_MASK_S2>\n";
      outputFile << "\t\t<PMT_MASK_S12>" << (int)ter.TB_PMT_MASK_S12 << "</PMT_MASK_S12>\n";
      outputFile << "\t\t<PMT_MASK_S11>" << (int)ter.TB_PMT_MASK_S11 << "</PMT_MASK_S11>\n";
      outputFile << "\t\t<S4_MASK>"      << (int)ter.TB_S4_MASK      << "</S4_MASK>\n";
      outputFile << "\t\t<CALO_MASK>"    << (int)ter.TB_CALO_MASK    << "</CALO_MASK>\n";
      outputFile << "\t\t<BUSY_MASK>"    << (int)ter.TB_BUSY_MASK    << "</BUSY_MASK>\n";
      outputFile << "\t\t<CALIB_FLAG>"   << (int)ter.TB_CALIB_FLAG   << "</CALIB_FLAG>\n";
      outputFile << "\t\t<S4_TRIG>"      << (int)ter.TB_S4_TRIG      << "</S4_TRIG>\n";
      outputFile << "\t\t<CALO_TRIG>"    << (int)ter.TB_CALO_TRIG    << "</CALO_TRIG>\n";
      outputFile << "\t\t<TOF_TRIG>"     << (int)ter.TB_TOF_TRIG     << "</TOF_TRIG>\n";
      outputFile << "\t</TBENDRUN>\n";
            
      outputFile << "</PHYSER_EVENT>\n";	
    }
    outputFile << "</ROOT_SOURCE>\n";
    outputFile.close();
}

int main(int argc, char* argv[]){
    TString outDir     = "";
    TString xslPath    = "";
    
 if (argc < 2){
    printf("You have to insert at least the file to analyze \n");
    printf("Try '--help' for more information. \n");
    exit(1);
  }  

  if (!strcmp(argv[1], "--help")){
        printf( "Usage: PhysEndRunToXML FILE [OPTION] \n");
        printf( "\t --help                 Print this help and exit \n");
        printf( "\t -outDir[path]          Path where to put the output [default ~/tmp] \n");
        printf( "\t -xslPath[path]         Set the path to a XSL file for formatting [default  '']\n");
        exit(1);
  }

  for (int i = 2; i < argc; i++){
    if (!strcmp(argv[i], "-outDir")){
        if (++i >= argc){
            printf( "-outDir needs arguments. \n");
            printf( "Try '--help' for more information. \n");
            exit(1);
        } else {
            outDir = argv[i];
            continue;
        }
    }

    if (!strcmp(argv[i], "-xslPath")) 
    	if (++i >= argc){
            printf( "-xslPath needs arguments. \n");
            printf( "Try '--help' for more information. \n");
            exit(1);
        } else {
        	xslPath = argv[i];
        	continue;
        }
    }
	PhysEndRunToXML(argv[1], outDir, xslPath);
}

