/* ======================================================================== *\
!
!
!   Author(s): Ester Aliu, 2/2004 <aliu@ifae.es>
!   
!   Last Update: 6/2004
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
//  MIslandCalc
//
// The Island Calc task calculates the some islands parameters for each 
// of the events such as:
// 
//   - fIslNum             //  number of islands
//   - fIslId[577]         //  island Id
//   - fPixNum[20]         //  number of pixels in the island
//   - fSigToNoise[20]     //  signal to noise of the island
//   - fTime[20][577]      //  mean of the arrival time  
//   - fTimeSpread[20]     //  mean arrival time spread of the island
//   - fMeanX[20]          //  mean X position of the island
//   - fMeanY[20]          //  mean Y position of the island
//   - fDist[20]           //  dist between an island and the continent
//
// Input Containers:
//   MGeomCam
//   MCerPhotEvt
//   MPedestalCam
//   MArrivalTimeCam
//
// Output Containers:
//   MIslands
//
/////////////////////////////////////////////////////////////////////////////
#include "MIslandCalc.h"

#include <stdlib.h>       // atof					  
#include <fstream>        // ofstream, SavePrimitive

#include "MLog.h"
#include "MLogManip.h"

#include "MIslands.h"

#include "MParList.h"

#include "MGeomPix.h"
#include "MGeomCam.h"

#include "MCerPhotPix.h"
#include "MCerPhotEvt.h"

#include "MPedestalCam.h"
#include "MPedestalPix.h"

#include "MArrivalTimeCam.h"
#include "MArrivalTimePix.h"

ClassImp(MIslandCalc);


using namespace std;

// --------------------------------------------------------------------------
//
// Default constructor.
//
MIslandCalc::MIslandCalc(const char* name, const char* title)    
  : fIsl(NULL)
{
    fName  = name  ? name  : "MIslandCalc";
    fTitle = title ? title : "Calculate island parameters";
}


// --------------------------------------------------------------------------
Int_t MIslandCalc::PreProcess (MParList *pList)
{
    fCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
    if (!fCam)
    {
        *fLog << dbginf << "MGeomCam not found (no geometry information available)... aborting." << endl;
        return kFALSE;
    }

    fEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
    if (!fEvt)
    {
        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
        return kFALSE;
    }

    fPed = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
    if (!fPed)
      {
        *fLog << dbginf << "MPedestalCam not found... aborting." << endl;
        return kFALSE;
      }

    fTime = (MArrivalTimeCam*)pList->FindObject(AddSerialNumber("MArrivalTimeCam"));
    if (!fTime)
      {
        *fLog << dbginf << "MArrivalTimeCam not found... aborting." << endl;
        return kFALSE;
      }
   
    if (strlen(fIslName) > 0)
      {
	fIsl = (MIslands*)pList->FindCreateObj("MIslands", AddSerialNumber(fIslName));
	//cout << "kk1" << endl;
      }
    else
      {
      fIsl = (MIslands*)pList->FindCreateObj(AddSerialNumber("MIslands"));
      //cout << "kk2" << endl;
      }
    if (!fIsl)
      return kFALSE;
    
    return kTRUE;
}


Int_t MIslandCalc::Process()
{
  
  if (fIslandAlgorithm == 1)
    Calc1();
  
  if (fIslandAlgorithm == 2)
    Calc2();
  return kTRUE;  
   
}


Int_t MIslandCalc::Calc1(){
  
  
  /////////////////////////////
  //
  //        ALGORITHM # 1
  // counts the number of islands as you can see in 
  // the event display after doing the std image cleaning
  //
  /////////////////////////////
  
  Float_t  noise;
  Float_t  signal;

  Int_t    npix = 577;

  Int_t    sflag;
  Int_t    control;
  
  Int_t    nvect = 0;
  Int_t    fIslNum = 0;
 
  Int_t    vect[50][577];

  Int_t    zeros[50];
  
  for(Int_t m = 0; m < 50 ; m++)
    for(Int_t n = 0; n < npix ; n++)
	vect[m][n] = 0;
    
  for(Int_t n = 0; n < 50 ; n++)
    zeros[n] = 0;
  

  MCerPhotPix *pix;

  //loop over all pixels
  MCerPhotEvtIter Next(fEvt, kFALSE);
  
  while ((pix=static_cast<MCerPhotPix*>(Next())))
    {
      const Int_t idx = pix->GetPixId();

      const MGeomPix &gpix  = (*fCam)[idx];
      const Int_t    nnmax  = gpix.GetNumNeighbors();

      if( fEvt->IsPixelUsed(idx)) 
     	{
	  sflag = 0;
	  
	  for(Int_t j=0; j < nnmax ; j++)
	    {
	      const Int_t idx2 = gpix.GetNeighbor(j);
	      
	      if (idx2 < idx)
		{
		  for(Int_t k = 1; k <= nvect; k++)
		    {
		      if (vect[k][idx2] == 1)
			{
			  sflag = 1;
			  vect[k][idx] = 1;
			}
		    }
		}
	    }
	  
	  if (sflag == 0)
	    {
	      nvect++;
	      vect[nvect][idx] = 1;	     
	    }
	  
	}
    }
  
  fIslNum = nvect;
  
  
  // Repeated Chain Corrections

  
  for(Int_t i = 1; i <= nvect; i++)
    {
      for(Int_t j = i+1; j <= nvect; j++)
	{
	  control = 0;
	  for(Int_t k = 0; k < npix; k++)
	    {
	      if (vect[i][k] == 1 && vect[j][k] == 1)
		{
		  control = 1; 
		  break;
		}
	    }
	  if (control == 1)
	    {
	      for(Int_t k = 0; k < npix; k++)
		{
		  if(vect[j][k] == 1)
		    vect[i][k] = 1;
		  vect[j][k] = 0;
		  zeros[j] = 1;
		}	
	      fIslNum = fIslNum-1;	    
	    }
	  
	}
    }
  
  

  Int_t l = 1;
  Int_t numpixels;
  Int_t pixMAX = 0;
  Int_t idMAX = 1;

  for(Int_t i = 1;  i<= nvect ; i++)
    {
      numpixels = 0;

      if (zeros[i] == 0)
	{
	  for(Int_t k = 0; k<npix; k++)
	    {
	      vect[l][k] = vect[i][k];
	      if (vect[l][k] == 1)
		numpixels++;
	    }
	  if (numpixels>pixMAX)
	    {
	      pixMAX = numpixels;
	      idMAX = l;
	    }
	  l++;
	}
    }
  
  //the larger island will correspond to the 1st component of the vector

  for(Int_t k = 0; k<npix; k++) 
    {
      vect[nvect+1][k] = vect[1][k];
      vect[1][k] = vect[idMAX][k];
      vect[idMAX][k] = vect[nvect+1][k];
    }


  //set the number of islands in one event
  fIsl->SetIslNum(fIslNum);

  //examine each island...
  Int_t fPixNum[fIslNum];
  Float_t fSigToNoise[fIslNum];
  Float_t time[577];
  Float_t timeVariance[fIslNum];
  Float_t size, meanX, meanY, dist;

  //reset the "sets" functions
  if (fIslNum <1)
    fIsl->SetIslNum(0);

  for(Int_t i = 0; i<20 ;i++)
    {
      fIsl->SetPixNum(i,-1);
      fIsl->SetSigToNoise(i,-1);
      fIsl->SetTimeSpread(i,-1);
    
      for(Int_t idx = 0; idx<npix; idx++)
	{
	  fIsl->SetIslId(idx, -1);
	  fIsl->SetArrivalTime(i, idx, -1 );
	}
    }
 

  Float_t X = 0;
  Float_t Y = 0;
   
   for(Int_t i = 1; i<=fIslNum ; i++)
    {
      Int_t n = 0;
      Int_t ncore = 0;
      
      Float_t MIN = 10000;
      Float_t MAX = 0;

      signal = 0;
      noise = 0;

      size = 0;
      meanX = 0;
      meanY = 0;
      dist = 0;

      fPixNum[i-1] = 0;
      timeVariance[i-1] = 0;
      
      for(Int_t idx=0 ; idx<npix ; idx++)
	{
	  
	  MCerPhotPix *pix = fEvt->GetPixById(idx);
	  const MGeomPix &gpix2 = (*fCam)[pix->GetPixId()];
	  const MPedestalPix &ped  = (*fPed)[idx];
	  const MArrivalTimePix &timepix = (*fTime)[idx];
	  const Float_t nphot = pix->GetNumPhotons();

	  if (pix == NULL) break;
	    
	  if (vect[i][idx]==1){
	    
	    fPixNum[i-1]++;
	    signal += nphot * (fCam->GetPixRatio(idx));
	    noise += pow(ped.GetPedestalRms(),2);
	    
	    size += nphot;
	    meanX += nphot * gpix2.GetX();
	    meanY += nphot * gpix2.GetY();
	    
	    time[n] = timepix.IsLoGainUsed() ? timepix.GetArrivalTimeLoGain() : timepix.GetArrivalTimeHiGain();
	    
	    
	    if (fEvt->IsPixelCore(idx)){ 
	      
	      if (time[n] > MAX)
		MAX = time[n];
	      if (time[n] < MIN)
		MIN = time[n];
	      
	      ncore++;
	    }
	    
	    fIsl->SetIslId(idx, i-1);
	    fIsl->SetArrivalTime(i-1, idx, time[n]);
	   	
	    n++;
	  }
	  
	}

      meanX /= size;
      meanY /= size;
  
      if (i ==1){
	X = meanX;
	Y = meanY;
      }
    
      dist = TMath::Power(meanX-X,2) + TMath::Power(meanY-Y,2);
      dist = TMath::Sqrt(dist);

      timeVariance[i-1] = (MAX - MIN); 

      fSigToNoise[i-1]= (Float_t)signal/(Float_t)sqrt(noise);

      fIsl->SetPixNum(i-1,fPixNum[i-1]);
      fIsl->SetSigToNoise(i-1,fSigToNoise[i-1]);
      fIsl->SetTimeSpread(i-1, timeVariance[i-1]);
      fIsl->SetMeanX(i-1, meanX);
      fIsl->SetMeanY(i-1, meanY);
      fIsl->SetDist(i-1, dist);
      
    }
  
  fIsl->SetReadyToSave();
  
  return kTRUE;  
}


Int_t MIslandCalc::Calc2(){
  
  
  /////////////////////////////
  //
  //        ALGORITHM # 2
  // counts the number of islands considering as the same 
  // islands the ones separated for 2 or less pixels
  //
  /////////////////////////////
  
  Float_t  noise;
  Float_t  signal;

  Int_t    npix = 577;

  Int_t    sflag;
  Int_t    control;
  
  Int_t    nvect = 0;
  Int_t    fIslNum = 0;
 
  Int_t    vect[50][577];

  Int_t    zeros[50];
  
  Int_t kk[577];

  for(Int_t m = 0; m < 50 ; m++)
    for(Int_t n = 0; n < npix ; n++)
	vect[m][n] = 0;
    
  for(Int_t n = 0; n < 50 ; n++)
    zeros[n] = 0;
  
  for(Int_t n = 0; n < 577 ; n++)
    kk[n] = 0;
  
  MCerPhotPix *pix;

  //1st loop over all pixels
  MCerPhotEvtIter Next0(fEvt, kFALSE);
 
  while ((pix=static_cast<MCerPhotPix*>(Next0())))
    {
      const Int_t idx = pix->GetPixId();
      
      const MGeomPix &gpix  = (*fCam)[idx]; 
      const Int_t    nnmax  = gpix.GetNumNeighbors();

      if( fEvt->IsPixelUsed(idx))
	{
	  kk[idx] = 1 ;
	  for(Int_t j=0; j< nnmax; j++)
	    {
	      kk[gpix.GetNeighbor(j)] = 1;
	    }
	} 
      
    }
      
  //2nd loop over all pixels
  MCerPhotEvtIter Next(fEvt, kFALSE);
  
  while ((pix=static_cast<MCerPhotPix*>(Next())))
    {
      const Int_t idx = pix->GetPixId();
      
      const MGeomPix &gpix  = (*fCam)[idx];
      const Int_t    nnmax  = gpix.GetNumNeighbors();
      
      if ( kk[idx] > 0)
     	{
	  sflag = 0;
	  
	  for(Int_t j=0; j < nnmax ; j++)
	    {
	      const Int_t idx2 = gpix.GetNeighbor(j);
	      
	      if (idx2 < idx)
		{
		  for(Int_t k = 1; k <= nvect; k++)
		    {
		      if (vect[k][idx2] == 1)
			{
			  sflag = 1;
			  vect[k][idx] = 1;
			}
		    }
		}
	    }
	  
	  if (sflag == 0)
	    {
	      nvect++;
	      vect[nvect][idx] = 1;	     
	    }
	  
	}
    }
  
  fIslNum = nvect;
  
  
  // Repeated Chain Corrections
  
  for(Int_t i = 1; i <= nvect; i++)
    {
      for(Int_t j = i+1; j <= nvect; j++)
	{
	  control = 0;
	  for(Int_t k = 0; k < npix; k++)
	    {
	      
	      if (vect[i][k] == 1 && vect[j][k] == 1)
		{
		  control = 1; 
		  break;
		}
	    }
	  if (control == 1)
	    {
	      for(Int_t k = 0; k < npix; k++)
		{
		  if(vect[j][k] == 1)
		    vect[i][k] = 1;
		  vect[j][k] = 0;
		  zeros[j] = 1;
		}	
	      fIslNum = fIslNum-1;	    
	    }
	  
	}
    }
  
    
  Int_t l = 1;
  Int_t numpixels;
  Int_t pixMAX = 0;
  Int_t idMAX = 1;

  for(Int_t i = 1;  i<= nvect ; i++)
    {
      numpixels = 0;

      if (zeros[i] == 0)
	{
	  for(Int_t k = 0; k<npix; k++)
	    {
	      vect[l][k] = vect[i][k];
	      if (vect[l][k] == 1)
		numpixels++;
	    }
	  if (numpixels>pixMAX)
	    {
	      pixMAX = numpixels;
	      idMAX = l;
	    }
	  l++;
	}
    }
  
  
  //the larger island will correspond to the 1st component of the vector

  for(Int_t k = 0; k<npix; k++) 
    {
      vect[nvect+1][k] = vect[1][k];
      vect[1][k] = vect[idMAX][k];
      vect[idMAX][k] = vect[nvect+1][k];
    }
  

  //set the number of islands in one event
  fIsl->SetIslNum(fIslNum);

  //examine each island...
  Int_t fPixNum[fIslNum];
  Float_t fSigToNoise[fIslNum];
  Float_t time[577];
  Float_t timeVariance[fIslNum];
  Float_t size, meanX, meanY, dist;

  //reset the "sets" functions
  if (fIslNum <1)
    fIsl->SetIslNum(0);

  for(Int_t i = 0; i<20 ;i++)
    {
      fIsl->SetPixNum(i,-1);
      fIsl->SetSigToNoise(i,-1);
      fIsl->SetTimeSpread(i,-1);
    
      for(Int_t idx = 0; idx<npix; idx++)
	{
	  fIsl->SetIslId(idx, -1);
	  fIsl->SetArrivalTime(i, idx, -1 );
	}
    }
 

  Float_t X = 0;
  Float_t Y = 0;
   
   for(Int_t i = 1; i<=fIslNum ; i++)
    {
      Int_t n = 0;
      Int_t ncore = 0;
      
      Float_t MIN = 10000;
      Float_t MAX = 0;

      signal = 0;
      noise = 0;

      size = 0;
      meanX = 0;
      meanY = 0;
      dist = 0;

      fPixNum[i-1] = 0;
      timeVariance[i-1] = 0;
      
      for(Int_t idx=0 ; idx<npix ; idx++)
	{
	  
	  MCerPhotPix *pix = fEvt->GetPixById(idx);
	  const MGeomPix &gpix2 = (*fCam)[pix->GetPixId()];
	  const MPedestalPix &ped  = (*fPed)[idx];
	  const MArrivalTimePix &timepix = (*fTime)[idx];
	  const Float_t nphot = pix->GetNumPhotons();

	  if (pix == NULL) break;
	    
	  if (vect[i][idx]==1){
	    
	    fPixNum[i-1]++;
	    signal += nphot * (fCam->GetPixRatio(idx));
	    noise += pow(ped.GetPedestalRms(),2);
	    
	    size += nphot;
	    meanX += nphot * gpix2.GetX();
	    meanY += nphot * gpix2.GetY();
	    
	    time[n] = timepix.IsLoGainUsed() ? timepix.GetArrivalTimeLoGain() : timepix.GetArrivalTimeHiGain();
	    
	    
	    if (fEvt->IsPixelCore(idx)){ 
	      
	      if (time[n] > MAX)
		MAX = time[n];
	      if (time[n] < MIN)
		MIN = time[n];
	      
	      ncore++;
	    }
	    
	    fIsl->SetIslId(idx, i-1);
	    fIsl->SetArrivalTime(i-1, idx, time[n]);
	   	
	    n++;
	  }
	  
	}

      meanX /= size;
      meanY /= size;
  
      if (i ==1){
	X = meanX;
	Y = meanY;
      }
    
      dist = TMath::Power(meanX-X,2) + TMath::Power(meanY-Y,2);
      dist = TMath::Sqrt(dist);

      timeVariance[i-1] = (MAX - MIN); 

      fSigToNoise[i-1]= (Float_t)signal/(Float_t)sqrt(noise);

      fIsl->SetPixNum(i-1,fPixNum[i-1]);
      fIsl->SetSigToNoise(i-1,fSigToNoise[i-1]);
      fIsl->SetTimeSpread(i-1, timeVariance[i-1]);
      fIsl->SetMeanX(i-1, meanX);
      fIsl->SetMeanY(i-1, meanY);
      fIsl->SetDist(i-1, dist);
      
    }

     
  fIsl->SetReadyToSave();
  
  return 1;  
}
