/*******************************************************************************
*
*  McStas, neutron ray-tracing package
*  Copyright(C) 2007 Risoe National Laboratory.
*
* %I
* Written by: Milán Klausz, derived from Union_abs_logger_nD by Mads Bertelsen
* Date: 23.09.26
* Version: $Revision: 0.1 $
* Origin: ESS
*
* Absorption logger for a specific position sensitive scintillator detector
*
* %D
* Part of the Union components, a set of components that work together and thus
*  separates geometry and physics within McStas.
* The use of this component requires other components to be used.
*
* 1) One specifies a number of processes using process components
* 2) These are gathered into material definitions using Union_make_material
* 3) Geometries are placed using Union_box/cylinder/sphere, assigned a material
* 4) Logger and conditional components can be placed which will record what happens
* 5) A Union_master component placed after all of the above
*
* Only in step 5 will any simulation happen, and per default all geometries
*  defined before this master, but after the previous will be simulated here.
*
* There is a dedicated manual available for the Union_components
*
* This component is an absorption logger, and thus placed in point 4) above.
*
* An absorption logger will log something for each absorption event happening
*  in the geometry or geometries on which it is attached. These are specified
*  in the target_geometry string. By leaving it blank, all geometries are
*  logged, even the ones not defined at this point in the instrument file.
*  Multiple geometries are specified as a comma separated list.
*
* This absorption logger stores absorption as events, with position, velocity,
* time and weight. The Monitor_nD libraries are used to write the event files.
* This version is a close copy of Monitor_nD, having the same interface, though
* the user must be aware that no propagation happens for rays to hit the
* detector pixels, instead it uses the position where the ray was absorbed.
* Values must still be set for xwidth and yheight: they do not select which
* absorptions are recorded, that is decided by the Union geometry named in
* target_geometry, but a monitor with zero area is deactivated by Monitor_nD.
*
* This absorption logger needs to be placed in space, the position and velocity
*  is recorded in the coordinate system of the logger component.
*
* It is possible to attach one or more conditional components to this absorption
*  logger. Such a conditional component would impose a condition on the state of
*  the neutron after the Union_master component that executes the simulation,
*  and the absorption logger will only record the event if this condition is true.
*
* To use the logger_conditional_extend function, set it to some integer value n
*  and make and extend section to the master component that runs the geometry.
* In this extend function, logger_conditional_extend[n] is 1 if the conditional
*  stack evaluated to true, 0 if not. This way one can check what rays is logged
*  using regular McStas monitors. Only works if a conditional is applied to this
*  logger.
*
* This is a scintillator variant of Union_abs_logger_nD, designed for a specific
*  position sensitive scintillator detector: a GS20 converter layer read out by
*  a multi-anode photomultiplier tube (MAPMT). The logger is placed in the
*  converter layer, and represents the physics from the neutron conversion up to
*  a detection event being triggered in one of the MAPMT pixels.
*
* Instead of logging each absorption at its own position, it converts it into up
*  to five weighted detection events: the MAPMT pixel facing the absorption
*  position and its four neighbours. The weights are tabulated position
*  dependent detection efficiencies, read from the text files
*  true/up/down/left/right_pixel_hit_efficiency[_high_resolution].txt (must be
*  present in the working directory). They answer the question "given that a
*  neutron is absorbed at this position in the converter, what is the
*  probability that a detection event is recorded in each MAPMT pixel", and were
*  produced by a separate Geant4 simulation of the scintillation light, applying
*  a detection threshold per pixel. That threshold suppresses events whose light
*  is shared between neighbouring pixels and would otherwise be counted twice.
*  Two MAPMT pixel sizes are supported, each with its own set of tables.
*
* Note that the detector geometry is hard coded to match the tabulated
*  efficiency files, and is not derived from xwidth and yheight: the tables are
*  read as a 100 x 100 grid of 0.5 mm bins covering a 50 x 50 mm converter tile,
*  read out by a MAPMT pixel grid spanning the central 48.5 x 48.5 mm of that
*  tile. Absorptions outside that map are clamped to its edge bins rather than
*  rejected, so attaching this logger to a geometry of a different size silently
*  gives meaningless efficiencies. Using it for another detector means replacing
*  the efficiency files and adjusting these hard coded values together.
*
* The real MAPMT pixels are not actually all the same size: the outermost ring
*  of pixels is 0.25 mm larger than the rest (3.25 mm vs 3 mm for the high
*  resolution grid, 6.25 mm vs 6 mm for the low resolution one). Monitor_nD only
*  supports a uniform pixel size, so it cannot represent that directly. The
*  trick used here is to build the Monitor_nD pixel grid at the regular
*  (smaller) pixel size, spanning the central 48 x 48 mm, and to treat the 0.25
*  mm wide band just outside it as still belonging to the perimeter pixels: an
*  absorption position that falls in that band is shifted inward by 0.25 mm -
*  onto the strip of the grid that Monitor_nD considers part of the
*  corresponding (undersized) perimeter pixel - before the position is handed to
*  Monitor_nD, so that Monitor_nD bins the resulting detection event into the
*  correct perimeter pixel. This repositioning is done purely for pixel
*  assignment, after the pixel-hit detection efficiencies have already been
*  looked up for the true, unshifted absorption position (see
*  compute_scintillator_pixel_hit_probabilities and
*  move_perimeter_det_event_inside_monitor_limits below).
*
* %P
* INPUT PARAMETERS:
* target_geometry: [string] Comma separated list of geometry names that will be logged, leave empty for all volumes (even not defined yet)
* order_total:     [1]      Only log rays that have scattered n times, -1 for all orders
* order_volume:    [1]      Only log rays that have scattered n times in the same geometry, -1 for all orders
* logger_conditional_extend_index: [1] If a conditional is used with this logger, the result of each conditional calculation can be made available in extend as a array called "logger_conditional_extend", and one would then access logger_conditional_extend[n] if logger_conditional_extend_index is set to n
* xwidth: [m]            Width of detector.
* yheight: [m]           Height of detector.
* zdepth: [m]            Thickness of detector (z).
* radius: [m]            Radius of sphere/banana shape monitor
* options: [str]         String that specifies the configuration of the monitor. The general syntax is "[x] options..." (see <b>Descr.</b>).
* xmin: [m]              Lower x bound of opening
* xmax: [m]              Upper x bound of opening
* ymin: [m]              Lower y bound of opening
* ymax: [m]              Upper y bound of opening
* zmin: [m]              Lower z bound of opening
* zmax: [m]              Upper z bound of opening
* filename: [str]        Output file name (overrides file=XX option).
* bins: [1]              Number of bins to force for all variables. Use 'bins' keyword in 'options' for heterogeneous bins
* min: [u]               Minimum range value to force for all variables. Use 'min' or 'limits' keyword in 'options' for other limits
* max: [u]               Maximum range value to force for all variables. Use 'max' or 'limits' keyword in 'options' for other limits
* user0: [str]           Variable name of USERVAR to be monitored by user0.
* user1: [str]           Variable name of USERVAR to be monitored by user1.
* user2: [str]           Variable name of USERVAR to be monitored by user2.
* user3: [str]           Variable name of USERVAR to be monitored by user3.
* user4: [str]           Variable name of USERVAR to be monitored by user4.
* user5: [str]           Variable name of USERVAR to be monitored by user5.
* user6: [str]           Variable name of USERVAR to be monitored by user6.
* user7: [str]           Variable name of USERVAR to be monitored by user7.
* user8: [str]           Variable name of USERVAR to be monitored by user8.
* user9: [str]           Variable name of USERVAR to be monitored by user9.
* username0: [str]       Name assigned to User0
* username1: [str]       Name assigned to User1
* username2: [str]       Name assigned to User2
* username3: [str]       Name assigned to User3
* username4: [str]       Name assigned to User4
* username5: [str]       Name assigned to User5
* username6: [str]       Name assigned to User6
* username7: [str]       Name assigned to User7
* username8: [str]       Name assigned to User8
* username9: [str]       Name assigned to User9
* restore_neutron: [0|1] Not functional for Union version
* geometry: [str]        Name of an OFF file to specify a complex geometry detector
* nowritefile: [1]       If set, logger will skip writing to disk
* nexus_bins: [1]        NeXus mode only: store component BIN information <br>(-1 disable, 0 enable for list mode monitor, 1 enable for any montor)
* is_high_resolution: [0|1]    Selects the MAPMT pixel size (0: low resolution, 6 mm pixels; 1: high resolution, 3 mm pixels), and correspondingly which set of pixel-hit-efficiency table files is read.
* table_dir: [str]       Directory of the table files (default: none)
* init:              [string]    Deprecated and unused. Accepted so that instruments written for McStas/McXtrace 3.8.7 and earlier, which name the Union_init component here, still compile.
*
* OUTPUT PARAMETERS:
*
* GLOBAL PARAMETERS:
*
* %L
* See also <a href="../monitors/Monitor_nD.html">the Monitor_nD mcdoc page"</a>
*
* %E
******************************************************************************/

DEFINE COMPONENT Union_abs_logger_nD_scintillator
DEFINITION PARAMETERS ()
SETTING PARAMETERS(string target_geometry="NULL",
                   order_total=-1, order_volume=-1, logger_conditional_extend_index=-1,
				   string user0="",string user1="", string user2="", string user3="", string user4="",
		                   string user5="",string user6="", string user7="", string user8="", string user9="",
				   xwidth=0, yheight=0, zdepth=0,
				   xmin=0, xmax=0, ymin=0, ymax=0, zmin=0, zmax=0,
				   int bins=0, min=-1e40, max=1e40, int restore_neutron=0, radius=0,
				   string options="NULL", string filename="NULL",string geometry="NULL", int nowritefile=0, int nexus_bins=0,
				   string username0="NULL", string username1="NULL", string username2="NULL", string username3="NULL", string username4="NULL",
				   string username5="NULL", string username6="NULL", string username7="NULL", string username8="NULL", string username9="NULL",
                   int is_high_resolution=0, string table_dir="", string init="")
OUTPUT PARAMETERS ()

/* Neutron parameters: (x,y,z,vx,vy,vz,t,sx,sy,sz,p) */

SHARE
%{
  %include "union-lib"

  %include "monitor_nd-lib"

  // The file name, in the directory dir (if not empty):
  char*
  scintillator_table_file (char* buffer, size_t size, char* dir, char* file) {
    if (dir && dir[0])
      snprintf (buffer, size, "%s/%s", dir, file);
    else
      snprintf (buffer, size, "%s", file);
    return buffer;
  }
  %include "read_table-lib"
  %include "interoff-lib"

  struct temp_abs_nD_scintillator_data_element_struct {
    double x_pos;
    double y_pos;
    double z_pos;

    double x_vel;
    double y_vel;
    double z_vel;

    double x_pol;
    double y_pol;
    double z_pol;

    double time;
    double weight;

    // The particle when the event was recorded, for its ID and user variables
    _class_particle particle;
  };

  struct temp_abs_nD_scintillator_data_struct {
    int num_elements;
    int allocated_elements;
    struct temp_abs_nD_scintillator_data_element_struct* elements;
  };

  struct a_nD_scintillator_abs_storage_struct {
    MonitornD_Defines_type* p_DEFS;
    MonitornD_Variables_type* p_Vars;

    struct temp_abs_nD_scintillator_data_struct temp_abs_nD_scintillator_data;
    // some type
    int order;
    int order_in_this_volume;
    int order_process_in_this_volume;

    Coords position;
    Rotation rotation;

    double pixel_size;

    t_Table* true_pixel_detection_efficiency_table;
    t_Table* up_pixel_detection_efficiency_table;
    t_Table* down_pixel_detection_efficiency_table;
    t_Table* left_pixel_detection_efficiency_table;
    t_Table* right_pixel_detection_efficiency_table;
  };

  // Handle pixels on the perimeter that are perimeter_pixel_extra_size larger than normal pixels inside
  // by moving det positions in the 'extra size frame' closer to the centre by a distance of perimeter_pixel_extra_size
  void
  move_perimeter_det_event_inside_monitor_limits (double* given_x_pos, double* given_y_pos, double monitor_limit, double detector_limit,
                                                  double perimeter_pixel_extra_size) {
    if (*given_x_pos > monitor_limit && *given_x_pos < detector_limit) {
      *given_x_pos -= perimeter_pixel_extra_size;
    } else if (*given_x_pos < -monitor_limit && *given_x_pos > -detector_limit) {
      *given_x_pos += perimeter_pixel_extra_size;
    }
    if (*given_y_pos > monitor_limit && *given_y_pos < detector_limit) {
      *given_y_pos -= perimeter_pixel_extra_size;
    } else if (*given_y_pos < -monitor_limit && *given_y_pos > -detector_limit) {
      *given_y_pos += perimeter_pixel_extra_size;
    }
  }

  struct scintillator_pixel_hit_probabilities_struct {
    double pixel_size;
    double x; // absorption position, corrected for the larger perimeter pixel size
    double y; // absorption position, corrected for the larger perimeter pixel size
    double true_pixel_p;
    double up_pixel_p;
    double down_pixel_p;
    double left_pixel_p;
    double right_pixel_p;
  };

  // Looks up the five pixel-hit-efficiency probabilities (true pixel + four
  // neighbours) for an absorption position, and returns that position corrected
  // for the larger perimeter pixel size as hit.x/hit.y (see
  // move_perimeter_det_event_inside_monitor_limits above; hit.x/hit.y equal
  // given_x_pos/given_y_pos unless the position falls in the extra-size
  // perimeter band not covered by the regular pixel grid). Shared by
  // record_to_perm_abs_nD_scintillator and record_to_temp_abs_nD_scintillator,
  // which only differ in what they do with the resulting hits.
  struct scintillator_pixel_hit_probabilities_struct
  compute_scintillator_pixel_hit_probabilities (struct a_nD_scintillator_abs_storage_struct* storage, double given_x_pos, double given_y_pos) {
    struct scintillator_pixel_hit_probabilities_struct hit;

    hit.pixel_size = storage->pixel_size; // 3 mm for high resolution, 6 mm for low resolution
    double monitor_limit = 0.024;         // 24 mm from the centre for both 3 mm and 6 mm pixel size

    double perimeter_pixel_extra_size = 0.00025; // Pixels on the perimeter are 0.25 mm larger (3.25 mm vs 3 mm / 6.25 mm vs 6 mm)
    double detector_limit = monitor_limit + perimeter_pixel_extra_size;

    double efficiency_map_offset = 0.025;      // offset to move the lower left corner (-25 mm,-25 mm) of the GS20 to (0,0)
    double efficiency_map_pixel_size = 0.0005; // 0.5 mm //NOTE this might change
    double x_efficiency_map_bin = floor ((given_x_pos + efficiency_map_offset) / efficiency_map_pixel_size);
    double y_efficiency_map_bin = floor ((given_y_pos + efficiency_map_offset) / efficiency_map_pixel_size);
    // Correct neutron weight by the probability of a single multiplicity
    // detection event happening at the conversion point inside the pixel
    // Table_Index(table, i, j) reads row i, column j; the pixel-hit-efficiency
    // table files are written with x indexed by row and y indexed by column.
    hit.true_pixel_p = Table_Index (*(storage->true_pixel_detection_efficiency_table), x_efficiency_map_bin, y_efficiency_map_bin);
    hit.up_pixel_p = Table_Index (*(storage->up_pixel_detection_efficiency_table), x_efficiency_map_bin, y_efficiency_map_bin);
    hit.down_pixel_p = Table_Index (*(storage->down_pixel_detection_efficiency_table), x_efficiency_map_bin, y_efficiency_map_bin);
    hit.left_pixel_p = Table_Index (*(storage->left_pixel_detection_efficiency_table), x_efficiency_map_bin, y_efficiency_map_bin);
    hit.right_pixel_p = Table_Index (*(storage->right_pixel_detection_efficiency_table), x_efficiency_map_bin, y_efficiency_map_bin);

    // The Monitor_nD doesn't handle the larger pixel size on the perimeter when determining which pixel the position belongs to, so the position is moved inside
    // the 'normal size' part of the corresponding perimeter pixel. Note that this happens after the detection probabilities are determined for the true position.
    hit.x = given_x_pos;
    hit.y = given_y_pos;
    move_perimeter_det_event_inside_monitor_limits (&hit.x, &hit.y, monitor_limit, detector_limit, perimeter_pixel_extra_size);

    return hit;
  }

  // Appends one weighted position/velocity data point to the logger's temporary
  // buffer (growing it if necessary). Used once per non-zero-probability pixel
  // hit computed in record_to_temp_abs_nD_scintillator below.
  void
  add_element_to_temp_abs_nD_scintillator (struct a_nD_scintillator_abs_storage_struct* storage, double x_pos, double y_pos, double z_pos, double x_vel,
                                           double y_vel, double z_vel, double time, double weight, struct abs_logger_struct* abs_logger,
                                           struct abs_logger_with_data_struct* abs_logger_with_data_array, _class_particle* _particle) {

    if (storage->temp_abs_nD_scintillator_data.num_elements < storage->temp_abs_nD_scintillator_data.allocated_elements) {

      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].x_pos = x_pos;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].y_pos = y_pos;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].z_pos = z_pos;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].x_vel = x_vel;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].y_vel = y_vel;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].z_vel = z_vel;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].x_pol = 0.0;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].y_pol = 0.0;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].z_pol = 1.0;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].time = time;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].particle = *_particle;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements++].weight = weight;
    } else {
      // No more space, need to allocate a larger buffer for this logger. Wish I had generics.

      // copy current data to temp
      struct temp_abs_nD_scintillator_data_struct temporary_storage;
      temporary_storage.num_elements = storage->temp_abs_nD_scintillator_data.num_elements;
      temporary_storage.elements = malloc (temporary_storage.num_elements * sizeof (struct temp_abs_nD_scintillator_data_element_struct));
      if (!temporary_storage.elements)
        exit (fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: ERROR allocating memory (add_element_to_temp_abs_nD_scintillator)\n", abs_logger->name));

      int index;
      for (index = 0; index < storage->temp_abs_nD_scintillator_data.num_elements; index++) {
        temporary_storage.elements[index].x_pos = storage->temp_abs_nD_scintillator_data.elements[index].x_pos;
        temporary_storage.elements[index].y_pos = storage->temp_abs_nD_scintillator_data.elements[index].y_pos;
        temporary_storage.elements[index].z_pos = storage->temp_abs_nD_scintillator_data.elements[index].z_pos;
        temporary_storage.elements[index].x_vel = storage->temp_abs_nD_scintillator_data.elements[index].x_vel;
        temporary_storage.elements[index].y_vel = storage->temp_abs_nD_scintillator_data.elements[index].y_vel;
        temporary_storage.elements[index].z_vel = storage->temp_abs_nD_scintillator_data.elements[index].z_vel;
        temporary_storage.elements[index].x_pol = storage->temp_abs_nD_scintillator_data.elements[index].x_pol;
        temporary_storage.elements[index].y_pol = storage->temp_abs_nD_scintillator_data.elements[index].y_pol;
        temporary_storage.elements[index].z_pol = storage->temp_abs_nD_scintillator_data.elements[index].z_pol;
        temporary_storage.elements[index].time = storage->temp_abs_nD_scintillator_data.elements[index].time;
        temporary_storage.elements[index].weight = storage->temp_abs_nD_scintillator_data.elements[index].weight;
        temporary_storage.elements[index].particle = storage->temp_abs_nD_scintillator_data.elements[index].particle;
      }

      // free current data
      free (storage->temp_abs_nD_scintillator_data.elements);

      // allocate larger array (10 larger)
      storage->temp_abs_nD_scintillator_data.allocated_elements = 10 + storage->temp_abs_nD_scintillator_data.num_elements;
      storage->temp_abs_nD_scintillator_data.elements
          = malloc (storage->temp_abs_nD_scintillator_data.allocated_elements * sizeof (struct temp_abs_nD_scintillator_data_element_struct));
      if (!storage->temp_abs_nD_scintillator_data.elements)
        exit (fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: ERROR allocating memory (add_element_to_temp_abs_nD_scintillator)\n", abs_logger->name));

      // copy back from temp
      for (index = 0; index < temporary_storage.num_elements; index++) {
        storage->temp_abs_nD_scintillator_data.elements[index].x_pos = temporary_storage.elements[index].x_pos;
        storage->temp_abs_nD_scintillator_data.elements[index].y_pos = temporary_storage.elements[index].y_pos;
        storage->temp_abs_nD_scintillator_data.elements[index].z_pos = temporary_storage.elements[index].z_pos;
        storage->temp_abs_nD_scintillator_data.elements[index].x_vel = temporary_storage.elements[index].x_vel;
        storage->temp_abs_nD_scintillator_data.elements[index].y_vel = temporary_storage.elements[index].y_vel;
        storage->temp_abs_nD_scintillator_data.elements[index].z_vel = temporary_storage.elements[index].z_vel;
        storage->temp_abs_nD_scintillator_data.elements[index].x_pol = temporary_storage.elements[index].x_pol;
        storage->temp_abs_nD_scintillator_data.elements[index].y_pol = temporary_storage.elements[index].y_pol;
        storage->temp_abs_nD_scintillator_data.elements[index].z_pol = temporary_storage.elements[index].z_pol;
        storage->temp_abs_nD_scintillator_data.elements[index].time = temporary_storage.elements[index].time;
        storage->temp_abs_nD_scintillator_data.elements[index].weight = temporary_storage.elements[index].weight;
        storage->temp_abs_nD_scintillator_data.elements[index].particle = temporary_storage.elements[index].particle;
      }

      // free temporary data
      free (temporary_storage.elements);

      // add new data point
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].x_pos = x_pos;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].y_pos = y_pos;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].z_pos = z_pos;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].x_vel = x_vel;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].y_vel = y_vel;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].z_vel = z_vel;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].x_pol = 0.0;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].y_pol = 0.0;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].z_pol = 1.0;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].time = time;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements].particle = *_particle;
      storage->temp_abs_nD_scintillator_data.elements[storage->temp_abs_nD_scintillator_data.num_elements++].weight = weight;
    }

    // If this is the first time this ray is being recorded in this logger, add it to the list of loggers that write to temp and may get it moved to perm
    if (storage->temp_abs_nD_scintillator_data.num_elements == 1)
      add_to_abs_logger_with_data (abs_logger_with_data_array, abs_logger);
  }

  // record_to_temp
  // Would be nice if x y z, k_new and k_old were all coords
  //
  // Mirrors record_to_perm_abs_nD_scintillator below (same pixel-hit physics),
  // but pushes each weighted hit into the temporary buffer via
  // add_element_to_temp_abs_nD_scintillator instead of writing directly to
  // Monitor_nD, since this path is only used while a conditional is attached
  // to this logger and the outcome isn't known yet.
  void
  record_to_temp_abs_nD_scintillator (Coords* position, double* k, double p, double time, int scattered_in_this_volume, int total_number_of_scattering_events,
                                      struct abs_logger_struct* abs_logger, struct abs_logger_with_data_struct* abs_logger_with_data_array,
                                      _class_particle* _particle) {

    struct a_nD_scintillator_abs_storage_struct* storage;
    storage = abs_logger->data_union.p_nD_scintillator_abs_storage;

    int add_point = 1;

    if (storage->order != -1) {
      if (storage->order == total_number_of_scattering_events)
        add_point = 1;
      else
        add_point = 0;
    }

    if (storage->order_in_this_volume != -1) {
      if (storage->order_in_this_volume == scattered_in_this_volume)
        add_point = 1;
      else
        add_point = 0;
    }

    if (add_point == 1) {

      Coords transformed_ray_position;
      transformed_ray_position = coords_sub (*position, storage->position);
      transformed_ray_position = rot_apply (storage->rotation, transformed_ray_position);

      double given_x_pos, given_y_pos, given_z_pos;
      coords_get (transformed_ray_position, &given_x_pos, &given_y_pos, &given_z_pos);

      struct scintillator_pixel_hit_probabilities_struct hit = compute_scintillator_pixel_hit_probabilities (storage, given_x_pos, given_y_pos);

      Coords k_coords = make_position (k);
      Coords transformed_k_coords = rot_apply (storage->rotation, k_coords);

      double given_x_vel, given_y_vel, given_z_vel;
      coords_get (coords_scalar_mult (transformed_k_coords, K2V), &given_x_vel, &given_y_vel, &given_z_vel);

      if (hit.true_pixel_p > 0.0)
        add_element_to_temp_abs_nD_scintillator (storage, hit.x, hit.y, given_z_pos, given_x_vel, given_y_vel, given_z_vel, time, p * hit.true_pixel_p,
                                                 abs_logger, abs_logger_with_data_array, _particle);
      if (hit.up_pixel_p > 0.0)
        add_element_to_temp_abs_nD_scintillator (storage, hit.x, hit.y + hit.pixel_size, given_z_pos, given_x_vel, given_y_vel, given_z_vel, time,
                                                 p * hit.up_pixel_p, abs_logger, abs_logger_with_data_array, _particle);
      if (hit.down_pixel_p > 0.0)
        add_element_to_temp_abs_nD_scintillator (storage, hit.x, hit.y - hit.pixel_size, given_z_pos, given_x_vel, given_y_vel, given_z_vel, time,
                                                 p * hit.down_pixel_p, abs_logger, abs_logger_with_data_array, _particle);
      if (hit.left_pixel_p > 0.0)
        add_element_to_temp_abs_nD_scintillator (storage, hit.x - hit.pixel_size, hit.y, given_z_pos, given_x_vel, given_y_vel, given_z_vel, time,
                                                 p * hit.left_pixel_p, abs_logger, abs_logger_with_data_array, _particle);
      if (hit.right_pixel_p > 0.0)
        add_element_to_temp_abs_nD_scintillator (storage, hit.x + hit.pixel_size, hit.y, given_z_pos, given_x_vel, given_y_vel, given_z_vel, time,
                                                 p * hit.right_pixel_p, abs_logger, abs_logger_with_data_array, _particle);
    }
  }

  // clear_temp
  void
  clear_temp_abs_nD_scintillator (union abs_logger_data_union* data_union) {
    data_union->p_nD_scintillator_abs_storage->temp_abs_nD_scintillator_data.num_elements = 0;
  }

  // record_to_perm
  void
  record_to_perm_abs_nD_scintillator (Coords* position, double* k, double p, double time, int scattered_in_this_volume, int total_number_of_scattering_events,
                                      struct abs_logger_struct* abs_logger, struct abs_logger_with_data_struct* abs_logger_with_data_array,
                                      _class_particle* _particle) {

    struct a_nD_scintillator_abs_storage_struct* storage;
    storage = abs_logger->data_union.p_nD_scintillator_abs_storage;

    int add_point = 1;

    if (storage->order != -1) {
      if (storage->order == total_number_of_scattering_events)
        add_point = 1;
      else
        add_point = 0;
    }

    if (storage->order_in_this_volume != -1) {
      if (storage->order_in_this_volume == scattered_in_this_volume)
        add_point = 1;
      else
        add_point = 0;
    }

    if (add_point == 1) {
      Coords transformed_ray_position;
      transformed_ray_position = coords_sub (*position, storage->position);
      transformed_ray_position = rot_apply (storage->rotation, transformed_ray_position);

      double given_x_pos, given_y_pos, given_z_pos;
      coords_get (transformed_ray_position, &given_x_pos, &given_y_pos, &given_z_pos);

      struct scintillator_pixel_hit_probabilities_struct hit = compute_scintillator_pixel_hit_probabilities (storage, given_x_pos, given_y_pos);

      Coords k_coords = make_position (k);
      Coords transformed_k_coords = rot_apply (storage->rotation, k_coords);

      double given_x_vel, given_y_vel, given_z_vel;
      coords_get (coords_scalar_mult (transformed_k_coords, K2V), &given_x_vel, &given_y_vel, &given_z_vel);

      // Start from the real particle, for its ID and user variables
      _class_particle _localparticle = *_particle;

      _localparticle.z = given_z_pos;

      _localparticle.vx = given_x_vel;
      _localparticle.vy = given_y_vel;
      _localparticle.vz = given_z_vel;

      _localparticle.sx = 0.0;
      _localparticle.sy = 0.0;
      _localparticle.sz = 1.0;

      _localparticle.t = time;

      int pp;

      if (hit.true_pixel_p > 0.0) {
        _localparticle.p = p * hit.true_pixel_p;
        _localparticle.x = hit.x;
        _localparticle.y = hit.y;
        pp = Monitor_nD_Trace (storage->p_DEFS, storage->p_Vars, &_localparticle);
      }
      if (hit.up_pixel_p > 0.0) {
        _localparticle.p = p * hit.up_pixel_p;
        _localparticle.x = hit.x;
        _localparticle.y = hit.y + hit.pixel_size;
        pp = Monitor_nD_Trace (storage->p_DEFS, storage->p_Vars, &_localparticle);
      }
      if (hit.down_pixel_p > 0.0) {
        _localparticle.p = p * hit.down_pixel_p;
        _localparticle.x = hit.x;
        _localparticle.y = hit.y - hit.pixel_size;
        pp = Monitor_nD_Trace (storage->p_DEFS, storage->p_Vars, &_localparticle);
      }
      if (hit.left_pixel_p > 0.0) {
        _localparticle.p = p * hit.left_pixel_p;
        _localparticle.x = hit.x - hit.pixel_size;
        _localparticle.y = hit.y;
        pp = Monitor_nD_Trace (storage->p_DEFS, storage->p_Vars, &_localparticle);
      }
      if (hit.right_pixel_p > 0.0) {
        _localparticle.p = p * hit.right_pixel_p;
        _localparticle.x = hit.x + hit.pixel_size;
        _localparticle.y = hit.y;
        pp = Monitor_nD_Trace (storage->p_DEFS, storage->p_Vars, &_localparticle);
      }
    }
  }

  // write_temp_to_perm
  void
  write_temp_to_perm_abs_nD_scintillator (union abs_logger_data_union* data_union) {

    struct a_nD_scintillator_abs_storage_struct* storage;
    storage = data_union->p_nD_scintillator_abs_storage;

    int index;
    // Add all data points to the historgram, they are saved as index / weight combinations
    for (index = 0; index < storage->temp_abs_nD_scintillator_data.num_elements; index++) {

      // Start from the particle as recorded, for its ID and user variables
      _class_particle _localparticle = storage->temp_abs_nD_scintillator_data.elements[index].particle;

      _localparticle.x = storage->temp_abs_nD_scintillator_data.elements[index].x_pos;
      _localparticle.y = storage->temp_abs_nD_scintillator_data.elements[index].y_pos;
      _localparticle.z = storage->temp_abs_nD_scintillator_data.elements[index].z_pos;

      _localparticle.vx = storage->temp_abs_nD_scintillator_data.elements[index].x_vel;
      _localparticle.vy = storage->temp_abs_nD_scintillator_data.elements[index].y_vel;
      _localparticle.vz = storage->temp_abs_nD_scintillator_data.elements[index].z_vel;

      _localparticle.sx = 0.0;
      _localparticle.sy = 0.0;
      _localparticle.sz = 1.0;

      _localparticle.p = storage->temp_abs_nD_scintillator_data.elements[index].weight;
      _localparticle.t = storage->temp_abs_nD_scintillator_data.elements[index].time;

      int pp;
      pp = Monitor_nD_Trace (storage->p_DEFS, storage->p_Vars, &_localparticle);
    }
    clear_temp_abs_nD_scintillator (data_union);
  }

  void
  write_temp_to_perm_final_p_abs_nD_scintillator (union abs_logger_data_union* data_union, double final_weight) {

    struct a_nD_scintillator_abs_storage_struct* storage;
    storage = data_union->p_nD_scintillator_abs_storage;

    int index;
    // Add all data points to the historgram, they are saved as index / weight combinations
    for (index = 0; index < storage->temp_abs_nD_scintillator_data.num_elements; index++) {

      // Start from the particle as recorded, for its ID and user variables
      _class_particle _localparticle = storage->temp_abs_nD_scintillator_data.elements[index].particle;

      _localparticle.x = storage->temp_abs_nD_scintillator_data.elements[index].x_pos;
      _localparticle.y = storage->temp_abs_nD_scintillator_data.elements[index].y_pos;
      _localparticle.z = storage->temp_abs_nD_scintillator_data.elements[index].z_pos;

      _localparticle.vx = storage->temp_abs_nD_scintillator_data.elements[index].x_vel;
      _localparticle.vy = storage->temp_abs_nD_scintillator_data.elements[index].y_vel;
      _localparticle.vz = storage->temp_abs_nD_scintillator_data.elements[index].z_vel;

      _localparticle.sx = 0.0;
      _localparticle.sy = 0.0;
      _localparticle.sz = 1.0;

      _localparticle.p = final_weight;
      _localparticle.t = storage->temp_abs_nD_scintillator_data.elements[index].time;

      int pp;
      pp = Monitor_nD_Trace (storage->p_DEFS, storage->p_Vars, &_localparticle);
    }
    clear_temp_abs_nD_scintillator (data_union);
  }

  // Only need to define linking function for loggers once.
  #ifndef UNION_ABS_LOGGER
  #define UNION_ABS_LOGGER Dummy
  // Linking function for loggers, finds the indicies of the specified geometries on the global_geometry_list
  void
  manual_linking_function_abs_logger_volumes (char* input_string, struct pointer_to_global_geometry_list* global_geometry_list,
                                              struct pointer_to_1d_int_list* accepted_volumes, char* component_name) {
    // Need to check a input_string of text for an occurance of name. If it is in the inputstring, yes return 1, otherwise 0.
    char* token;
    int loop_index;
    char local_string[512];

    strcpy (local_string, input_string);
    // get the first token
    token = strtok (local_string, ",");

    // walk through other tokens
    while (token != NULL) {
      // printf( " %s\n", token );
      for (loop_index = 0; loop_index < global_geometry_list->num_elements; loop_index++) {
        if (strcmp (token, global_geometry_list->elements[loop_index].name) == 0) {
          add_element_to_int_list (accepted_volumes, loop_index);
          break;
        }

        if (loop_index == global_geometry_list->num_elements - 1) {
          // All possible geometry names have been looked through, and the break was not executed.
          // Alert the user to this problem by showing the geometry name that was not found and the currently available geometires
          printf ("\n");
          printf ("ERROR: The target_geometry string \"%s\" in Union logger component \"%s\" had an entry that did not match a specified geometry. \n",
                  input_string, component_name);
          printf ("       The unrecoignized geometry name was: \"%s\" \n", token);
          printf ("       The geometries available at this point (need to be defined before the logger): \n");
          for (loop_index = 0; loop_index < global_geometry_list->num_elements; loop_index++)
            printf ("         %s\n", global_geometry_list->elements[loop_index].name);
          exit (1);
        }
      }

      // Updates the token
      token = strtok (NULL, ",");
    }
  }

  #endif

  int low_resolution_efficiency_tables_already_read = 0;
  t_Table low_resolution_true_pixel_detection_efficiency_table;
  t_Table low_resolution_up_pixel_detection_efficiency_table;
  t_Table low_resolution_down_pixel_detection_efficiency_table;
  t_Table low_resolution_left_pixel_detection_efficiency_table;
  t_Table low_resolution_right_pixel_detection_efficiency_table;

  int high_resolution_efficiency_tables_already_read = 0;
  t_Table high_resolution_true_pixel_detection_efficiency_table;
  t_Table high_resolution_up_pixel_detection_efficiency_table;
  t_Table high_resolution_down_pixel_detection_efficiency_table;
  t_Table high_resolution_left_pixel_detection_efficiency_table;
  t_Table high_resolution_right_pixel_detection_efficiency_table;
%}

DECLARE
%{
  int loop_index;
  int found_process;
  int specified_processes;
  char local_string[256];

  // Reused for logger
  struct pointer_to_1d_int_list accepted_processes;

  struct global_abs_logger_element_struct abs_logger_list_element;

  struct pointer_to_1d_int_list accepted_volumes;

  struct abs_logger_struct this_abs_logger;
  struct a_nD_scintillator_abs_storage_struct this_abs_storage;

  struct abs_loggers_struct* abs_loggers_on_target_volume;
  struct Volume_struct* target_volume;

  MonitornD_Defines_type DEFS;
  MonitornD_Variables_type Vars;
  MCDETECTOR detector;
  off_struct offdata;
%}

INITIALIZE INHERIT Monitor_nD EXTEND
%{
  struct union_state_struct* union_state_p = union_acquire ();
  char table_file[1024];
  #define TABLE_FILE(file) scintillator_table_file (table_file, sizeof (table_file), table_dir, file)
  if (is_high_resolution) {
    if (high_resolution_efficiency_tables_already_read == 0) {
      if (Table_Read (&high_resolution_true_pixel_detection_efficiency_table, TABLE_FILE ("true_pixel_hit_efficiency_high_resolution.txt"), 0) <= 0) {
        exit (fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file true_pixel_hit_efficiency_high_resolution.txt\n",
                       NAME_CURRENT_COMP));
      }
      if (Table_Read (&high_resolution_up_pixel_detection_efficiency_table, TABLE_FILE ("up_pixel_hit_efficiency_high_resolution.txt"), 0) <= 0) {
        exit (fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file up_pixel_hit_efficiency_high_resolution.txt\n",
                       NAME_CURRENT_COMP));
      }
      if (Table_Read (&high_resolution_down_pixel_detection_efficiency_table, TABLE_FILE ("down_pixel_hit_efficiency_high_resolution.txt"), 0) <= 0) {
        exit (fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file down_pixel_hit_efficiency_high_resolution.txt\n",
                       NAME_CURRENT_COMP));
      }
      if (Table_Read (&high_resolution_left_pixel_detection_efficiency_table, TABLE_FILE ("left_pixel_hit_efficiency_high_resolution.txt"), 0) <= 0) {
        exit (fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file left_pixel_hit_efficiency_high_resolution.txt\n",
                       NAME_CURRENT_COMP));
      }
      if (Table_Read (&high_resolution_right_pixel_detection_efficiency_table, TABLE_FILE ("right_pixel_hit_efficiency_high_resolution.txt"), 0) <= 0) {
        exit (fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file right_pixel_hit_efficiency_high_resolution.txt\n",
                       NAME_CURRENT_COMP));
      }
      high_resolution_efficiency_tables_already_read = 1;
    }
  } else {
    if (low_resolution_efficiency_tables_already_read == 0) {
      if (Table_Read (&low_resolution_true_pixel_detection_efficiency_table, TABLE_FILE ("true_pixel_hit_efficiency.txt"), 0) <= 0) {
        exit (
            fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file true_pixel_hit_efficiency.txt\n", NAME_CURRENT_COMP));
      }
      if (Table_Read (&low_resolution_up_pixel_detection_efficiency_table, TABLE_FILE ("up_pixel_hit_efficiency.txt"), 0) <= 0) {
        exit (fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file up_pixel_hit_efficiency.txt\n", NAME_CURRENT_COMP));
      }
      if (Table_Read (&low_resolution_down_pixel_detection_efficiency_table, TABLE_FILE ("down_pixel_hit_efficiency.txt"), 0) <= 0) {
        exit (
            fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file down_pixel_hit_efficiency.txt\n", NAME_CURRENT_COMP));
      }
      if (Table_Read (&low_resolution_left_pixel_detection_efficiency_table, TABLE_FILE ("left_pixel_hit_efficiency.txt"), 0) <= 0) {
        exit (
            fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file left_pixel_hit_efficiency.txt\n", NAME_CURRENT_COMP));
      }
      if (Table_Read (&low_resolution_right_pixel_detection_efficiency_table, TABLE_FILE ("right_pixel_hit_efficiency.txt"), 0) <= 0) {
        exit (
            fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: can not read pixel hit efficiency file right_pixel_hit_efficiency.txt\n", NAME_CURRENT_COMP));
      }
      low_resolution_efficiency_tables_already_read = 1;
    }
  }

  // input sanitation, provide error if commands used in options that are not supported in Union context
  // capture, 3He_pressure, slit, absorb
  if (strstr (Vars.option, "capture") || strstr (Vars.option, "3He_pressure") || strstr (Vars.option, "slit") || strstr (Vars.option, "absorb"))
    exit (printf ("Abs_logger_nD: %s Union version does not support following options. Aborting (capture, 3He_pressure, slit, absorb).\n", NAME_CURRENT_COMP));

  // May need to manipulate options string for: min pixel ID (if auto_pixel_ID) and previous

  this_abs_storage.p_DEFS = &DEFS; // Grab DEFS prepared by Monitor_nD initialization
  this_abs_storage.p_Vars = &Vars; // Grab Vars prepared by Monitor_nD initialization

  this_abs_storage.order = order_total;
  this_abs_storage.order_in_this_volume = order_volume;

  this_abs_storage.temp_abs_nD_scintillator_data.num_elements = 0;

  this_abs_storage.temp_abs_nD_scintillator_data.allocated_elements = 10;
  this_abs_storage.temp_abs_nD_scintillator_data.elements
      = malloc (this_abs_storage.temp_abs_nD_scintillator_data.allocated_elements * sizeof (struct temp_abs_nD_scintillator_data_element_struct));
  if (!this_abs_storage.temp_abs_nD_scintillator_data.elements)
    exit (fprintf (stderr, "Union_abs_logger_nD_scintillator: %s: ERROR allocating memory (init)\n", NAME_CURRENT_COMP));

  #undef TABLE_FILE

  this_abs_storage.pixel_size = is_high_resolution ? 0.003 : 0.006; // 3 mm for high resolution, 6 mm for low resolution

  if (is_high_resolution) {
    this_abs_storage.true_pixel_detection_efficiency_table = &high_resolution_true_pixel_detection_efficiency_table;
    this_abs_storage.up_pixel_detection_efficiency_table = &high_resolution_up_pixel_detection_efficiency_table;
    this_abs_storage.down_pixel_detection_efficiency_table = &high_resolution_down_pixel_detection_efficiency_table;
    this_abs_storage.left_pixel_detection_efficiency_table = &high_resolution_left_pixel_detection_efficiency_table;
    this_abs_storage.right_pixel_detection_efficiency_table = &high_resolution_right_pixel_detection_efficiency_table;
  } else {
    this_abs_storage.true_pixel_detection_efficiency_table = &low_resolution_true_pixel_detection_efficiency_table;
    this_abs_storage.up_pixel_detection_efficiency_table = &low_resolution_up_pixel_detection_efficiency_table;
    this_abs_storage.down_pixel_detection_efficiency_table = &low_resolution_down_pixel_detection_efficiency_table;
    this_abs_storage.left_pixel_detection_efficiency_table = &low_resolution_left_pixel_detection_efficiency_table;
    this_abs_storage.right_pixel_detection_efficiency_table = &low_resolution_right_pixel_detection_efficiency_table;
  }

  struct global_positions_to_transform_list_struct* global_positions_to_transform_list = &union_state_p->u_positions_to_transform_list;
  struct global_rotations_to_transform_list_struct* global_rotations_to_transform_list = &union_state_p->u_rotations_to_transform_list;
  // Test position and rotation stored in a data storage, and pointers assigned to transform lists
  this_abs_storage.position = POS_A_CURRENT_COMP;
  add_position_pointer_to_list (global_positions_to_transform_list, &this_abs_storage.position);

  rot_copy (this_abs_storage.rotation, ROT_A_CURRENT_COMP);
  add_rotation_pointer_to_list (global_rotations_to_transform_list, &this_abs_storage.rotation);

  // Book keeping
  this_abs_logger.abs_logger_extend_index = logger_conditional_extend_index;
  this_abs_logger.function_pointers.active_record_function = &record_to_perm_abs_nD_scintillator;   // Assume no conditional
  this_abs_logger.function_pointers.inactive_record_function = &record_to_temp_abs_nD_scintillator; // If an assume is present, these two pointers are switched
  // Temp to perm functions, and standard identifier
  // this_abs_logger.function_pointers.select_t_to_p = 1; // 1: temp_to_perm, 2: temp_to_perm_final_p // Not relevant for abs
  this_abs_logger.function_pointers.temp_to_perm = &write_temp_to_perm_abs_nD_scintillator;
  this_abs_logger.function_pointers.temp_to_perm_final_p = &write_temp_to_perm_final_p_abs_nD_scintillator;
  this_abs_logger.function_pointers.clear_temp = &clear_temp_abs_nD_scintillator;

  // Initializing for conditional
  this_abs_logger.conditional_list.num_elements = 0;

  this_abs_logger.data_union.p_nD_scintillator_abs_storage = &this_abs_storage;
  sprintf (this_abs_logger.name, "%s", NAME_CURRENT_COMP);
  sprintf (abs_logger_list_element.name, "%s", NAME_CURRENT_COMP);
  abs_logger_list_element.component_index = INDEX_CURRENT_COMP;
  abs_logger_list_element.abs_logger = &this_abs_logger;

  struct pointer_to_global_geometry_list* global_geometry_list = &union_state_p->u_geometry_list;
  struct pointer_to_global_abs_logger_list* global_specific_volumes_abs_logger_list = &union_state_p->u_specific_volumes_abs_logger_list;
  // In order to run the logger at the right times, pointers to this logger is stored in each volume it logs,
  //  and additionally for each avaiable process. If a process is not logged, the pointer is simply not stored.
  int process_index;
  // Need to find the volumes for which the processes should have a reference to this logger
  if (target_geometry && strlen (target_geometry) && strcmp (target_geometry, "NULL") && strcmp (target_geometry, "0")) {
    // Certain volumes were selected, find the indicies in the global_geometry_list
    manual_linking_function_abs_logger_volumes (target_geometry, global_geometry_list, &accepted_volumes, NAME_CURRENT_COMP);
    // Add this logger to the global_specific_volumes_logger_list (so that conditionals can affect it)
    add_element_to_abs_logger_list (global_specific_volumes_abs_logger_list, abs_logger_list_element);

    for (loop_index = 0; loop_index < accepted_volumes.num_elements; loop_index++) {
      target_volume = global_geometry_list->elements[accepted_volumes.elements[loop_index]].Volume;
      // Add an element to its abs_logger list

      add_initialized_abs_logger_in_volume (&target_volume->abs_loggers);
      target_volume->abs_loggers.p_abs_logger[target_volume->abs_loggers.num_elements - 1] = &this_abs_logger;
    }
  } else {
    // Send to global_all_volumes_logger_list
    // Here there is no system for selecting processes as well
    struct pointer_to_global_abs_logger_list* global_all_volume_abs_logger_list = &union_state_p->u_all_volume_abs_logger_list;
    add_element_to_abs_logger_list (global_all_volume_abs_logger_list, abs_logger_list_element);
  }
 %}

TRACE
%{
%}

SAVE INHERIT Monitor_nD

FINALLY INHERIT Monitor_nD EXTEND
%{
  // Remember to clean up allocated lists
  if (this_abs_storage.temp_abs_nD_scintillator_data.allocated_elements > 0)
    free (this_abs_storage.temp_abs_nD_scintillator_data.elements);

  if (accepted_processes.num_elements > 0)
    free (accepted_processes.elements);
  if (accepted_volumes.num_elements > 0)
    free (accepted_volumes.elements);

  if (low_resolution_efficiency_tables_already_read) {
    Table_Free (&low_resolution_true_pixel_detection_efficiency_table);
    Table_Free (&low_resolution_up_pixel_detection_efficiency_table);
    Table_Free (&low_resolution_down_pixel_detection_efficiency_table);
    Table_Free (&low_resolution_left_pixel_detection_efficiency_table);
    Table_Free (&low_resolution_right_pixel_detection_efficiency_table);
    low_resolution_efficiency_tables_already_read = 0;
  }
  if (high_resolution_efficiency_tables_already_read) {
    Table_Free (&high_resolution_true_pixel_detection_efficiency_table);
    Table_Free (&high_resolution_up_pixel_detection_efficiency_table);
    Table_Free (&high_resolution_down_pixel_detection_efficiency_table);
    Table_Free (&high_resolution_left_pixel_detection_efficiency_table);
    Table_Free (&high_resolution_right_pixel_detection_efficiency_table);
    high_resolution_efficiency_tables_already_read = 0;
  }
  union_release (NAME_CURRENT_COMP);
%}

MCDISPLAY INHERIT Monitor_nD

END

