/**
* ArrDumpToXML
* author  Nagni
* version 2.0 - 03 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 - 03 February 2006
* Modified for new Yoda unpacking structure (one single file)
*/
#include <arrDump/ArrDumpRecord.h>
#include <arrDump/ArrDumpEvent.h>
#include <PscuHeader.h>
#include <EventHeader.h>
#include <yodaUtility.h>
#include <fstream>

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


void ArrDumpToXML(TString base, TString outDirectory = "", TString xslPath = ""){

  Int_t    	tmpSize;
  ofstream 	outputFile;
  stringstream 	oss;
  
  pamela::ArrDumpEvent  *ade = 0;
  pamela::ArrDumpRecord *adr = 0;
  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() << "ArrDump.xml";
  } else {
  	oss << outDirectory.Data() << fileName.Data() << "ArrDump.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);
  }
  

    TTree *tr = (TTree*)rootFile->Get("ArrDump");
    Long64_t nevents    = tr->GetEntries();
    UInt_t k_data    = 0;
    tr->SetBranchAddress("ArrDump", &ade);
    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";
    for (int i = 0; i < nevents; i++){
      tr->GetEntry(i);
      tmpSize = ade->Records->GetEntries();
      ph      = eh->GetPscuHeader();
      outputFile << "<ARRDUMP_EVENT>\n";
      outputFile << "\t<PACKET_OBT>"     << ph->GetOrbitalTime()      << "</PACKET_OBT>\n";
      outputFile << "\t<PACKET_NUM>"     << ph->GetCounter()          << "</PACKET_NUM>\n";
      outputFile << "\t<COMPILATION_TS>" << ade->PARAMETER_STAMP << "</COMPILATION_TS>\n";
      outputFile << "\t<ARRDUMP_RECORDS>\n";
      for (int j = 0; j < tmpSize; j++){
	adr = (pamela::ArrDumpRecord*)ade->Records->At(j);
	outputFile << "\t\t<ARRDUMP_RECORD>\n";
	outputFile << "\t\t\t<ARR_ID>"         << (short)adr->Arr_ID       << "</ARR_ID>\n";
	TArrayI *Data = (TArrayI*)adr->Data;
 	  for (int k  = 0; k < adr->Arr_len; k++){
 	    k_data = (UInt_t)Data->At(k);
 	    Utility::endian_swap(k_data);
	    outputFile << "\t\t\t<ARR_VALUE>"      << k_data  << "</ARR_VALUE>\n";
	  }
	outputFile << "\t\t</ARRDUMP_RECORD>\n";
      }
      outputFile << "\t</ARRDUMP_RECORDS>\n";
      outputFile << "</ARRDUMP_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: ArrDumpToXML 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;
        }
    }
	ArrDumpToXML(argv[1], outDir, xslPath);
}
