/**
* McmdToXML
* author  Nagni
* version 2.0 - 14 February 2006
*
* Exctract info from the Mcmd packets into the ROOT file generated by YODA
* Note that the libutils.so and the utils/*.h are needed to compile this code.
*
* 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 <mcmd/McmdEvent.h>
#include <mcmd/McmdRecord.h>
#include <PscuHeader.h>
#include <EventHeader.h>
#include <sstream>
#include <fstream>
#include <YMcmd.h>

using namespace std;
void McmdToXML(TString base, TString outDirectory = "", TString xslPath = ""){
  
  Int_t    	tmpSize;
  Int_t         tmpSize2;
  ofstream 	outputFile;
  stringstream 	oss;
  
  McmdScan *mcmdReader = new McmdScan();
  TArrayC *data;
  pamela::McmdEvent  	*mcmde 	= 0;
  pamela::McmdRecord 	*mcmdr	= 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() << "Mcmd.xml";
  } else {
  	oss << outDirectory.Data() << fileName.Data() << "Mcmd.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("Mcmd");
    Long64_t nevents    = tr->GetEntries();
    tr->SetBranchAddress("Mcmd", &mcmde);
    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 << "<McmdFile fileName = '" <<   fileName.Data() << "'>\n";
    
    //<!-- Istruzione che indica il documento XSLT da associare -->    
    for (int i = 0; i < nevents; i++){
      tr->GetEntry(i);
      tmpSize = mcmde->Records->GetEntries();
      ph      = eh->GetPscuHeader();
      outputFile << "\t<McmdEvent PacketOBT = '" << dec << ph->GetOrbitalTime() 
	       << "' PacketNum = '"            <<  ph->GetCounter()    << "'>\n";
      for (int j = 0; j < tmpSize; j++){
	mcmdr = (pamela::McmdRecord*)mcmde->Records->At(j);
	outputFile << "\t\t<McmdRecord McmdOBT = '" << dec << mcmdr->MCMD_RECORD_OBT  
		 << "' SeqID = '"                 << (int)mcmdr->SeqID  
		 << "' ID1 = '"                   << hex << (int)mcmdr->ID1  << "'>\n";
	//printf("mcmd Code: %x \n", mcmdr->ID1);
	outputFile << mcmdReader->extract(mcmdr->McmdData, mcmdr->ID1, "\t\t\t");

	outputFile << "\t\t</McmdRecord>\n";
      }
      outputFile << "\t</McmdEvent>\n";	
    }
    outputFile << "</McmdFile>\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: McmdToXML FILE [OPTION] \n");
        printf( "\t --help                 Print this help and exit \n");
        printf( "\t -outDir[path]          Path where to put the output [default ./] \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;
        }
    }
	McmdToXML(argv[1], outDir, xslPath);
}


   
