//******************************************************************************************
// BinToStd_GammaAtCreation.C
// Root command file
// Type: root BinToStd_GammaAtCreation.C
//
// Read the output file GammaAtCreation.dat that is generated by Geant4
// tomography simulation It read all the gamma at creation information, and
// rewrite the events in a binary file PixeEvent_std_AtCreation.DAT
//
// More information is available in UserGuide
// Created by Z.LI LP2i Bordeaux 2022
//*******************************************************************************************

#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include <vector>
// using namespace std;

// Define a structure to read and write each event in the required binary format
struct PixeEvent
{
  uint16_t energy_10eV;
  uint16_t pixelIndex;
  uint16_t sliceIndex;
  uint8_t projectionIndex;
};
struct ParticleInfo
{
  float energy_keV;
  float mx;
  float my;
  float mz;
};

struct RunInfo
{
  // uint_16t
  uint8_t projectionIndex;  // 1 byte
  uint16_t sliceIndex;  //
  uint16_t pixelIndex;
  uint32_t nbParticle;  // 4 bytes int
};
struct Point
{
  double m_x;
  double m_y;
  double m_z;
};

// double DegreeToRadian(double degree) { return (PI * degree / 180.); }

bool IsDetected(Point poi1, Point poi2, double theta)
{
  double a = (poi1.m_x * poi2.m_x + poi1.m_y * poi2.m_y + poi1.m_z * poi2.m_z)
             / sqrt(poi1.m_x * poi1.m_x + poi1.m_y * poi1.m_y + poi1.m_z * poi1.m_z)
             / sqrt(poi2.m_x * poi2.m_x + poi2.m_y * poi2.m_y + poi2.m_z * poi2.m_z);
  if (a > 1.0) a = 1;
  if (a < -1.0) a = -1;
  double r = acos(a);
  if (r > theta)
    return false;
  else
    return true;
}
void BinToStd_GammaAtCreation()
{
  //***********************************************************************
  //**************************Detection parameters (begin)*****************
  //***********************************************************************

  const int nbProjection = 10;
  const int nbSlice = 1;
  const int nbPixel = 20;
  double totalAngleSpan = 180.;  // in degree

  double angleOfDetector = 135.;  // angle of detector relative to the incident
                                  // direction of the primary protons //
  double distanceObjectDetector = 22.;  // 22 mm
  double radiusOfDetector = 5.;  // 5 mm
  // double theta = atan(radiusOfDetector/distanceObjectDetector); //half apex
  // angle of the right circular cone in radian
  double theta = 70 * TMath::DegToRad();  // in radian

  //***********************************************************************
  //**************************Detection parameters (end)*******************
  //***********************************************************************

  FILE* input = fopen("../build/GammaAtCreation.dat", "rb");
  FILE* out = fopen("../build/PixeEvent_std_AtCreation.DAT", "wb");

  if (input == NULL) {
    printf("error for opening the input GammaAtCreation.dat file\n");
    return;
  }

  RunInfo runInfo;
  PixeEvent pixeEvent;
  Point centerOfDetector;
  Point gammaMomentum;
  long long count = 0;
  int runID = -1;  // index of simulations, namely runID, starting from 0

  // while(!feof(input)) //if not the end, read
  while (fread(&runInfo, sizeof(RunInfo), 1, input)) {
    runID++;
    // if(runID==5) continue;
    int nbParticle = runInfo.nbParticle;

    //(begin)*****************************************************************
    // the following codes are used only when in the simulation
    // the index of projection, slice and pixel is not
    // correctly configured
    runInfo.projectionIndex = runID / (nbSlice * nbPixel);
    int remain = runID % (nbSlice * nbPixel);
    runInfo.sliceIndex = remain / nbPixel;
    runInfo.pixelIndex = remain % nbPixel;
    //(end)******************************************************************

    //***********************************************************************
    //**************************Print information (begin)********************
    //***********************************************************************

    printf(
      "---------RunID=%d:\nProjectionIndex=%d, SliceIndex=%d, PixelIndex=%d,"
      "nbParticle = %d\n",
      runID, runInfo.projectionIndex, runInfo.sliceIndex, runInfo.pixelIndex, nbParticle);

    //***********************************************************************
    //**************************Print information (end)**********************
    //***********************************************************************

    if (!nbParticle) continue;
    std::vector<ParticleInfo> gammaAtCreation(nbParticle);
    fread(&gammaAtCreation[0], sizeof(ParticleInfo), nbParticle, input);

    // angleOfDetector+totalAngleSpan/nbProjection*runInfo.projectionIndex means
    // the angle between source direction and detector, which should be constant
    // when source is rotating
    double ra = TMath::DegToRad()
                * (angleOfDetector + totalAngleSpan / nbProjection * runInfo.projectionIndex);
    centerOfDetector.m_x = distanceObjectDetector * cos(ra);
    centerOfDetector.m_y = distanceObjectDetector * sin(ra);
    centerOfDetector.m_z = 0;

    for (int i = 0; i < nbParticle; ++i) {
      // gamma selection: energy should be lower than 4095*10eV = 49.45 keV
      if (gammaAtCreation[i].energy_keV >= 40.95 || gammaAtCreation[i].energy_keV <= 0.9)
        continue;  // gamma selection

      gammaMomentum.m_x = gammaAtCreation[i].mx;
      gammaMomentum.m_y = gammaAtCreation[i].my;
      gammaMomentum.m_z = gammaAtCreation[i].mz;

      if (!IsDetected(centerOfDetector, gammaMomentum, theta))
        continue;
      else {
        pixeEvent.energy_10eV = floor(100 * gammaAtCreation[i].energy_keV + 0.5);
        pixeEvent.projectionIndex = runInfo.projectionIndex;
        pixeEvent.sliceIndex = runInfo.sliceIndex;
        pixeEvent.pixelIndex = runInfo.pixelIndex;
        fwrite(&pixeEvent, 7, 1, out);
        count++;

        //***********************************************************************
        //**************************Print information (begin)********************
        //***********************************************************************

        // printf("momentum: (%f, %f, %f), energy: %f keV %d 10eV\n",
        // gammaAtCreation[i].mx, gammaAtCreation[i].my, gammaAtCreation[i].mz,
        // gammaAtCreation[i].energy_keV, pixeEvent.energy_10eV);

        //***********************************************************************
        //**************************Print information (end)**********************
        //***********************************************************************
      }
    }
  }
  printf(
    "---------------Number of PixeEvent in total: "
    "%lld------------------------\n",
    count);
  fclose(input);
  fclose(out);

  // Recheck the output file in case
  // FILE* input2 = fopen("PixeEvent_std_AtCreation.DAT","rb");
  // PixeEvent p;
  // while(fread(&p, 7, 1, input2))
  // {
  // printf("__ProjectionIndex=%d, SliceIndex=%d, PixelIndex=%d,
  // Energy_10eV=%d\n", p.projectionIndex, p.sliceIndex, p.pixelIndex,
  // p.energy_10eV);

  // }
  // fclose(input2);
}
