<commit_before>// --- ROOT system
#include <TFile.h>
#include <TClonesArray.h>
#include <TList.h>
#include <TObjString.h>
#include <TTimeStamp.h>

#include "AliZDCPreprocessor.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliCDBMetaData.h"
#include "AliDCSValue.h"
#include "AliAlignObj.h"
#include "AliAlignObjParams.h"
#include "AliLog.h"
#include "AliZDCDataDCS.h"
#include "AliZDCPedestals.h"
#include "AliZDCCalib.h"
#include "AliZDCRecParam.h"

/////////////////////////////////////////////////////////////////////
//								   //
// Class implementing ZDC pre-processor.			   //
// It takes data from DCS and passes it to the class AliZDCDataDCS //
// The class is then written to the CDB.			   //
//								   //
/////////////////////////////////////////////////////////////////////

ClassImp(AliZDCPreprocessor)

//______________________________________________________________________________________________
AliZDCPreprocessor::AliZDCPreprocessor(AliShuttleInterface* shuttle) :
  AliPreprocessor("ZDC", shuttle),
  fData(0)
{
  // constructor
}

//______________________________________________________________________________________________
AliZDCPreprocessor::~AliZDCPreprocessor()
{
  // destructor
}

//______________________________________________________________________________________________
void AliZDCPreprocessor::Initialize(Int_t run, UInt_t startTime,
	UInt_t endTime)
{
  // Creates AliZDCDataDCS object

  AliPreprocessor::Initialize(run, startTime, endTime);

	Log(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run,
		TTimeStamp(startTime).AsString(),
		TTimeStamp(endTime).AsString()));

 	fRun = run;
        fStartTime = startTime;
        fEndTime = endTime;

	fData = new AliZDCDataDCS(fRun, fStartTime, fEndTime);
}

//______________________________________________________________________________________________
UInt_t AliZDCPreprocessor::Process(TMap* dcsAliasMap)
{
  // *************** From DCS ******************
  // Fills data into a AliZDCDataDCS object
  if(!dcsAliasMap) return 1;

  // The processing of the DCS input data is forwarded to AliZDCDataDCS
  Float_t dcsValues[28]; // DCSAliases=28
  fData->ProcessData(*dcsAliasMap, dcsValues);
  // Store DCS data for reference
  AliCDBMetaData metadata;
  metadata.SetResponsible("Chiara Oppedisano");
  metadata.SetComment("DCS data for ZDC");
  Bool_t resDCSRef = kFALSE;
  resDCSRef = StoreReferenceData("DCS","Data",fData,&metadata);
  //dcsAliasMap->Print("");
  //
  // --- Writing ZDC table positions into alignment object
  TClonesArray *array = new TClonesArray("AliAlignObjParams",10);
  TClonesArray &alobj = *array;
  AliAlignObjParams a;
  Double_t dx=0., dz=0., dpsi=0., dtheta=0., dphi=0.;
  // Vertical table position in mm from DCS
  Double_t dyZN1 = (Double_t) (dcsValues[0]/10.);
  Double_t dyZP1 = (Double_t) (dcsValues[1]/10.);
  Double_t dyZN2 = (Double_t) (dcsValues[2]/10.);
  Double_t dyZP2 = (Double_t) (dcsValues[3]/10.);
  const char *n1ZDC="ZDC/NeutronZDC1";
  const char *p1ZDC="ZDC/ProtonZDC1";
  const char *n2ZDC="ZDC/NeutronZDC2";
  const char *p2ZDC="ZDC/ProtonZDC2";
  UShort_t iIndex=0;
  AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer;
  UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,iIndex);
  //
  new(alobj[0]) AliAlignObjParams(n1ZDC, volid, dx, dyZN1, dz, dpsi, dtheta, dphi, kTRUE);
  new(alobj[1]) AliAlignObjParams(p1ZDC, volid, dx, dyZP1, dz, dpsi, dtheta, dphi, kTRUE);
  new(alobj[2]) AliAlignObjParams(n2ZDC, volid, dx, dyZN2, dz, dpsi, dtheta, dphi, kTRUE);
  new(alobj[3]) AliAlignObjParams(p2ZDC, volid, dx, dyZP2, dz, dpsi, dtheta, dphi, kTRUE);
  // save in CDB storage
  AliCDBMetaData md;
  md.SetResponsible("Chiara Oppedisano");
  md.SetComment("Alignment object for ZDC");
  Bool_t resultAl = kFALSE;
  resultAl = Store("Align","Data", array, &md, 0, 0);

// *************** From DAQ ******************
Bool_t resPedCal = kTRUE, resECal = kTRUE, resRecPar = kTRUE;
// *****************************************************
// [a] PEDESTALS -> Pedestal subtraction
// *****************************************************
TString runType = GetRunType();
printf("\n\t AliZDCPreprocessor -> runType detected %s\n\n",runType.Data());
if(runType == "PEDESTAL_RUN"){
  TList* daqSources = GetFileSources(kDAQ, "PEDESTALS");
  if(!daqSources){
    Log(Form("No source for PEDESTALS run %d !", fRun));
    return 1;
  }
  Log("\t List of sources for PEDESTALS");
  daqSources->Print();
  //
  TIter iter(daqSources);
  TObjString* source = 0;
  Int_t i=0;
  while((source = dynamic_cast<TObjString*> (iter.Next()))){
       Log(Form("\n\t Getting file #%d\n",++i));
       TString stringPedFileName = GetFile(kDAQ, "PEDESTALS", source->GetName());
       if(stringPedFileName.Length() <= 0){
          Log(Form("No PEDESTAL file from source %s!", source->GetName()));
	  return 1;
       }
       // --- Initializing pedestal calibration object
       AliZDCPedestals *pedCalib = new AliZDCPedestals("ZDC");
       // --- Reading file with pedestal calibration data
       const char* pedFileName = stringPedFileName.Data();
       // no. ADCch = (22 signal ch. + 2 reference PMs) * 2 gain chain = 48
       const Int_t knZDCch = 48;
       if(pedFileName){
         FILE *file;
         if((file = fopen(pedFileName,"r")) == NULL){
           printf("Cannot open file %s \n",pedFileName);
	   return 1;
         }
         Log(Form("File %s connected to process pedestal data", pedFileName));
         Float_t pedVal[(3*knZDCch)][2];
         for(Int_t i=0; i<(3*knZDCch); i++){
            for(Int_t j=0; j<2; j++){
               fscanf(file,"%f",&pedVal[i][j]);
	       //if(j==1) printf("pedVal[%d] -> %f, %f \n",i,pedVal[i][0],pedVal[i][1]);
            }
            if(i<knZDCch){
              pedCalib->SetMeanPed(i,pedVal[i][0]);
              pedCalib->SetMeanPedWidth(i,pedVal[i][1]);
            }
            else if(i>=knZDCch && i<(2*knZDCch)){
              pedCalib->SetOOTPed(i-knZDCch,pedVal[i][0]);
              pedCalib->SetOOTPedWidth(i-knZDCch,pedVal[i][1]);
            }
            else if(i>=(2*knZDCch) && i<(3*knZDCch)){
              pedCalib->SetPedCorrCoeff(i-(2*knZDCch),pedVal[i][0],pedVal[i][1]);
            }
         }
       }
       else{
          Log(Form("File %s not found", pedFileName));
          return 1;
       }
       //
      //pedCalib->Print("");
      //
      AliCDBMetaData metaData;
      metaData.SetBeamPeriod(0);
      metaData.SetResponsible("Chiara");
      metaData.SetComment("Filling AliZDCPedestals object");
      //
      resPedCal = Store("Calib","Pedestals",pedCalib, &metaData, 0, 1);
  }
  delete daqSources; daqSources = 0;
}
// *****************************************************
// [b] EMD EVENTS -> Energy calibration and equalization
// *****************************************************
else if(runType == "PULSER_RUN"){
  TList* daqSources = GetFileSources(kDAQ, "EMDCALIB");
  if(!daqSources){
    AliError(Form("No sources for PULSER_RUN run %d !", fRun));
    return 1;
  }
  Log("\t List of sources for PULSER_RUN");
  daqSources->Print();
  //
  TIter iter2(daqSources);
  TObjString* source = 0;
  Int_t j=0;
  while((source = dynamic_cast<TObjString*> (iter2.Next()))){
       Log(Form("\n\t Getting file #%d\n",++j));
       TString stringEMDFileName = GetFile(kDAQ, "EMDCALIB", source->GetName());
       if(stringEMDFileName.Length() <= 0){
         Log(Form("No EMDCALIB file from source %s!", source->GetName()));
	 return 1;
       }
       // --- Initializing pedestal calibration object
       AliZDCCalib *eCalib = new AliZDCCalib("ZDC");
       // --- Reading file with pedestal calibration data
       const char* emdFileName = stringEMDFileName.Data();
       if(emdFileName){
    	 FILE *file;
    	 if((file = fopen(emdFileName,"r")) == NULL){
    	   printf("Cannot open file %s \n",emdFileName);
	   return 1;
    	 }
    	 Log(Form("File %s connected to process data from EM dissociation events", emdFileName));
    	 //
	 Float_t fitValEMD[6]; Float_t equalCoeff[5][4];
	 Float_t calibVal[4];
    	 for(Int_t j=0; j<10; j++){
    	   if(j<6){
	     fscanf(file,"%f",&fitValEMD[j]);
             if(j<4){
	       calibVal[j] = fitValEMD[j]/2.76;
	       eCalib->SetEnCalib(j,calibVal[j]);
	     }
	     else eCalib->SetEnCalib(j,fitValEMD[j]);
	   }
	   else{
	     for(Int_t k=0; k<5; k++){
	        fscanf(file,"%f",&equalCoeff[j][k]);
	        if(j==6) eCalib->SetZN1EqualCoeff(k, equalCoeff[j][k]);
	 	else if(j==7) eCalib->SetZP1EqualCoeff(k, equalCoeff[j][k]);
	 	else if(j==8) eCalib->SetZN2EqualCoeff(k, equalCoeff[j][k]);
	 	else if(j==9) eCalib->SetZP2EqualCoeff(k, equalCoeff[j][k]);
             }
	   }
         }
       }
       else{
         Log(Form("File %s not found", emdFileName));
         return 1;
       }
       //calibdata->Print("");
      //
      AliCDBMetaData metaData;
      metaData.SetBeamPeriod(0);
      metaData.SetResponsible("Chiara");
      metaData.SetComment("Filling AliZDCCalib object");
      //
      resECal = Store("Calib","Calib",eCalib, &metaData, 0, 1);
  }
}
// ********************************************************
// [c] PHYSICS RUNS -> Parameters needed for reconstruction
// ********************************************************
else if(runType == "PHYSICS"){
  TList* daqSources = GetFileSources(kDAQ, "PHYSICS");
  if(!daqSources){
    AliError(Form("No sources for PHYSICS run %d !", fRun));
    return 1;
  }
  Log("\t List of sources for PHYSICS");
  daqSources->Print();
  //
  TIter iter2(daqSources);
  TObjString* source = 0;
  Int_t j=0;
  while((source = dynamic_cast<TObjString*> (iter2.Next()))){
       Log(Form("\n\t Getting file #%d\n",++j));
       TString stringPHYSFileName = GetFile(kDAQ, "PHYSICS", source->GetName());
       if(stringPHYSFileName.Length() <= 0){
         Log(Form("No PHYSICS file from source %s!", source->GetName()));
	 return 1;
       }
       // --- Initializing pedestal calibration object
       AliZDCRecParam *recCalib = new AliZDCRecParam("ZDC");
       // --- Reading file with pedestal calibration data
       const char* physFileName = stringPHYSFileName.Data();
       if(physFileName){
    	 FILE *file;
    	 if((file = fopen(physFileName,"r")) == NULL){
    	   printf("Cannot open file %s \n",physFileName);
	   return 1;
    	 }
    	 Log(Form("File %s connected to process data from PHYSICS runs", physFileName));
    	 //
	 Float_t physRecParam[10];
    	 for(Int_t j=0; j<10; j++) fscanf(file,"%f",&physRecParam[j]);
	 recCalib->SetZEMEndValue(physRecParam[0]);
	 recCalib->SetZEMCutFraction(physRecParam[1]);
	 recCalib->SetDZEMSup(physRecParam[2]);
	 recCalib->SetDZEMInf(physRecParam[3]);
	 recCalib->SetEZN1MaxValue(physRecParam[4]);
	 recCalib->SetEZP1MaxValue(physRecParam[5]);
	 recCalib->SetEZDC1MaxValue(physRecParam[6]);
	 recCalib->SetEZN2MaxValue(physRecParam[7]);
	 recCalib->SetEZP2MaxValue(physRecParam[8]);
	 recCalib->SetEZDC2MaxValue(physRecParam[9]);
       }
       else{
         Log(Form("File %s not found", physFileName));
         return 1;
       }
       //calibdata->Print("");
      //
      AliCDBMetaData metaData;
      metaData.SetBeamPeriod(0);
      metaData.SetResponsible("Chiara");
      metaData.SetComment("Filling AliZDCCalib object");
      //
      resRecPar = Store("Calib","RecParam",recCalib, &metaData, 0, 1);
  }
}
else {
  Log(Form("Nothing to do: run type is %s", runType.Data()));
  return 0;
}

  // note that the parameters are returned as character strings!
  const char* nEvents = GetRunParameter("totalEvents");
  if(nEvents) Log(Form("Number of events for run %d: %s",fRun, nEvents));
  else Log(Form("Number of events not put in logbook!"));

  UInt_t result = 0;
  if(resDCSRef==kFALSE || resultAl==kFALSE ||
     resPedCal==kFALSE || resECal==kFALSE || resRecPar==kFALSE){
    if(resDCSRef == kFALSE) result = 1;
    else if(resultAl == kFALSE)  result = 2;
    else if(resPedCal == kFALSE) result = 3;
    else if(resECal == kFALSE)   result = 4;
    else if(resRecPar == kFALSE) result = 5;
  }

  return result;

}
<commit_msg>Minor change<commit_after>// --- ROOT system
#include <TFile.h>
#include <TClonesArray.h>
#include <TList.h>
#include <TObjString.h>
#include <TTimeStamp.h>

#include "AliZDCPreprocessor.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliCDBMetaData.h"
#include "AliDCSValue.h"
#include "AliAlignObj.h"
#include "AliAlignObjParams.h"
#include "AliLog.h"
#include "AliZDCDataDCS.h"
#include "AliZDCPedestals.h"
#include "AliZDCCalib.h"
#include "AliZDCRecParam.h"

/////////////////////////////////////////////////////////////////////
//								   //
// Class implementing ZDC pre-processor.			   //
// It takes data from DCS and passes it to the class AliZDCDataDCS //
// The class is then written to the CDB.			   //
//								   //
/////////////////////////////////////////////////////////////////////

ClassImp(AliZDCPreprocessor)

//______________________________________________________________________________________________
AliZDCPreprocessor::AliZDCPreprocessor(AliShuttleInterface* shuttle) :
  AliPreprocessor("ZDC", shuttle),
  fData(0)
{
  // constructor
}

//______________________________________________________________________________________________
AliZDCPreprocessor::~AliZDCPreprocessor()
{
  // destructor
}

//______________________________________________________________________________________________
void AliZDCPreprocessor::Initialize(Int_t run, UInt_t startTime,
	UInt_t endTime)
{
  // Creates AliZDCDataDCS object

  AliPreprocessor::Initialize(run, startTime, endTime);

	Log(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run,
		TTimeStamp(startTime).AsString(),
		TTimeStamp(endTime).AsString()));

 	fRun = run;
        fStartTime = startTime;
        fEndTime = endTime;

	fData = new AliZDCDataDCS(fRun, fStartTime, fEndTime);
}

//______________________________________________________________________________________________
UInt_t AliZDCPreprocessor::Process(TMap* dcsAliasMap)
{
  // *************** From DCS ******************
  // Fills data into a AliZDCDataDCS object
  if(!dcsAliasMap) return 1;

  // The processing of the DCS input data is forwarded to AliZDCDataDCS
  Float_t dcsValues[28]; // DCSAliases=28
  fData->ProcessData(*dcsAliasMap, dcsValues);
  // Store DCS data for reference
  AliCDBMetaData metadata;
  metadata.SetResponsible("Chiara Oppedisano");
  metadata.SetComment("DCS data for ZDC");
  Bool_t resDCSRef = kTRUE;
  resDCSRef = StoreReferenceData("DCS","Data",fData,&metadata);
  //dcsAliasMap->Print("");
  //
  // --- Writing ZDC table positions into alignment object
  TClonesArray *array = new TClonesArray("AliAlignObjParams",10);
  TClonesArray &alobj = *array;
  AliAlignObjParams a;
  Double_t dx=0., dz=0., dpsi=0., dtheta=0., dphi=0.;
  // Vertical table position in mm from DCS
  Double_t dyZN1 = (Double_t) (dcsValues[0]/10.);
  Double_t dyZP1 = (Double_t) (dcsValues[1]/10.);
  Double_t dyZN2 = (Double_t) (dcsValues[2]/10.);
  Double_t dyZP2 = (Double_t) (dcsValues[3]/10.);
  const char *n1ZDC="ZDC/NeutronZDC1";
  const char *p1ZDC="ZDC/ProtonZDC1";
  const char *n2ZDC="ZDC/NeutronZDC2";
  const char *p2ZDC="ZDC/ProtonZDC2";
  UShort_t iIndex=0;
  AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer;
  UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,iIndex);
  //
  new(alobj[0]) AliAlignObjParams(n1ZDC, volid, dx, dyZN1, dz, dpsi, dtheta, dphi, kTRUE);
  new(alobj[1]) AliAlignObjParams(p1ZDC, volid, dx, dyZP1, dz, dpsi, dtheta, dphi, kTRUE);
  new(alobj[2]) AliAlignObjParams(n2ZDC, volid, dx, dyZN2, dz, dpsi, dtheta, dphi, kTRUE);
  new(alobj[3]) AliAlignObjParams(p2ZDC, volid, dx, dyZP2, dz, dpsi, dtheta, dphi, kTRUE);
  // save in CDB storage
  AliCDBMetaData md;
  md.SetResponsible("Chiara Oppedisano");
  md.SetComment("Alignment object for ZDC");
  Bool_t resultAl = kTRUE;
  resultAl = Store("Align","Data", array, &md, 0, 0);

// *************** From DAQ ******************
Bool_t resPedCal = kTRUE, resECal = kTRUE, resRecPar = kTRUE;
// *****************************************************
// [a] PEDESTALS -> Pedestal subtraction
// *****************************************************
TString runType = GetRunType();
printf("\n\t AliZDCPreprocessor -> runType detected %s\n\n",runType.Data());
if(runType == "PEDESTAL_RUN"){
  TList* daqSources = GetFileSources(kDAQ, "PEDESTALS");
  if(!daqSources){
    Log(Form("No source for PEDESTALS run %d !", fRun));
    return 1;
  }
  Log("\t List of sources for PEDESTALS");
  daqSources->Print();
  //
  TIter iter(daqSources);
  TObjString* source = 0;
  Int_t i=0;
  while((source = dynamic_cast<TObjString*> (iter.Next()))){
       Log(Form("\n\t Getting file #%d\n",++i));
       TString stringPedFileName = GetFile(kDAQ, "PEDESTALS", source->GetName());
       if(stringPedFileName.Length() <= 0){
          Log(Form("No PEDESTAL file from source %s!", source->GetName()));
	  return 1;
       }
       // --- Initializing pedestal calibration object
       AliZDCPedestals *pedCalib = new AliZDCPedestals("ZDC");
       // --- Reading file with pedestal calibration data
       const char* pedFileName = stringPedFileName.Data();
       // no. ADCch = (22 signal ch. + 2 reference PMs) * 2 gain chain = 48
       const Int_t knZDCch = 48;
       if(pedFileName){
         FILE *file;
         if((file = fopen(pedFileName,"r")) == NULL){
           printf("Cannot open file %s \n",pedFileName);
	   return 1;
         }
         Log(Form("File %s connected to process pedestal data", pedFileName));
         Float_t pedVal[(3*knZDCch)][2];
         for(Int_t i=0; i<(3*knZDCch); i++){
            for(Int_t j=0; j<2; j++){
               fscanf(file,"%f",&pedVal[i][j]);
	       //if(j==1) printf("pedVal[%d] -> %f, %f \n",i,pedVal[i][0],pedVal[i][1]);
            }
            if(i<knZDCch){
              pedCalib->SetMeanPed(i,pedVal[i][0]);
              pedCalib->SetMeanPedWidth(i,pedVal[i][1]);
            }
            else if(i>=knZDCch && i<(2*knZDCch)){
              pedCalib->SetOOTPed(i-knZDCch,pedVal[i][0]);
              pedCalib->SetOOTPedWidth(i-knZDCch,pedVal[i][1]);
            }
            else if(i>=(2*knZDCch) && i<(3*knZDCch)){
              pedCalib->SetPedCorrCoeff(i-(2*knZDCch),pedVal[i][0],pedVal[i][1]);
            }
         }
       }
       else{
          Log(Form("File %s not found", pedFileName));
          return 1;
       }
       //
      //pedCalib->Print("");
      //
      AliCDBMetaData metaData;
      metaData.SetBeamPeriod(0);
      metaData.SetResponsible("Chiara");
      metaData.SetComment("Filling AliZDCPedestals object");
      //
      resPedCal = Store("Calib","Pedestals",pedCalib, &metaData, 0, 1);
  }
  delete daqSources; daqSources = 0;
}
// *****************************************************
// [b] EMD EVENTS -> Energy calibration and equalization
// *****************************************************
else if(runType == "PULSER_RUN"){
  TList* daqSources = GetFileSources(kDAQ, "EMDCALIB");
  if(!daqSources){
    AliError(Form("No sources for PULSER_RUN run %d !", fRun));
    return 1;
  }
  Log("\t List of sources for PULSER_RUN");
  daqSources->Print();
  //
  TIter iter2(daqSources);
  TObjString* source = 0;
  Int_t j=0;
  while((source = dynamic_cast<TObjString*> (iter2.Next()))){
       Log(Form("\n\t Getting file #%d\n",++j));
       TString stringEMDFileName = GetFile(kDAQ, "EMDCALIB", source->GetName());
       if(stringEMDFileName.Length() <= 0){
         Log(Form("No EMDCALIB file from source %s!", source->GetName()));
	 return 1;
       }
       // --- Initializing pedestal calibration object
       AliZDCCalib *eCalib = new AliZDCCalib("ZDC");
       // --- Reading file with pedestal calibration data
       const char* emdFileName = stringEMDFileName.Data();
       if(emdFileName){
    	 FILE *file;
    	 if((file = fopen(emdFileName,"r")) == NULL){
    	   printf("Cannot open file %s \n",emdFileName);
	   return 1;
    	 }
    	 Log(Form("File %s connected to process data from EM dissociation events", emdFileName));
    	 //
	 Float_t fitValEMD[6]; Float_t equalCoeff[5][4];
	 Float_t calibVal[4];
    	 for(Int_t j=0; j<10; j++){
    	   if(j<6){
	     fscanf(file,"%f",&fitValEMD[j]);
             if(j<4){
	       calibVal[j] = fitValEMD[j]/2.76;
	       eCalib->SetEnCalib(j,calibVal[j]);
	     }
	     else eCalib->SetEnCalib(j,fitValEMD[j]);
	   }
	   else{
	     for(Int_t k=0; k<5; k++){
	        fscanf(file,"%f",&equalCoeff[j][k]);
	        if(j==6) eCalib->SetZN1EqualCoeff(k, equalCoeff[j][k]);
	 	else if(j==7) eCalib->SetZP1EqualCoeff(k, equalCoeff[j][k]);
	 	else if(j==8) eCalib->SetZN2EqualCoeff(k, equalCoeff[j][k]);
	 	else if(j==9) eCalib->SetZP2EqualCoeff(k, equalCoeff[j][k]);
             }
	   }
         }
       }
       else{
         Log(Form("File %s not found", emdFileName));
         return 1;
       }
       //calibdata->Print("");
      //
      AliCDBMetaData metaData;
      metaData.SetBeamPeriod(0);
      metaData.SetResponsible("Chiara");
      metaData.SetComment("Filling AliZDCCalib object");
      //
      resECal = Store("Calib","Calib",eCalib, &metaData, 0, 1);
  }
}
// ********************************************************
// [c] PHYSICS RUNS -> Parameters needed for reconstruction
// ********************************************************
else if(runType == "PHYSICS"){
  TList* daqSources = GetFileSources(kDAQ, "PHYSICS");
  if(!daqSources){
    AliError(Form("No sources for PHYSICS run %d !", fRun));
    return 1;
  }
  Log("\t List of sources for PHYSICS");
  daqSources->Print();
  //
  TIter iter2(daqSources);
  TObjString* source = 0;
  Int_t j=0;
  while((source = dynamic_cast<TObjString*> (iter2.Next()))){
       Log(Form("\n\t Getting file #%d\n",++j));
       TString stringPHYSFileName = GetFile(kDAQ, "PHYSICS", source->GetName());
       if(stringPHYSFileName.Length() <= 0){
         Log(Form("No PHYSICS file from source %s!", source->GetName()));
	 return 1;
       }
       // --- Initializing pedestal calibration object
       AliZDCRecParam *recCalib = new AliZDCRecParam("ZDC");
       // --- Reading file with pedestal calibration data
       const char* physFileName = stringPHYSFileName.Data();
       if(physFileName){
    	 FILE *file;
    	 if((file = fopen(physFileName,"r")) == NULL){
    	   printf("Cannot open file %s \n",physFileName);
	   return 1;
    	 }
    	 Log(Form("File %s connected to process data from PHYSICS runs", physFileName));
    	 //
	 Float_t physRecParam[10];
    	 for(Int_t j=0; j<10; j++) fscanf(file,"%f",&physRecParam[j]);
	 recCalib->SetZEMEndValue(physRecParam[0]);
	 recCalib->SetZEMCutFraction(physRecParam[1]);
	 recCalib->SetDZEMSup(physRecParam[2]);
	 recCalib->SetDZEMInf(physRecParam[3]);
	 recCalib->SetEZN1MaxValue(physRecParam[4]);
	 recCalib->SetEZP1MaxValue(physRecParam[5]);
	 recCalib->SetEZDC1MaxValue(physRecParam[6]);
	 recCalib->SetEZN2MaxValue(physRecParam[7]);
	 recCalib->SetEZP2MaxValue(physRecParam[8]);
	 recCalib->SetEZDC2MaxValue(physRecParam[9]);
       }
       else{
         Log(Form("File %s not found", physFileName));
         return 1;
       }
       //calibdata->Print("");
      //
      AliCDBMetaData metaData;
      metaData.SetBeamPeriod(0);
      metaData.SetResponsible("Chiara");
      metaData.SetComment("Filling AliZDCCalib object");
      //
      resRecPar = Store("Calib","RecParam",recCalib, &metaData, 0, 1);
  }
}
else {
  Log(Form("Nothing to do: run type is %s", runType.Data()));
  return 0;
}

  // note that the parameters are returned as character strings!
  const char* nEvents = GetRunParameter("totalEvents");
  if(nEvents) Log(Form("Number of events for run %d: %s",fRun, nEvents));
  else Log(Form("Number of events not put in logbook!"));

  UInt_t result = 0;
  if(resDCSRef==kFALSE || resultAl==kFALSE ||
     resPedCal==kFALSE || resECal==kFALSE || resRecPar==kFALSE){
    if(resDCSRef == kFALSE) result = 1;
    else if(resultAl == kFALSE)  result = 2;
    else if(resPedCal == kFALSE) result = 3;
    else if(resECal == kFALSE)   result = 4;
    else if(resRecPar == kFALSE) result = 5;
  }

  return result;

}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Project: BaBar detector at the SLAC PEP-II B-factory
 * Package: RooFitCore
 *    File: $Id: RooCurve.cc,v 1.27 2001/11/19 18:03:20 verkerke Exp $
 * Authors:
 *   DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu
 * History:
 *   29-Apr-2001 DK Created initial version
 *
 * Copyright (C) 2001 Stanford University
 *****************************************************************************/

// -- CLASS DESCRIPTION [PLOT] --
// A RooCurve is a one-dimensional graphical representation of a real-valued function.
// A curve is approximated by straight line segments with endpoints chosen to give
// a "good" approximation to the true curve. The goodness of the approximation is
// controlled by a precision and a resolution parameter. To view the points where
// a function y(x) is actually evaluated to approximate a smooth curve, use:
//
//  RooPlot *p= y.plotOn(x.frame());
//  p->getAttMarker("curve_y")->SetMarkerStyle(20);
//  p->setDrawOptions("curve_y","PL");
//  p->Draw();

// #include "BaBar/BaBar.hh"

#include "RooFitCore/RooCurve.hh"
#include "RooFitCore/RooHist.hh"
#include "RooFitCore/RooAbsReal.hh"
#include "RooFitCore/RooArgSet.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooRealIntegral.hh"
#include "RooFitCore/RooRealBinding.hh"
#include "RooFitCore/RooScaledFunc.hh"

#include <iostream.h>
#include <iomanip.h>
#include <math.h>
#include <assert.h>

ClassImp(RooCurve)

static const char rcsid[] =
"$Id: RooCurve.cc,v 1.27 2001/11/19 18:03:20 verkerke Exp $";

RooCurve::RooCurve() {
  initialize();
}

RooCurve::RooCurve(const RooAbsReal &f, RooAbsRealLValue &x, Double_t xlo, Double_t xhi, Int_t xbins,
		   Double_t scaleFactor, const RooArgSet *normVars, Double_t prec, Double_t resolution,
		   Bool_t shiftToZero) {
  // Create a 1-dim curve of the value of the specified real-valued expression
  // as a function of x. Use the optional precision parameter to control
  // how precisely the smooth curve is rasterized. Use the optional argument set
  // to specify how the expression should be normalized. Use the optional scale
  // factor to rescale the expression after normalization.
  // If shiftToZero is set, the entire curve is shift down to make the lowest
  // point in of the curve go through zero.

  // grab the function's name and title
  TString name("curve_");
  name.Append(f.GetName());
  SetName(name.Data());
  TString title(f.GetTitle());
  SetTitle(title.Data());
  // append " ( [<funit> ][/ <xunit> ])" to our y-axis label if necessary
  if(0 != strlen(f.getUnit()) || 0 != strlen(x.getUnit())) {
    title.Append(" ( ");
    if(0 != strlen(f.getUnit())) {
      title.Append(f.getUnit());
      title.Append(" ");
    }
    if(0 != strlen(x.getUnit())) {
      title.Append("/ ");
      title.Append(x.getUnit());
      title.Append(" ");
    }
    title.Append(")");
  }
  setYAxisLabel(title.Data());

  RooAbsFunc *funcPtr(0),*rawPtr(0);
  funcPtr= f.bindVars(x,normVars,kTRUE);

  // apply a scale factor if necessary
  if(scaleFactor != 1) {
    rawPtr= funcPtr;
    funcPtr= new RooScaledFunc(*rawPtr,scaleFactor);
  }
  assert(0 != funcPtr);

  // calculate the points to add to our curve
  Double_t prevYMax = getYAxisMax() ;
  addPoints(*funcPtr,xlo,xhi,xbins+1,prec,resolution);
  initialize();

  // cleanup
  delete funcPtr;
  if(rawPtr) delete rawPtr;
  if (shiftToZero) shiftCurveToZero(prevYMax) ;
}

RooCurve::RooCurve(const char *name, const char *title, const RooAbsFunc &func,
		   Double_t xlo, Double_t xhi, UInt_t minPoints, Double_t prec, Double_t resolution,
		   Bool_t shiftToZero) {
  SetName(name);
  SetTitle(title);
  Double_t prevYMax = getYAxisMax() ;
  addPoints(func,xlo,xhi,minPoints,prec,resolution);
  initialize();
  if (shiftToZero) shiftCurveToZero(prevYMax) ;
}

RooCurve::~RooCurve()
{
}

void RooCurve::initialize()
{
  // Perform initialization that is common to all constructors.

  // set default line width in pixels
  SetLineWidth(3);
  // set default line color
  SetLineColor(kBlue);
}

void RooCurve::shiftCurveToZero(Double_t prevYMax)
  // Find lowest point in curve and move all points in curve so that
  // lowest point will go exactly through zero
{
  Int_t i ;
  Double_t minVal(1e30) ;
  Double_t maxVal(-1e30) ;

  // First iteration, find current lowest point
  for (i=0 ; i<GetN() ; i++) {
    Double_t x,y ;
    GetPoint(i,x,y) ;
    if (y<minVal) minVal=y ;
    if (y>maxVal) maxVal=y ;
  }

  // Second iteration, lower all points by minVal
  for (i=0 ; i<GetN() ; i++) {
    Double_t x,y ;
    GetPoint(i,x,y) ;
    SetPoint(i,x,y-minVal) ;
  }

  // Check if y-axis range needs readjustment
  if (getYAxisMax()>prevYMax) {
    Double_t newMax = maxVal - minVal ;
    setYAxisLimits(getYAxisMin(), newMax<prevYMax ? prevYMax : newMax) ;
  }
}

void RooCurve::addPoints(const RooAbsFunc &func, Double_t xlo, Double_t xhi,
			 Int_t minPoints, Double_t prec, Double_t resolution) {
  // Add points calculated with the specified function, over the range (xlo,xhi).
  // Add at least minPoints equally spaced points, and add sufficient points so that
  // the maximum deviation from the final straight-line segements is prec*(ymax-ymin),
  // down to a minimum horizontal spacing of resolution*(xhi-xlo).

  // check the inputs
  if(!func.isValid()) {
    cout << fName << "::addPoints: input function is not valid" << endl;
    return;
  }
  if(minPoints <= 0 || xhi <= xlo) {
    cout << fName << "::addPoints: bad input (nothing added)" << endl;
    return;
  }

  // Perform a coarse scan of the function to estimate its y range.
  // Save the results so we do not have to re-evaluate at the scan points.
  Double_t *yval= new Double_t[minPoints];
  assert(0 != yval);
  Double_t x,dx= (xhi-xlo)/(minPoints-1.);
  for(Int_t step= 0; step < minPoints; step++) {
    x= xlo + step*dx;
    if (step==minPoints-1) x-=1e-15 ;
    yval[step]= func(&x);
    updateYAxisLimits(yval[step]);
  }

  // store points of the coarse scan and calculate any refinements necessary
  Double_t minDx= resolution*(xhi-xlo);
  Double_t x1,x2= xlo;

  addPoint(xlo-dx,0) ;
  addPoint(xlo-dx,yval[0]) ;

  addPoint(xlo,yval[0]);
  for(Int_t step= 1; step < minPoints; step++) {
    x1= x2;
    x2= xlo + step*dx;
    addRange(func,x1,x2,yval[step-1],yval[step],prec,minDx);
  }
  addPoint(xhi,yval[minPoints-1]) ;

  addPoint(xhi+dx,yval[minPoints-1]) ;
  addPoint(xhi+dx,0) ;

  // cleanup
  delete [] yval;
}

void RooCurve::addRange(const RooAbsFunc& func, Double_t x1, Double_t x2,
			Double_t y1, Double_t y2, Double_t prec, Double_t minDx) {
  // Fill the range (x1,x2) with points calculated using func(&x). No point will
  // be added at x1, and a point will always be added at x2. The density of points
  // will be calculated so that the maximum deviation from a straight line
  // approximation is prec*(ymax-ymin) down to the specified minimum horizontal spacing.

  // calculate our value at the midpoint of this range
  Double_t xmid= 0.5*(x1+x2);
  Double_t ymid= func(&xmid);
  // test if the midpoint is sufficiently close to a straight line across this interval
  Double_t dy= ymid - 0.5*(y1+y2);
  if((xmid - x1 >= minDx) && fabs(dy)>0 && fabs(dy) >= prec*(getYAxisMax()-getYAxisMin())) {
    // fill in each subrange
    updateYAxisLimits(ymid);
    addRange(func,x1,xmid,y1,ymid,prec,minDx);
    addRange(func,xmid,x2,ymid,y2,prec,minDx);
  }
  else {
    // add the endpoint
    addPoint(x2,y2);
  }
}

void RooCurve::addPoint(Double_t x, Double_t y) {
  // Add a point with the specified coordinates. Update our y-axis limits.

  // cout << "RooCurve("<< GetName() << ") adding point at (" << x << "," << y << ")" << endl ;
  Int_t next= GetN();
  SetPoint(next, x, y);
}

Double_t RooCurve::getFitRangeNEvt() const {
  return 1;
}

Double_t RooCurve::getFitRangeBinW() const {
  return 1;
}

void RooCurve::printToStream(ostream& os, PrintOption opt, TString indent) const {
  // Print info about this histogram to the specified output stream.
  //
  //   Standard: number of entries
  //    Verbose: print points on curve

  oneLinePrint(os,*this);
  RooPlotable::printToStream(os,opt,indent);
  if(opt >= Standard) {
    os << indent << "--- RooCurve ---" << endl;
    Int_t n= GetN();
    os << indent << "  Contains " << n << " points" << endl;
    if(opt >= Verbose) {
      os << indent << "  Graph points:" << endl;
      for(Int_t i= 0; i < n; i++) {
	os << indent << setw(3) << i << ") x = " << fX[i] << " , y = " << fY[i] << endl;
      }
    }
  }
}

Double_t RooCurve::chiSquare(const RooHist& hist) const
{
  Int_t i,np = hist.GetN() ;
  Double_t x,y,eyl,eyh ;
  Double_t hbinw2 = hist.getNominalBinWidth()/2 ;

  Double_t chisq(0) ;
  for (i=0 ; i<np ; i++) {
    // Retrieve histogram contents
    ((RooHist&)hist).GetPoint(i,x,y) ;
    eyl = hist.GetEYlow()[i] ;
    eyh = hist.GetEYhigh()[i] ;

    // Integrate function over this bin
    Double_t avg = average(x-hbinw2,x+hbinw2) ;

    // Add pull^2 to chisq
    if (y!=0) {
      Double_t pull = (y>avg) ? ((y-avg)/eyh) : ((y-avg)/eyl) ;
      chisq += pull*pull ;
    }
  }

  // Return chisq/nDOF
  return chisq / np ;
}

Double_t RooCurve::average(Double_t lo, Double_t hi) const
{
  // Find points corresponding to first and last point
  Int_t ifirst = findPoint(lo) ;
  Int_t ilast  = findPoint(hi) ;

  if (ilast<=ifirst) {
    cout << "RooCurve::average(" << GetName()
	 << ") invalid range (" << lo << "," << hi << ")" << endl ;
    return 0 ;
  }

  // Trapezoid integration
  Int_t i ;
  Double_t sum(0),x1,y1,x2,y2 ;
  for (i=ifirst ; i<ilast ; i++) {
    ((RooCurve&)*this).GetPoint(i,x1,y1) ;
    ((RooCurve&)*this).GetPoint(i+1,x2,y2) ;
    sum += (x2-x1)*(y1+y2)/2 ;
  }

  // Return trapezoid sum devided by integration range
  ((RooCurve&)*this).GetPoint(ifirst,x1,y1) ;
  ((RooCurve&)*this).GetPoint(ilast,x2,y2) ;
  return sum/(x2-x1) ;
}

Int_t RooCurve::findPoint(Double_t xvalue) const
{
  Double_t delta(999.),x,y ;
  Int_t i,n = GetN() ;
  Int_t ibest(-1) ;
  for (i=0 ; i<n ; i++) {
    ((RooCurve&)*this).GetPoint(i,x,y) ;
    if (fabs(xvalue-x)<delta) {
      delta = fabs(xvalue-x) ;
      ibest = i ;
    }
  }

  return (delta<1e-10)?ibest:-1 ;
}
<commit_msg><commit_after>/*****************************************************************************
 * Project: BaBar detector at the SLAC PEP-II B-factory
 * Package: RooFitCore
 *    File: $Id: RooCurve.cc,v 1.28 2001/12/13 23:08:44 verkerke Exp $
 * Authors:
 *   DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu
 * History:
 *   29-Apr-2001 DK Created initial version
 *
 * Copyright (C) 2001 Stanford University
 *****************************************************************************/

// -- CLASS DESCRIPTION [PLOT] --
// A RooCurve is a one-dimensional graphical representation of a real-valued function.
// A curve is approximated by straight line segments with endpoints chosen to give
// a "good" approximation to the true curve. The goodness of the approximation is
// controlled by a precision and a resolution parameter. To view the points where
// a function y(x) is actually evaluated to approximate a smooth curve, use:
//
//  RooPlot *p= y.plotOn(x.frame());
//  p->getAttMarker("curve_y")->SetMarkerStyle(20);
//  p->setDrawOptions("curve_y","PL");
//  p->Draw();

// #include "BaBar/BaBar.hh"

#include "RooFitCore/RooCurve.hh"
#include "RooFitCore/RooHist.hh"
#include "RooFitCore/RooAbsReal.hh"
#include "RooFitCore/RooArgSet.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooRealIntegral.hh"
#include "RooFitCore/RooRealBinding.hh"
#include "RooFitCore/RooScaledFunc.hh"

#include <iostream.h>
#include <iomanip.h>
#include <math.h>
#include <assert.h>

ClassImp(RooCurve)

static const char rcsid[] =
"$Id: RooCurve.cc,v 1.28 2001/12/13 23:08:44 verkerke Exp $";

RooCurve::RooCurve() {
  initialize();
}

RooCurve::RooCurve(const RooAbsReal &f, RooAbsRealLValue &x, Double_t xlo, Double_t xhi, Int_t xbins,
		   Double_t scaleFactor, const RooArgSet *normVars, Double_t prec, Double_t resolution,
		   Bool_t shiftToZero) {
  // Create a 1-dim curve of the value of the specified real-valued expression
  // as a function of x. Use the optional precision parameter to control
  // how precisely the smooth curve is rasterized. Use the optional argument set
  // to specify how the expression should be normalized. Use the optional scale
  // factor to rescale the expression after normalization.
  // If shiftToZero is set, the entire curve is shift down to make the lowest
  // point in of the curve go through zero.

  // grab the function's name and title
  TString name("curve_");
  name.Append(f.GetName());
  SetName(name.Data());
  TString title(f.GetTitle());
  SetTitle(title.Data());
  // append " ( [<funit> ][/ <xunit> ])" to our y-axis label if necessary
  if(0 != strlen(f.getUnit()) || 0 != strlen(x.getUnit())) {
    title.Append(" ( ");
    if(0 != strlen(f.getUnit())) {
      title.Append(f.getUnit());
      title.Append(" ");
    }
    if(0 != strlen(x.getUnit())) {
      title.Append("/ ");
      title.Append(x.getUnit());
      title.Append(" ");
    }
    title.Append(")");
  }
  setYAxisLabel(title.Data());

  RooAbsFunc *funcPtr(0),*rawPtr(0);
  funcPtr= f.bindVars(x,normVars,kTRUE);

  // apply a scale factor if necessary
  if(scaleFactor != 1) {
    rawPtr= funcPtr;
    funcPtr= new RooScaledFunc(*rawPtr,scaleFactor);
  }
  assert(0 != funcPtr);

  // calculate the points to add to our curve
  Double_t prevYMax = getYAxisMax() ;
  addPoints(*funcPtr,xlo,xhi,xbins+1,prec,resolution);
  initialize();

  // cleanup
  delete funcPtr;
  if(rawPtr) delete rawPtr;
  if (shiftToZero) shiftCurveToZero(prevYMax) ;
}

RooCurve::RooCurve(const char *name, const char *title, const RooAbsFunc &func,
		   Double_t xlo, Double_t xhi, UInt_t minPoints, Double_t prec, Double_t resolution,
		   Bool_t shiftToZero) {
  SetName(name);
  SetTitle(title);
  Double_t prevYMax = getYAxisMax() ;
  addPoints(func,xlo,xhi,minPoints,prec,resolution);
  initialize();
  if (shiftToZero) shiftCurveToZero(prevYMax) ;
}

RooCurve::~RooCurve()
{
}

void RooCurve::initialize()
{
  // Perform initialization that is common to all constructors.

  // set default line width in pixels
  SetLineWidth(3);
  // set default line color
  SetLineColor(kBlue);
}

void RooCurve::shiftCurveToZero(Double_t prevYMax)
  // Find lowest point in curve and move all points in curve so that
  // lowest point will go exactly through zero
{
  Int_t i ;
  Double_t minVal(1e30) ;
  Double_t maxVal(-1e30) ;

  // First iteration, find current lowest point
  for (i=1 ; i<GetN()-1 ; i++) {
    Double_t x,y ;
    GetPoint(i,x,y) ;
    if (y<minVal) minVal=y ;
    if (y>maxVal) maxVal=y ;
  }

  // Second iteration, lower all points by minVal
  for (i=1 ; i<GetN()-1 ; i++) {
    Double_t x,y ;
    GetPoint(i,x,y) ;
    SetPoint(i,x,y-minVal) ;
  }

  // Check if y-axis range needs readjustment
  if (getYAxisMax()>prevYMax) {
    Double_t newMax = maxVal - minVal ;
    setYAxisLimits(getYAxisMin(), newMax<prevYMax ? prevYMax : newMax) ;
  }
}

void RooCurve::addPoints(const RooAbsFunc &func, Double_t xlo, Double_t xhi,
			 Int_t minPoints, Double_t prec, Double_t resolution) {
  // Add points calculated with the specified function, over the range (xlo,xhi).
  // Add at least minPoints equally spaced points, and add sufficient points so that
  // the maximum deviation from the final straight-line segements is prec*(ymax-ymin),
  // down to a minimum horizontal spacing of resolution*(xhi-xlo).

  // check the inputs
  if(!func.isValid()) {
    cout << fName << "::addPoints: input function is not valid" << endl;
    return;
  }
  if(minPoints <= 0 || xhi <= xlo) {
    cout << fName << "::addPoints: bad input (nothing added)" << endl;
    return;
  }

  // Perform a coarse scan of the function to estimate its y range.
  // Save the results so we do not have to re-evaluate at the scan points.
  Double_t *yval= new Double_t[minPoints];
  assert(0 != yval);
  Double_t x,dx= (xhi-xlo)/(minPoints-1.);
  for(Int_t step= 0; step < minPoints; step++) {
    x= xlo + step*dx;
    if (step==minPoints-1) x-=1e-15 ;
    yval[step]= func(&x);
    updateYAxisLimits(yval[step]);
  }

  // store points of the coarse scan and calculate any refinements necessary
  Double_t minDx= resolution*(xhi-xlo);
  Double_t x1,x2= xlo;

  addPoint(xlo-dx,0) ;
  addPoint(xlo-dx,yval[0]) ;

  addPoint(xlo,yval[0]);
  for(Int_t step= 1; step < minPoints; step++) {
    x1= x2;
    x2= xlo + step*dx;
    addRange(func,x1,x2,yval[step-1],yval[step],prec,minDx);
  }
  addPoint(xhi,yval[minPoints-1]) ;

  addPoint(xhi+dx,yval[minPoints-1]) ;
  addPoint(xhi+dx,0) ;

  // cleanup
  delete [] yval;
}

void RooCurve::addRange(const RooAbsFunc& func, Double_t x1, Double_t x2,
			Double_t y1, Double_t y2, Double_t prec, Double_t minDx) {
  // Fill the range (x1,x2) with points calculated using func(&x). No point will
  // be added at x1, and a point will always be added at x2. The density of points
  // will be calculated so that the maximum deviation from a straight line
  // approximation is prec*(ymax-ymin) down to the specified minimum horizontal spacing.

  // calculate our value at the midpoint of this range
  Double_t xmid= 0.5*(x1+x2);
  Double_t ymid= func(&xmid);
  // test if the midpoint is sufficiently close to a straight line across this interval
  Double_t dy= ymid - 0.5*(y1+y2);
  if((xmid - x1 >= minDx) && fabs(dy)>0 && fabs(dy) >= prec*(getYAxisMax()-getYAxisMin())) {
    // fill in each subrange
    updateYAxisLimits(ymid);
    addRange(func,x1,xmid,y1,ymid,prec,minDx);
    addRange(func,xmid,x2,ymid,y2,prec,minDx);
  }
  else {
    // add the endpoint
    addPoint(x2,y2);
  }
}

void RooCurve::addPoint(Double_t x, Double_t y) {
  // Add a point with the specified coordinates. Update our y-axis limits.

  // cout << "RooCurve("<< GetName() << ") adding point at (" << x << "," << y << ")" << endl ;
  Int_t next= GetN();
  SetPoint(next, x, y);
}

Double_t RooCurve::getFitRangeNEvt() const {
  return 1;
}

Double_t RooCurve::getFitRangeBinW() const {
  return 1;
}

void RooCurve::printToStream(ostream& os, PrintOption opt, TString indent) const {
  // Print info about this histogram to the specified output stream.
  //
  //   Standard: number of entries
  //    Verbose: print points on curve

  oneLinePrint(os,*this);
  RooPlotable::printToStream(os,opt,indent);
  if(opt >= Standard) {
    os << indent << "--- RooCurve ---" << endl;
    Int_t n= GetN();
    os << indent << "  Contains " << n << " points" << endl;
    if(opt >= Verbose) {
      os << indent << "  Graph points:" << endl;
      for(Int_t i= 0; i < n; i++) {
	os << indent << setw(3) << i << ") x = " << fX[i] << " , y = " << fY[i] << endl;
      }
    }
  }
}

Double_t RooCurve::chiSquare(const RooHist& hist) const
{
  Int_t i,np = hist.GetN() ;
  Double_t x,y,eyl,eyh ;
  Double_t hbinw2 = hist.getNominalBinWidth()/2 ;

  Double_t chisq(0) ;
  for (i=0 ; i<np ; i++) {
    // Retrieve histogram contents
    ((RooHist&)hist).GetPoint(i,x,y) ;
    eyl = hist.GetEYlow()[i] ;
    eyh = hist.GetEYhigh()[i] ;

    // Integrate function over this bin
    Double_t avg = average(x-hbinw2,x+hbinw2) ;

    // Add pull^2 to chisq
    if (y!=0) {
      Double_t pull = (y>avg) ? ((y-avg)/eyh) : ((y-avg)/eyl) ;
      chisq += pull*pull ;
    }
  }

  // Return chisq/nDOF
  return chisq / np ;
}

Double_t RooCurve::average(Double_t lo, Double_t hi) const
{
  // Find points corresponding to first and last point
  Int_t ifirst = findPoint(lo) ;
  Int_t ilast  = findPoint(hi) ;

  if (ilast<=ifirst) {
    cout << "RooCurve::average(" << GetName()
	 << ") invalid range (" << lo << "," << hi << ")" << endl ;
    return 0 ;
  }

  // Trapezoid integration
  Int_t i ;
  Double_t sum(0),x1,y1,x2,y2 ;
  for (i=ifirst ; i<ilast ; i++) {
    ((RooCurve&)*this).GetPoint(i,x1,y1) ;
    ((RooCurve&)*this).GetPoint(i+1,x2,y2) ;
    sum += (x2-x1)*(y1+y2)/2 ;
  }

  // Return trapezoid sum devided by integration range
  ((RooCurve&)*this).GetPoint(ifirst,x1,y1) ;
  ((RooCurve&)*this).GetPoint(ilast,x2,y2) ;
  return sum/(x2-x1) ;
}

Int_t RooCurve::findPoint(Double_t xvalue) const
{
  Double_t delta(999.),x,y ;
  Int_t i,n = GetN() ;
  Int_t ibest(-1) ;
  for (i=0 ; i<n ; i++) {
    ((RooCurve&)*this).GetPoint(i,x,y) ;
    if (fabs(xvalue-x)<delta) {
      delta = fabs(xvalue-x) ;
      ibest = i ;
    }
  }

  return (delta<1e-10)?ibest:-1 ;
}
<|endoftext|>


<commit_before>//===--- ExprCXX.cpp - (C++) Expression AST Node Implementation -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Ted Kremenek and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the subclesses of Expr class declared in ExprCXX.h
//
//===----------------------------------------------------------------------===//

#include "clang/AST/ExprCXX.h"
using namespace clang;

//===----------------------------------------------------------------------===//
//  Child Iterators for iterating over subexpressions/substatements
//===----------------------------------------------------------------------===//

// CXXCastExpr
Stmt::child_iterator CXXCastExpr::child_begin() {
  return reinterpret_cast<Stmt**>(&Op);
}

Stmt::child_iterator CXXCastExpr::child_end() {
  return ++child_begin();
}

// CXXBoolLiteralExpr
Stmt::child_iterator CXXBoolLiteralExpr::child_begin() { return NULL; }
Stmt::child_iterator CXXBoolLiteralExpr::child_end() { return NULL; }
<commit_msg>Replaced virtual method call to child_begin() in child_end() by directly inlining its logic.<commit_after>//===--- ExprCXX.cpp - (C++) Expression AST Node Implementation -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Ted Kremenek and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the subclesses of Expr class declared in ExprCXX.h
//
//===----------------------------------------------------------------------===//

#include "clang/AST/ExprCXX.h"
using namespace clang;

//===----------------------------------------------------------------------===//
//  Child Iterators for iterating over subexpressions/substatements
//===----------------------------------------------------------------------===//

// CXXCastExpr
Stmt::child_iterator CXXCastExpr::child_begin() {
  return reinterpret_cast<Stmt**>(&Op);
}

Stmt::child_iterator CXXCastExpr::child_end() {
  return reinterpret_cast<Stmt**>(&Op)+1;
}

// CXXBoolLiteralExpr
Stmt::child_iterator CXXBoolLiteralExpr::child_begin() { return NULL; }
Stmt::child_iterator CXXBoolLiteralExpr::child_end() { return NULL; }
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include "world.h"
#include "room.h"
#include "exit.h"
#include "item.h"

using namespace std;

World::World()
{
	//Initializing turnTime to allow modifications later
	turnTime = 12000.0;

	//Room Creation
	Room* sleeping_quarters = new Room("Sleeping quarters", "It's kinda dark, and everyone is sleeping. You should not wake anyone...");
	Room* main_deck = new Room("Main deck", "The main deck of the ship. It's very peacefull at night, and you hear the waves hitting the ship. A light can be seen up, in the Crow's nest.");
	Room* storage_room = new Room("Storage room", "A couple of handy materials, food and general things. Everything the crew loots ends up here.");
	Room* poopdeck = new Room("Poopdeck", "You can see the rest of the ship from here, and the helm is resting, without anyone moving it at night.");
	Room* crows_nest = new Room("Crow's nest", "The lookouts' favourite place. The salty wind goes through you, slightly cold. You can see everything from here.");

	//Exit creation and storage
	Exit* exit1 = new Exit(up, sleeping_quarters, main_deck, false, "none");
	sleeping_quarters->exits.push_back(exit1);
	Exit* exit2 = new Exit(down, main_deck, sleeping_quarters, false, "none");
	main_deck->exits.push_back(exit2);
	Exit* exit3 = new Exit(west, sleeping_quarters, storage_room, true, "Key");
	sleeping_quarters->exits.push_back(exit3);
	Exit* exit4 = new Exit(east, storage_room, sleeping_quarters, false, "none");
	storage_room->exits.push_back(exit4);
	Exit* exit5 = new Exit(up, main_deck, crows_nest, false, "none");
	main_deck->exits.push_back(exit5);
	Exit* exit6 = new Exit(down, crows_nest, main_deck, false, "none");
	crows_nest->exits.push_back(exit6);
	Exit* exit7 = new Exit(north, main_deck, poopdeck, false, "none");
	main_deck->exits.push_back(exit7);
	Exit* exit8 = new Exit(south, poopdeck, main_deck, false, "none");
	poopdeck->exits.push_back(exit8);

	//Player and Badguy creation
	mainguy = new Player("Zelleryon", "A young, untrained but clever pirate", sleeping_quarters);
	badguy = new Npc("Slinger", "The cruel and harsh lookout of the ship.", crows_nest);

	//Item creation and storage - Pickable
	Item* sword = new Item("Cutlass", "A slightly old, ugly but effective weapon.", USABLE);
	sleeping_quarters->containedEntities.push_back(sword);
	Item* letter = new Item("Letter", "[...] By our majesty's name, this letter will serve as a forgiveness for the former pirate Joe 'Hound' Emmerick [...] surrendering of his whole crew to the navy [...] crew will be hanged with no possibility of trial. Signed: Admiral Robert Blake.", SIMPLE);
	sleeping_quarters->containedEntities.push_back(letter);
	Item* hammer = new Item("Hammer", "A small hammer. Nothing special.", USABLE);
	poopdeck->containedEntities.push_back(hammer);
	Item* nails = new Item("Nails", "Wood nails. As simple as that.", SIMPLE);
	storage_room->containedEntities.push_back(nails);
	Item* oranges = new Item("Oranges", "The favorite defense of all pirates against scurvy! Pretty tasty, too.", FOOD);
	storage_room->containedEntities.push_back(oranges);
	Item* bottle = new Item("Water", "A small bottle of water. This could be perfect for the trip.", FOOD);
	crows_nest->containedEntities.push_back(bottle);
	Item* bag = new Item("Bag", "A small bag. It can be used to carry something.", CONTAINER);
	poopdeck->containedEntities.push_back(bag);
	Item* woodplank = new Item("Plank", "A pretty solid plank. Could be used to close a door or cover something damaged.", SIMPLE);
	storage_room->containedEntities.push_back(woodplank);
	Item* spyglass = new Item("Spyglass", "An old spyglass stolen from the lookout.", SIMPLE);
	crows_nest->containedEntities.push_back(spyglass);
	Item* storagekey = new Item("Key", "The key of the Storage room.", SIMPLE);
	crows_nest->containedEntities.push_back(storagekey);

	//Item creation and storage - UnPickable
	Item* sails = new Item("Sails", "The sails of the ship. You can see the ropes that hold them together on the sides.", UNPICKABLE);
	main_deck->containedEntities.push_back(sails);
	Item* helm = new Item("Helm", "The device taking care of controling the direction of the ship. Would be a shame if someone messes with it...", UNPICKABLE);
	poopdeck->containedEntities.push_back(helm);
	Item* boat = new Item("Boat", "You can sail away with this lil' boat, but it looks damaged. With some quick repairs it could work.", UNPICKABLE);
	main_deck->containedEntities.push_back(boat);

	//Storage of all entities in World class container
	worldEntities.push_back(storagekey);
	worldEntities.push_back(spyglass);
	worldEntities.push_back(woodplank);
	worldEntities.push_back(bag);
	worldEntities.push_back(bottle);
	worldEntities.push_back(oranges);
	worldEntities.push_back(nails);
	worldEntities.push_back(hammer);
	worldEntities.push_back(letter);
	worldEntities.push_back(sword);
	worldEntities.push_back(sails);
	worldEntities.push_back(helm);
	worldEntities.push_back(boat);
	worldEntities.push_back(sleeping_quarters);
	worldEntities.push_back(poopdeck);
	worldEntities.push_back(crows_nest);
	worldEntities.push_back(storage_room);
	worldEntities.push_back(main_deck);
	worldEntities.push_back(mainguy);
	worldEntities.push_back(badguy);
}

World::~World()
{
	for (vector<Entity*>::iterator it = worldEntities.begin(); it != worldEntities.end(); ++it)
		delete *it;

	worldEntities.clear();

	delete badguy;
	delete mainguy;
}

//Reads user input and checks if its time to update the world (NPC Behaviour).
bool World::worldTurn(vector<string> &userInput)
{
	clock_t timeChecker = clock();
	if ((double)(timeChecker - worldTimer) > turnTime)
	{
		updateWorld();
		worldTimer = timeChecker;
	}

	if (userInput.size() > 0)
	{
		std::cout << endl;
		cout << "---------------------------------------------" << endl;
		readInput(userInput);
		return true;
	}
	else
	{
		return false;
	}
}

//Updates the status of the world (Calls for NPC behaviours)
const void World::updateWorld()
{
	if (badguy->alive)
	{
		if (!badguy->aware)
		{
			badguy->checkShip(mainguy->location);
			if (badguy->aware)	mainguy->trapped = true;
		}
		else
		{
			if (turnTime > 5000.0) turnTime = turnTime - 1000.0;
			badguy->getMad(mainguy->location);
		}
	}
	else
	{
		mainguy->trapped = false;
	}
}

//Input reading and calls for player actions
void World::readInput(vector<string> &userInput)
{
	switch ( userInput.size() )
	{
		case 1:
			if (userInput[0] == "Look")
			{
				mainguy->Look();
			}
			else if (userInput[0] == "Inventory")
			{
				mainguy->Inventory();
			}
			else if (userInput[0] == "Exits")
			{
				mainguy->Exits();
			}
			else if (userInput[0] == "Attack")
			{
				if (badguy->alive)
					mainguy->Attack(badguy);
				else
					std::cout << "That's not necessary anymore, butcher..." << endl << ">";
			}
			else
			{
				cout << "I didn't understand you, mate";
				cout << std::endl;
				cout << "---------------------------------------------" << endl;
				cout << ">";
			}
			break;

		case 2:
			if (userInput[0] == "Go")
			{
				if (userInput[1] == "north")
				{
					if (mainguy->Go(north)) mainguy->Look();
				}
				else if (userInput[1] == "south")
				{
					if (mainguy->Go(south)) mainguy->Look();
				}
				else if (userInput[1] == "east")
				{
					if (mainguy->Go(east)) mainguy->Look();
				}
				else if (userInput[1] == "west")
				{
					if (mainguy->Go(west)) mainguy->Look();
				}
				else if (userInput[1] == "up")
				{
					if (mainguy->Go(up)) mainguy->Look();
				}
				else if (userInput[1] == "down")
				{
					if (mainguy->Go(down)) mainguy->Look();
				}
				else
				{
					cout << "That's not a valid direction!";
					cout << std::endl;
					cout << "---------------------------------------------" << endl;
					cout << ">";
				}
			}
			else if (userInput[0] == "Unlock")
			{
				mainguy->Unlock(userInput[1].c_str());
			}
			else if (userInput[0] == "Pick")
			{
				mainguy->PickUp(userInput[1].c_str());
			}
			else if (userInput[0] == "Drop")
			{
				mainguy->Drop(userInput[1].c_str());
			}
			else if (userInput[0] == "Check")
			{
				mainguy->CheckItem(userInput[1].c_str());
			}
			else if (userInput[0] == "Repair")
			{
				mainguy->Repair(userInput[1].c_str());
			}
			else
			{
				cout << "I didn't understand you, mate";
				cout << std::endl;
				cout << "---------------------------------------------" << endl;
				cout << ">";
			}
			break;

		case 4:
			if (userInput[0] == "Use")
			{
				mainguy->Use(userInput[1].c_str(), userInput[3].c_str());
			}
			else if (userInput[0] == "Put")
			{
				mainguy->Put(userInput[1].c_str(), userInput[3].c_str());
			}
			else
			{
				cout << "I didn't understand you, mate";
				cout << std::endl;
				cout << "---------------------------------------------" << endl;
				cout << ">";
			}
			break;

		default:
			cout << "I didn't understand you, mate";
			cout << std::endl;
			cout << "---------------------------------------------" << endl;
			cout << ">";
			break;
	}
}

//Ending flavour text with conditionals
const void World::ending()
{
	if (badguy->shot)
	{
		std::cout << "Tired of you, and beeing the cruel pirate he is, Slinger does not think twice before making sure you won't disobey again." << std::endl;
		std::cout << "The last thing you listen is a loud sound. And then, all black." << std::endl;
		std::cout << "Davy Jones be with you. YOU DIED." << std::endl;
	}
	else if (badguy->alive)
	{
		std::cout << "You managed to move fast and silently enough to get out of there with the boat without Slinger beeing able to stop you!" << std::endl;
		std::cout << "Yeah. But did you really think that the lookout is someone with enough bad aiming to not be able of stopping this situation?" << std::endl;
		std::cout << "The last thing you listen is a loud sound. And then, all black." << std::endl;
		std::cout << "Davy Jones be with you. YOU DIED." << std::endl;
	}
	else
	{
		if (mainguy->helmDamaged && mainguy->sailsDamaged)
		{
			std::cout << "You take the boat in the silence of the night and sail away!" << std::endl;
			std::cout << "Thankfully, you where smart enough to make sure that the ship was damaged enough." << std::endl;
			std::cout << "When the Captain woke up and saw the lookout missing, the ship damaged and the letter not in his pocket, he panicked and tried to escape the ship." << std::endl;
			std::cout << "Let's hope the rest of the crew noticed it and did something, because he's the only one that knows for sure who destroyed his plans..." << std::endl;
		}
		else
		{
			std::cout << "You take the boat in the silence of the night and sail away!" << std::endl;
			std::cout << "But you did not think about something. The ship sailed to port without any problem, where all your crew was captured by the Navy." << std::endl;
			std::cout << "Only your old Captain survided and is now a very influential man. Let's hope he do not uses that power to look for you..." << std::endl;
		}
		if (mainguy->Find("Spyglass"))
		{
			std::cout << "Because you took the Spyglass with you, you could see an island and sail there, where you finally escaped. Good job!! Davy Jones smiles at you, lad!" << std::endl;
		}
		else
		{
			std::cout << "Sadly, you did not take a Spyglass with you. Getting in a boat in the middle of the sea is a real problem when you don't know where to go." << std::endl;
			std::cout << "Look at the bright side! Now you're the captain of your own ship! At least while you have something to eat..." << std::endl;
		}
	}
}<commit_msg>Modified the direction of two exits and one ending<commit_after>#include <iostream>
#include <algorithm>
#include "world.h"
#include "room.h"
#include "exit.h"
#include "item.h"

using namespace std;

World::World()
{
	//Initializing turnTime to allow modifications later
	turnTime = 13000.0;

	//Room Creation
	Room* sleeping_quarters = new Room("Sleeping quarters", "It's kinda dark, and everyone is sleeping. You should not wake anyone...");
	Room* main_deck = new Room("Main deck", "The main deck of the ship. It's very peacefull at night, and you hear the waves hitting the ship. A light can be seen up, in the Crow's nest.");
	Room* storage_room = new Room("Storage room", "A couple of handy materials, food and general things. Everything the crew loots ends up here.");
	Room* poopdeck = new Room("Poopdeck", "The rest of the ship can be seen from this position and the helm is resting in front of you, without anyone moving it at night.");
	Room* crows_nest = new Room("Crow's nest", "The lookouts' favourite place. The salty wind goes through you, slightly cold. You can see everything from here.");

	//Exit creation and storage
	Exit* exit1 = new Exit(up, sleeping_quarters, main_deck, false, "none");
	sleeping_quarters->exits.push_back(exit1);
	Exit* exit2 = new Exit(down, main_deck, sleeping_quarters, false, "none");
	main_deck->exits.push_back(exit2);
	Exit* exit3 = new Exit(west, sleeping_quarters, storage_room, true, "Key");
	sleeping_quarters->exits.push_back(exit3);
	Exit* exit4 = new Exit(east, storage_room, sleeping_quarters, false, "none");
	storage_room->exits.push_back(exit4);
	Exit* exit5 = new Exit(up, main_deck, crows_nest, false, "none");
	main_deck->exits.push_back(exit5);
	Exit* exit6 = new Exit(down, crows_nest, main_deck, false, "none");
	crows_nest->exits.push_back(exit6);
	Exit* exit7 = new Exit(south, main_deck, poopdeck, false, "none");
	main_deck->exits.push_back(exit7);
	Exit* exit8 = new Exit(north, poopdeck, main_deck, false, "none");
	poopdeck->exits.push_back(exit8);

	//Player and Badguy creation
	mainguy = new Player("Zelleryon", "A young, untrained but clever pirate", sleeping_quarters);
	badguy = new Npc("Slinger", "The cruel and harsh lookout of the ship.", crows_nest);

	//Item creation and storage - Pickable
	Item* sword = new Item("Cutlass", "A slightly old, ugly but effective weapon.", USABLE);
	sleeping_quarters->containedEntities.push_back(sword);
	Item* letter = new Item("Letter", "[...] By our majesty's name, this letter will serve as a forgiveness for the former pirate Joe 'Hound' Emmerick [...] surrendering of his whole crew to the navy [...] crew will be hanged with no possibility of trial. Signed: Admiral Robert Blake.", SIMPLE);
	sleeping_quarters->containedEntities.push_back(letter);
	Item* hammer = new Item("Hammer", "A small hammer. Nothing special.", USABLE);
	poopdeck->containedEntities.push_back(hammer);
	Item* nails = new Item("Nails", "Wood nails. As simple as that.", SIMPLE);
	storage_room->containedEntities.push_back(nails);
	Item* oranges = new Item("Oranges", "The favorite defense of all pirates against scurvy! Pretty tasty, too.", FOOD);
	storage_room->containedEntities.push_back(oranges);
	Item* bottle = new Item("Water", "A small bottle of water. This could be perfect for the trip.", FOOD);
	crows_nest->containedEntities.push_back(bottle);
	Item* bag = new Item("Bag", "A small bag. It can be used to carry something.", CONTAINER);
	poopdeck->containedEntities.push_back(bag);
	Item* woodplank = new Item("Plank", "A pretty solid plank. Could be used to close a door or cover something damaged.", SIMPLE);
	storage_room->containedEntities.push_back(woodplank);
	Item* spyglass = new Item("Spyglass", "An old spyglass stolen from the lookout.", SIMPLE);
	crows_nest->containedEntities.push_back(spyglass);
	Item* storagekey = new Item("Key", "The key of the Storage room.", SIMPLE);
	crows_nest->containedEntities.push_back(storagekey);

	//Item creation and storage - UnPickable
	Item* sails = new Item("Sails", "The sails of the ship. You can see the ropes that hold them together on the sides.", UNPICKABLE);
	main_deck->containedEntities.push_back(sails);
	Item* helm = new Item("Helm", "The device taking care of controling the direction of the ship. Would be a shame if someone messes with it...", UNPICKABLE);
	poopdeck->containedEntities.push_back(helm);
	Item* boat = new Item("Boat", "You can sail away with this lil' boat, but it looks damaged. With some quick repairs it could work.", UNPICKABLE);
	main_deck->containedEntities.push_back(boat);

	//Storage of all entities in World class container
	worldEntities.push_back(storagekey);
	worldEntities.push_back(spyglass);
	worldEntities.push_back(woodplank);
	worldEntities.push_back(bag);
	worldEntities.push_back(bottle);
	worldEntities.push_back(oranges);
	worldEntities.push_back(nails);
	worldEntities.push_back(hammer);
	worldEntities.push_back(letter);
	worldEntities.push_back(sword);
	worldEntities.push_back(sails);
	worldEntities.push_back(helm);
	worldEntities.push_back(boat);
	worldEntities.push_back(sleeping_quarters);
	worldEntities.push_back(poopdeck);
	worldEntities.push_back(crows_nest);
	worldEntities.push_back(storage_room);
	worldEntities.push_back(main_deck);
	worldEntities.push_back(mainguy);
	worldEntities.push_back(badguy);
}

World::~World()
{
	for (vector<Entity*>::iterator it = worldEntities.begin(); it != worldEntities.end(); ++it)
		delete *it;

	worldEntities.clear();

	delete badguy;
	delete mainguy;
}

//Reads user input and checks if its time to update the world (NPC Behaviour).
bool World::worldTurn(vector<string> &userInput)
{
	clock_t timeChecker = clock();
	if ((double)(timeChecker - worldTimer) > turnTime)
	{
		updateWorld();
		worldTimer = timeChecker;
	}

	if (userInput.size() > 0)
	{
		std::cout << endl;
		cout << "---------------------------------------------" << endl;
		readInput(userInput);
		return true;
	}
	else
	{
		return false;
	}
}

//Updates the status of the world (Calls for NPC behaviours)
const void World::updateWorld()
{
	if (badguy->alive)
	{
		if (!badguy->aware)
		{
			badguy->checkShip(mainguy->location);
			if (badguy->aware)	mainguy->trapped = true;
		}
		else
		{
			if (turnTime > 5000.0) turnTime = turnTime - 1000.0;
			badguy->getMad(mainguy->location);
		}
	}
	else
	{
		mainguy->trapped = false;
	}
}

//Input reading and calls for player actions
void World::readInput(vector<string> &userInput)
{
	switch ( userInput.size() )
	{
		case 1:
			if (userInput[0] == "Look")
			{
				mainguy->Look();
			}
			else if (userInput[0] == "Inventory")
			{
				mainguy->Inventory();
			}
			else if (userInput[0] == "Exits")
			{
				mainguy->Exits();
			}
			else if (userInput[0] == "Attack")
			{
				if (badguy->alive)
					mainguy->Attack(badguy);
				else
					std::cout << "That's not necessary anymore, butcher..." << endl << ">";
			}
			else
			{
				cout << "I didn't understand you, mate";
				cout << std::endl;
				cout << "---------------------------------------------" << endl;
				cout << ">";
			}
			break;

		case 2:
			if (userInput[0] == "Go")
			{
				if (userInput[1] == "north")
				{
					if (mainguy->Go(north)) mainguy->Look();
				}
				else if (userInput[1] == "south")
				{
					if (mainguy->Go(south)) mainguy->Look();
				}
				else if (userInput[1] == "east")
				{
					if (mainguy->Go(east)) mainguy->Look();
				}
				else if (userInput[1] == "west")
				{
					if (mainguy->Go(west)) mainguy->Look();
				}
				else if (userInput[1] == "up")
				{
					if (mainguy->Go(up)) mainguy->Look();
				}
				else if (userInput[1] == "down")
				{
					if (mainguy->Go(down)) mainguy->Look();
				}
				else
				{
					cout << "That's not a valid direction!";
					cout << std::endl;
					cout << "---------------------------------------------" << endl;
					cout << ">";
				}
			}
			else if (userInput[0] == "Unlock")
			{
				mainguy->Unlock(userInput[1].c_str());
			}
			else if (userInput[0] == "Pick")
			{
				mainguy->PickUp(userInput[1].c_str());
			}
			else if (userInput[0] == "Drop")
			{
				mainguy->Drop(userInput[1].c_str());
			}
			else if (userInput[0] == "Check")
			{
				mainguy->CheckItem(userInput[1].c_str());
			}
			else if (userInput[0] == "Repair")
			{
				mainguy->Repair(userInput[1].c_str());
			}
			else
			{
				cout << "I didn't understand you, mate";
				cout << std::endl;
				cout << "---------------------------------------------" << endl;
				cout << ">";
			}
			break;

		case 4:
			if (userInput[0] == "Use")
			{
				mainguy->Use(userInput[1].c_str(), userInput[3].c_str());
			}
			else if (userInput[0] == "Put")
			{
				mainguy->Put(userInput[1].c_str(), userInput[3].c_str());
			}
			else
			{
				cout << "I didn't understand you, mate";
				cout << std::endl;
				cout << "---------------------------------------------" << endl;
				cout << ">";
			}
			break;

		default:
			cout << "I didn't understand you, mate";
			cout << std::endl;
			cout << "---------------------------------------------" << endl;
			cout << ">";
			break;
	}
}

//Ending flavour text with conditionals
const void World::ending()
{
	if (badguy->shot)
	{
		std::cout << "Tired of you, and beeing the cruel pirate he is, Slinger does not think twice before making sure you won't disobey again." << std::endl;
		std::cout << "The last thing you listen is a loud sound. And then, all black." << std::endl;
		std::cout << "Davy Jones be with you. YOU DIED." << std::endl;
	}
	else if (badguy->alive)
	{
		std::cout << "You managed to move fast and silently enough to get out of there with the boat without Slinger beeing able to stop you!" << std::endl;
		std::cout << "Yeah. But did you really think that the lookout is someone with enough bad aiming to not be able of stopping this situation?" << std::endl;
		std::cout << "The last thing you listen is a loud sound. And then, all black." << std::endl;
		std::cout << "Davy Jones be with you. YOU DIED." << std::endl;
	}
	else
	{
		if (mainguy->helmDamaged && mainguy->sailsDamaged)
		{
			std::cout << "You take the boat in the silence of the night and sail away!" << std::endl;
			std::cout << "Thankfully, you where smart enough to make sure that the ship was damaged enough." << std::endl;
			std::cout << "When the Captain woke up and saw the lookout missing, the ship damaged and the letter not in his pocket, he panicked and tried to escape the ship." << std::endl;
			std::cout << "Let's hope the rest of the crew noticed it and did something, because he's the only one that knows for sure who destroyed his plans..." << std::endl;
		}
		else
		{
			std::cout << "You take the boat in the silence of the night and sail away!" << std::endl;
			std::cout << "But you did not think about something. The ship sailed to port without any problem, where all your crew was captured by the Navy." << std::endl;
			std::cout << "Only your old Captain survided and is now a very influential man. Let's hope he do not uses that power to look for you..." << std::endl;
		}
		if (mainguy->fullBag && mainguy->Find("Spyglass"))
		{
			std::cout << "Because you took the Spyglass with you, you could see an island and sail there. With your bag of supplies, you sustained yourself enough to reach it, where you finally escaped. Good job!! Davy Jones smiles at you, lad!" << std::endl;
		}
		else
		{
			std::cout << "Sadly, you thought that the sea was going to have mercy on you. To be sure to reach a safe pleace you need to SEE where are you leading and have ENOUGH SUPPLIES to reach it. Without one of them ..." << std::endl;
			std::cout << "Sadly, you did not take a Spyglass with you. Getting in a boat in the middle of the sea is a real problem when you don't know where to go and " << std::endl;
			std::cout << "But well, look at the bright side! Now you're the captain of your own ship! At least while you have something to eat..." << std::endl;
		}
	}
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: datasourceconverter.cxx,v $
 *
 * $Revision: 1.2 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/drawingml/chart/datasourceconverter.hxx"
#include <com/sun/star/chart2/XChartDocument.hpp>
#include "oox/drawingml/chart/chartconverter.hxx"
#include "oox/drawingml/chart/datasourcemodel.hxx"

using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::chart2::data::XDataSequence;

namespace oox {
namespace drawingml {
namespace chart {

// ============================================================================

DataSequenceConverter::DataSequenceConverter( const ConverterRoot& rParent, DataSequenceModel& rModel ) :
    ConverterBase< DataSequenceModel >( rParent, rModel )
{
}

DataSequenceConverter::~DataSequenceConverter()
{
}

Reference< XDataSequence > DataSequenceConverter::createDataSequence( const OUString& rRole )
{
    // create data sequence from formula (virtual call at chart converter)
    Reference< XDataSequence > xDataSeq;
    if( mrModel.maFormula.getLength() > 0 )
        xDataSeq = getChartConverter().createDataSequence( getChartDocument()->getDataProvider(), mrModel.maFormula );

    // TODO: create data sequence from literal data

    // set sequence role
    PropertySet aSeqProp( xDataSeq );
    aSeqProp.setProperty( CREATE_OUSTRING( "Role" ), rRole );

    return xDataSeq;
}

// ============================================================================

DataSourceConverter::DataSourceConverter( const ConverterRoot& rParent, DataSourceModel& rModel ) :
    ConverterBase< DataSourceModel >( rParent, rModel )
{
}

DataSourceConverter::~DataSourceConverter()
{
}

Reference< XDataSequence > DataSourceConverter::createDataSequence( const OUString& rRole )
{
    Reference< XDataSequence > xDataSeq;
    if( mrModel.mxDataSeq.is() )
    {
        DataSequenceConverter aDataSeqConv( *this, *mrModel.mxDataSeq );
        xDataSeq = aDataSeqConv.createDataSequence( rRole );
    }
    return xDataSeq;
}

// ============================================================================

} // namespace chart
} // namespace drawingml
} // namespace oox

<commit_msg>INTEGRATION: CWS xmlfilter06 (1.2.6); FILE MERGED 2008/06/24 14:03:14 dr 1.2.6.2: axis number formats, constant series source data 2008/05/27 10:40:38 dr 1.2.6.1: joined changes from CWS xmlfilter05<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: datasourceconverter.cxx,v $
 *
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/drawingml/chart/datasourceconverter.hxx"
#include <com/sun/star/chart2/XChartDocument.hpp>
#include "oox/drawingml/chart/chartconverter.hxx"
#include "oox/drawingml/chart/datasourcemodel.hxx"

using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::chart2::data::XDataSequence;

namespace oox {
namespace drawingml {
namespace chart {

// ============================================================================

DataSequenceConverter::DataSequenceConverter( const ConverterRoot& rParent, DataSequenceModel& rModel ) :
    ConverterBase< DataSequenceModel >( rParent, rModel )
{
}

DataSequenceConverter::~DataSequenceConverter()
{
}

Reference< XDataSequence > DataSequenceConverter::createDataSequence( const OUString& rRole )
{
    // create data sequence from data source model (virtual call at chart converter)
    Reference< XDataSequence > xDataSeq = getChartConverter().createDataSequence( getChartDocument()->getDataProvider(), mrModel );

    // set sequence role
    PropertySet aSeqProp( xDataSeq );
    aSeqProp.setProperty( CREATE_OUSTRING( "Role" ), rRole );

    return xDataSeq;
}

// ============================================================================

DataSourceConverter::DataSourceConverter( const ConverterRoot& rParent, DataSourceModel& rModel ) :
    ConverterBase< DataSourceModel >( rParent, rModel )
{
}

DataSourceConverter::~DataSourceConverter()
{
}

Reference< XDataSequence > DataSourceConverter::createDataSequence( const OUString& rRole )
{
    Reference< XDataSequence > xDataSeq;
    if( mrModel.mxDataSeq.is() )
    {
        DataSequenceConverter aDataSeqConv( *this, *mrModel.mxDataSeq );
        xDataSeq = aDataSeqConv.createDataSequence( rRole );
    }
    return xDataSeq;
}

// ============================================================================

} // namespace chart
} // namespace drawingml
} // namespace oox

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: orienthelper.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 15:03:32 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SVX_ORIENTHELPER_HXX
#define SVX_ORIENTHELPER_HXX

#include <memory>

#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef SFX_ITEMCONNECT_HXX
#include <sfx2/itemconnect.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class NumericField;
class CheckBox;

namespace svx {

class DialControl;

// ============================================================================

struct OrientationHelper_Impl;

/** A helper class that manages a DialControl and a "Stacked text" check box.

    This helper remembers a DialControl for entering a rotation angle, and a
    check box for stacked text, that enables/disables other controls dependent
    on its state.

    It is possible to register more controls that have to be enabled/disabled
    together with this helper object (optionally dependent on the stacked text
    check box), using the function AddDependentWindow(). All registered windows
    are handled on a call of Enable(), or Show(), or on changing the state of
    the "Stacked text" check box.

    Note: The member function SetStackedState() should be used instead of
    direct modifications of the "Stacked text" check box. Otherwise the update
    mechanism of registered controls will not work.
 */
class SVX_DLLPUBLIC OrientationHelper : public Window
{
public:
    explicit            OrientationHelper(
                            Window* pParent,
                            DialControl& rCtrlDial,
                            CheckBox& rCbStacked );

    /** @param rNfRotation  A numeric field that will be connected to the DialControl. */
    explicit            OrientationHelper(
                            Window* pParent,
                            DialControl& rCtrlDial,
                            NumericField& rNfRotation,
                            CheckBox& rCbStacked );

    virtual             ~OrientationHelper();

    /** Handles Enable/Show events for all registered windows. */
    virtual void        StateChanged( StateChangedType nStateChange );

    /** Registers the passed window to be enabled/disabled on call of Enable().
        @param eDisableIfStacked
        STATE_CHECK:    Window always disabled, if stacked text is turned on.
        STATE_NOCHECK:  Window always disabled, if stacked text is turned off.
        STATE_DONTKNOW: Window will be enabled/disabled independent from stacked text. */
    void                AddDependentWindow( Window& rWindow, TriState eDisableIfStacked = STATE_DONTKNOW );

    /** Sets the "stacked" check box to the passed state and updates dependent controls. */
    void                SetStackedState( TriState eState );
    /** Returns the state of the "stacked" check box. */
    TriState            GetStackedState() const;

    /** Enables/disables the "don't know" state of the "Stacked text" check box. */
    void                EnableStackedTriState( bool bEnable = true );

private:
    std::auto_ptr< OrientationHelper_Impl > mpImpl;
};

// ============================================================================

/** Wrapper for usage of the stacked attribute of an OrientationHelper in item connections. */
class SVX_DLLPUBLIC OrientStackedWrapper : public sfx::SingleControlWrapper< OrientationHelper, bool >
{
public:
    explicit            OrientStackedWrapper( OrientationHelper& rOrientHlp );

    virtual bool        IsControlDontKnow() const;
    virtual void        SetControlDontKnow( bool bSet );

    virtual bool        GetControlValue() const;
    virtual void        SetControlValue( bool bValue );
};

// ----------------------------------------------------------------------------

/** An item<->control connection for the stacked attribute of an OrientationHelper. */
typedef sfx::ItemControlConnection< sfx::BoolItemWrapper, OrientStackedWrapper > OrientStackedConnection;

// ============================================================================

} // namespace

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.430); FILE MERGED 2005/09/05 14:15:55 rt 1.3.430.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: orienthelper.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:14:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SVX_ORIENTHELPER_HXX
#define SVX_ORIENTHELPER_HXX

#include <memory>

#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef SFX_ITEMCONNECT_HXX
#include <sfx2/itemconnect.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class NumericField;
class CheckBox;

namespace svx {

class DialControl;

// ============================================================================

struct OrientationHelper_Impl;

/** A helper class that manages a DialControl and a "Stacked text" check box.

    This helper remembers a DialControl for entering a rotation angle, and a
    check box for stacked text, that enables/disables other controls dependent
    on its state.

    It is possible to register more controls that have to be enabled/disabled
    together with this helper object (optionally dependent on the stacked text
    check box), using the function AddDependentWindow(). All registered windows
    are handled on a call of Enable(), or Show(), or on changing the state of
    the "Stacked text" check box.

    Note: The member function SetStackedState() should be used instead of
    direct modifications of the "Stacked text" check box. Otherwise the update
    mechanism of registered controls will not work.
 */
class SVX_DLLPUBLIC OrientationHelper : public Window
{
public:
    explicit            OrientationHelper(
                            Window* pParent,
                            DialControl& rCtrlDial,
                            CheckBox& rCbStacked );

    /** @param rNfRotation  A numeric field that will be connected to the DialControl. */
    explicit            OrientationHelper(
                            Window* pParent,
                            DialControl& rCtrlDial,
                            NumericField& rNfRotation,
                            CheckBox& rCbStacked );

    virtual             ~OrientationHelper();

    /** Handles Enable/Show events for all registered windows. */
    virtual void        StateChanged( StateChangedType nStateChange );

    /** Registers the passed window to be enabled/disabled on call of Enable().
        @param eDisableIfStacked
        STATE_CHECK:    Window always disabled, if stacked text is turned on.
        STATE_NOCHECK:  Window always disabled, if stacked text is turned off.
        STATE_DONTKNOW: Window will be enabled/disabled independent from stacked text. */
    void                AddDependentWindow( Window& rWindow, TriState eDisableIfStacked = STATE_DONTKNOW );

    /** Sets the "stacked" check box to the passed state and updates dependent controls. */
    void                SetStackedState( TriState eState );
    /** Returns the state of the "stacked" check box. */
    TriState            GetStackedState() const;

    /** Enables/disables the "don't know" state of the "Stacked text" check box. */
    void                EnableStackedTriState( bool bEnable = true );

private:
    std::auto_ptr< OrientationHelper_Impl > mpImpl;
};

// ============================================================================

/** Wrapper for usage of the stacked attribute of an OrientationHelper in item connections. */
class SVX_DLLPUBLIC OrientStackedWrapper : public sfx::SingleControlWrapper< OrientationHelper, bool >
{
public:
    explicit            OrientStackedWrapper( OrientationHelper& rOrientHlp );

    virtual bool        IsControlDontKnow() const;
    virtual void        SetControlDontKnow( bool bSet );

    virtual bool        GetControlValue() const;
    virtual void        SetControlValue( bool bValue );
};

// ----------------------------------------------------------------------------

/** An item<->control connection for the stacked attribute of an OrientationHelper. */
typedef sfx::ItemControlConnection< sfx::BoolItemWrapper, OrientStackedWrapper > OrientStackedConnection;

// ============================================================================

} // namespace

#endif

<|endoftext|>