//=//////////////////////////////////////////////////////////////////////
//=
//= camera                
//=
//= @file        camera.h
//= @desc        Header file
//= @author      J C Gonzalez
//= @email       gonzalez@mppmu.mpg.de
//= @date        Thu May  7 16:24:22 1998
//=
//=----------------------------------------------------------------------
//=
//= Created: Thu May  7 16:24:22 1998
//= Author:  Jose Carlos Gonzalez
//= Purpose: Program for reflector simulation
//= Notes:   See files README for details
//=    
//=----------------------------------------------------------------------
//=
//= $RCSfile: timecam.h,v $
//= $Revision: 1.1.1.1 $
//= $Author: harald $ 
//= $Date: 2000-02-08 15:13:44 $
//=
//=//////////////////////////////////////////////////////////////////////

// @T \newpage

//!@section Source code of |camera.h|.

/*!@"

  This section shows the include file |camera.h|

  @"*/

//=-----------------------------------------------------------
//!@subsection Include files.

//!@{

#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <libgen.h>

#include "timecam-v.h"

#include "jcmacros.h"
#include "jcdebug.h"

#include "creadparam.h"
#include "atm.h"

#include "lagrange.h"

#include "MCEventHeader.hxx"
#include "MCCphoton.hxx"

// command line options available

#define COMMAND_LINE_OPTIONS    "f:h"

/*@'

  This is C++, but RANLIB routines are written in pure ANSI C.
  In order to read easily these routines, we must include
  the following directive
  
*/

extern "C" { 
#include "ranlib.h"       
}

// version of the reflector program that can read

#define REFL_PROGRAM reflector
#define REFL_VERSION 0.3

const char REFL_SIGNATURE[] = GLUE_postp( REFL_PROGRAM, REFL_VERSION );

//!@}

//=------------------------------------------------------------
//!@subsection Macro-definitions, and constants.

//!@{
#define SIN60   0.866025403784439
#define COS60   0.500000000000000

#define RandomNumber  drand48()

#define PIX_ARRAY_SIDE       40
#define PIX_ARRAY_HALF_SIDE  20
#define PIXNUM               0
#define PIXX                 1
#define PIXY                 2

#define iMAXNUMPIX  595 // total maximum possible number of pixels in the camera

//@ the trigger threshold up to which the maximum passable threshold is tested 
#define iMAX_THRESHOLD_PHE   50 

//@ number of the 1st. pixel of a sector s in a ring r (central pixel: ring=0)
#define FIRST_PIXEL(r,s)   ( ((r)>0) ? (3*(r)*((r)-1) + (r)*(s) + 1) : 0 )

//@ number of the pixels include in a camera of r pixels
#define NUMBER_PIXELS(r)   ( ((r)>0) ? FIRST_PIXEL((r)+1,0) : 1 )

//@ now we define the list CT_ITEM_LIST of possible items in the CT def. file
#define CT_ITEM_LIST  /* LIST OF ITEMS IN THE CT DEFINITION FILE */  \
T(type),              /* type of definition file */                  \
T(focal_distance),    /* std(focal distance) */                      \
T(focal_std),         /* focal distance */                           \
T(point_spread),      /* std(point spread)   */                      \
T(point_std),         /* point spread   */                           \
T(adjustment_dev),    /* std of adjustment deviation   */            \
T(black_spot),        /* radius of the black spot in center of mirror */ \
T(n_mirrors),         /* number of mirrors */                        \
T(r_mirror),          /* radius of one mirror */                     \
T(camera_width),      /* camera width */                             \
T(n_pixels),          /* total number of pixels in the camera */     \
T(n_centralpixels),   /* number of central pixels in the camera */   \
T(n_gappixels),       /* number of gap pixels in the camera */       \
T(pixel_width),       /* pixel width */                              \
T(define_mirrors)     /* this entry is followed by the def. of pixels */
  
#define T(x)  x               //@< define T() as the name as it is

enum CT_ITEM_TYPE {
  CT_ITEM_LIST
};

#undef T

#define T(x)  #x              //@< define T() as the string of x

const char *const CT_ITEM_NAMES[] = {
  CT_ITEM_LIST
};

#undef T


// TYPE=0  (CT1)
//     i   s   rho   theta   x   y   z   thetan  phin  xn   yn   zn
//
//      i : number of the mirror
//      s : arc length [cm]
//    rho : polar rho of the position of the center of the mirror [cm]
//  theta : polar angle of the position of the center of the mirror [cm]
//      x : x coordinate of the center of the mirror [cm]
//      y : y coordinate of the center of the mirror [cm]
//      z : z coordinate of the center of the mirror [cm]
// thetan : polar theta angle of the direction where the mirror points to
//   phin : polar phi angle of the direction where the mirror points to
//     xn : xn coordinate of the normal vector in the center (normalized)
//     yn : yn coordinate of the normal vector in the center (normalized)
//     zn : zn coordinate of the normal vector in the center (normalized)
//
// TYPE=1  (MAGIC)
//     i  f   sx   sy   x   y   z   thetan  phin 
//
//      i : number of the mirror
//      f : focal distance of that mirror
//     sx : curvilinear coordinate of mirror's center in X[cm]
//     sy : curvilinear coordinate of mirror's center in X[cm]
//      x : x coordinate of the center of the mirror [cm]
//      y : y coordinate of the center of the mirror [cm]
//      z : z coordinate of the center of the mirror [cm]
// thetan : polar theta angle of the direction where the mirror points to
//   phin : polar phi angle of the direction where the mirror points to
//     xn : xn coordinate of the normal vector in the center (normalized)
//     yn : yn coordinate of the normal vector in the center (normalized)
//     zn : zn coordinate of the normal vector in the center (normalized)

#define CT_I       0

#define CT_S       1
#define CT_RHO     2
#define CT_THETA   3

#define CT_FOCAL   1
#define CT_SX      2
#define CT_SY      3

#define CT_X       4
#define CT_Y       5
#define CT_Z       6
#define CT_THETAN  7
#define CT_PHIN    8
#define CT_XN      9
#define CT_YN     10
#define CT_ZN     11

#define CT_NDATA  12
 
//!@}

//=------------------------------------------------------------
//!@subsection data types

struct camera { /* camera parameters for imaging */
  int inumpixels;
  int inumcentralpixels;
  int inumgappixels;
  int inumbigpixels;
  double dpixdiameter_cm; /* diameter of the central and gap pixels in centimeters */
  double dpixsizefactor[iMAXNUMPIX]; /* size of the pixel relative to  dpixdiameter_deg */
  double dxc[iMAXNUMPIX]; /* Pixel coordinates in camera coordinate system (x points from pixel 1 to 2). */
  double dyc[iMAXNUMPIX]; /* The numbering of the pixels in these arrays starts at 0! */
  double dxpointcorr_deg; /* correction of the pixel coordinates; to be added to dxc[] to get correct value */
  double dypointcorr_deg; /* correction of the pixel coordinates; to be added to dxc[] to get correct value */
  double di[iMAXNUMPIX]; /* i coordinate in JCs bi-axis hexagonal coordinate system */
  double dj[iMAXNUMPIX]; /* j coordinate in JCs bi-axis hexagonal coordinate system */
 
};


//=------------------------------------------------------------
//!@subsection Pre-defined file names.

//!@{

#define QE_FILE     "../Data/qe.dat"

//!@}

//=------------------------------------------------------------
//!@subsection Prototypes of functions.

//!@{

//++
// prototypes
//--

#define ONoff(x)  ((x==TRUE) ? "[ ON ]" : "[ off]")

// Under Linux, the nint function does not exist, so we have to define it.
#define nint(x)  ((int)floor((x)+0.5))

void present(void);
void usage(void);
void clean(void);
void log(const char *funct, char *fmt, ...);
void error(const char *funct, char *fmt, ...);
int isA( char * s1, const char * flag );
void read_ct_file(void);
int igen_pixel_coordinates(struct camera *cam);
void read_pixels(struct camera *cam); 
int pixels_are_neig(int pix1, int pix2);
int bpoint_is_in_pix(double dx, double dy, int ipixnum, struct camera *pcam); 
float  dist_r_P(float a, float b, float c, 
                float l, float m, float n,
                float x, float y, float z);
     
//!@}

//=------------------------------------------------------------
//!@subsection Log of this file.

//!@{

/*
 *$Log: not supported by cvs2svn $
 *Revision 1.3  1999/11/11 20:29:29  harald
 *Small changes to run the new version on a linux machine.
 *
 *Revision 1.2  1999/11/10 07:42:41  harald
 *Small change to read the right data files in.
 *
 *Revision 1.1.1.1  1999/11/05 11:59:31  harald
 *This the starting point for CVS controlled further developments of the
 *camera program. The program was originally written by Jose Carlos. 
 *But here you can find a "rootified" version to the program. This means 
 *that there is no hbook stuff in it now. Also the output of the
 *program changed to the MagicRawDataFormat. 
 *
 *The "rootification" was done by Dirk Petry and Harald Kornmayer. 
 *
 *In the following you can see the README file of that version:
 *
 *==================================================
 *
 *Fri Oct 22  1999   D.P.
 *
 *The MAGIC Monte Carlo System
 *
 *Camera Simulation Programme
 *---------------------------
 *
 *1) Description
 *
 *This version is the result of the fusion of H.K.'s
 *root_camera which is described below (section 2)
 *and another version by D.P. which had a few additional
 *useful features.
 *
 *The version compiles under Linux with ROOT 2.22 installed
 *(variable ROOTSYS has to be set).
 *
 *Compile as before simply using "make" in the root_camera
 *directory.
 *
 *All features of H.K.'s root_camera were retained.
 *
 *Additional features of this version are:
 *
 *  a) HBOOK is no longer used and all references are removed.
 *
 *  b) Instead of HBOOK, the user is given now the possibility of 
 *     having Diagnostic data in ROOT format as a complement
 *     to the ROOT Raw data.
 *
 *     This data is written to the file which is determined by
 *     the new input parameter "diag_file" in the camera parameter
 *     file.
 *
 *     All source code file belonging to this part have filenames
 *     starting with "MDiag".
 *
 *     The user can read the output file using the following commands
 *     in an interactive ROOT session:
 *
 *       	root [0] .L MDiag.so
 *	root [1] new TFile("diag.root");
 *	root [2] new TTreeViewer("T");
 *	
 *     This brings up a viewer from which all variables of the
 *     TTree can be accessed and histogrammed. This example
 *     assumes that you have named the file "diag.root", that
 *     you are using ROOT version 2.22 or later and that you have
 *     the shared object library "MDiag.so" which is produced
 *     by the Makefile along with the executable "camera".
 *       
 * !   The contents of the so-called diag file is not yet fixed.
 * !   At the moment it is what J.C.G. used to put into the HBOOK
 * !   ntuple. In future versions the moments calculation can be
 * !   removed and the parameter list be modified correspondingly.
 *
 *  c) Now concatenated reflector files can be read. This is useful
 *     if you have run the reflector with different parameters but
 *     you want to continue the analysis with all reflector data
 *     going into ONE ROOT outputfile.
 *
 *     The previous camera version contained a bug which made reading 
 *     of two or more concatenated reflector files impossible.
 *
 *  d) The reflector output format was changed. It is now version
 *     0.4 .
 *     The change solely consists in a shortening of the flag
 *     definition in the file 
 *
 *           include-MC/MCCphoton.hxx  
 *
 * !   IF YOU WANT TO READ REFLECTOR FORMAT 0.3, you can easily
 * !   do so by recompiling camera with the previous version of
 * !   include-MC/MCCphoton.hxx.
 *
 *     The change was necessary for saving space and better
 *     debugging. From now on, this format can be frozen.
 *
 * !   For producing reflector output in the new format, you
 * !   of course have to recompile your reflector with the
 * !   new include-MC/MCCphoton.hxx .
 *
 *  e) A first version of the pixelization with the larger
 *     outer pixels is implemented. THIS IS NOT YET FULLY
 *     TESTED, but first rough tests show that it works
 *     at least to a good approximation.
 *
 *     The present version implements the camera outline
 *     with 18 "gap-pixels" and 595 pixels in total as
 *     shown in 
 *
 *        http://sarastro.ifae.es/internal/home/hardware/camera/numbering.ps
 *
 *     This change involved 
 *
 *	(i) The file pixels.dat is no longer needed. Instead
 *          the coordinates are generated by the program itself
 *          (takes maybe 1 second). In the file 
 *
 *		pixel-coords.txt
 *
 *	  in the same directory as this README, you find a list
 *          of the coordinates generated by this new routine. It
 *          has the format
 *
 *              number   i   j   x  y  size-factor
 *
 *          where i and j are J.C.G.'s so called biaxis hexagonal
 *          coordinates (for internal use) and x and y are the
 *          coordinates of the pixel centers in the standard camera
 *          coordinate system in units of centimeters. The value
 *          of "size-factor" determines the linear size of the pixel
 *          relative to the central pixels. 
 *
 *        (ii) The magic.def file has two additional parameters
 *          which give the number of central pixels and the
 *          number of gap pixels
 *
 *        (iii) In camera.h and camera.cxx several changes were 
 *          necessary, among them the introduction of several
 *          new functions 
 *
 *     The newly suggested outline with asymmetric Winston cones
 *     will be implemented in a later version.
 *
 *  f) phe files can no longer be read since this contradicts
 *     our philosophy that the analysis should be done with other
 *     programs like e.g. EVITA and not with "camera" itself.
 *     This possibility was removed. 
 *
 *  g) ROOT is no longer invoked with an interactive interface.
 *     In this way, camera can better be run as a batch program and
 *     it uses less memory.
 *
 *  h) small changes concerning the variable "t_chan" were necessary in
 *     order to avoid segmentation faults: The variable is used as an
 *     index and it went sometimes outside the limits when camera
 *     was reading proton data. This is because the reflector files
 *     don't contain the photons in a chronological order and also
 *     the timespread can be considerably longer that the foreseen
 *     digitisation timespan. Please see the source code of camera.cxx
 *     round about line 1090.
 *
 *  j) several unused variables were removed, a few warning messages
 *     occur when you compile camera.cxx but these can be ignored at
 *     the moment.
 *
 *In general the program is of course not finished. It still needs
 *debugging, proper trigger simulation, simulation of the asymmetric
 *version of the outer pixels, proper NSB simulation, adaption of
 *the diag "ntuple" contents to our need and others small improvements.
 *
 *In the directory rfl-files there is now a file in reflector format 0.4
 *containing a single event produced by the starfiled adder. It has
 *a duration of 30 ns and represents the region around the Crab Nebula.
 *Using the enclosed input parameter file, camera should process this
 *file without problems.
 *
 *2) The README for the previous version of root_camera
 *
 *README for a preliminary version of the 
 *root_camera program. 
 *
 *root_camera is based on the program "camera"of Jose Carlos
 *Gonzalez. It was changed in the way that only the pixelisation 
 *and the distibution of the phe to the FADCs works in a 
 *first version. 
 *
 *Using the #undef command most possibilities of the orignal 
 *program are switched of. 
 *
 *The new parts are signed by 
 *
 *- ROOT or __ROOT__ 
 *  nearly all  important codelines for ROOT output are enclosed 
 *  in structures like 
 *  #ifdef __ROOT__ 
 *  
 *    code 
 *
 *  #endif __ROOT__ 
 *
 *  In same case the new lines are signed by a comment with the word 
 *  ROOT in it. 
 *
 *  For timing of the pulse some variable names are changed. 
 *  (t0, t1, t  -->  t_ini, t_fin, t_1st, t_chan,...) 
 *  Look also for this changes. 
 *
 *  For the new root-file is also a change in readparm-files
 *
 *
 *- __DETAIL_TRIGGER__
 *
 *  This is for the implementation of the current work on trigger 
 *  studies. Because the class MTrigger is not well documented it 
 *  isnīt a part of this tar file. Only a dummy File exists. 
 *
 *
 *
 *With all files in the archive, the root_camera program should run. 
 *
 *A reflector file is in the directory rfl-files
 *
 *==================================================
 *
 *From now on, use CVS for development!!!!
 *
 *
 *
 *Revision 1.3  1999/10/22 15:32:56  petry
 *tidied-up version, really sent to H.K. and N.M., 22-10-99
 *
 *Revision 1.2  1999/10/22 15:01:28  petry
 *version sent to H.K. and N.M. on Fri Oct 22 1999
 *
 *Revision 1.1.1.1  1999/10/21 16:35:10  petry
 *first synthesised version
 *
 * Revision 1.8  1999/03/15  14:59:06  gonzalez
 * camera-1_1
 *
 * Revision 1.7  1999/03/02  09:56:11  gonzalez
 * *** empty log message ***
 *
 * Revision 1.6  1999/01/14  17:32:40  gonzalez
 * Added to camera the STDIN input option (data_from_input)
 *
 */

//!@}
//=EOF

