/*****************************************************************************
*
* McXtrace, X-ray tracing package
*         Copyright, All rights reserved
*         DTU Physics, Kgs. Lyngby, Denmark
*         Synchrotron SOLEIL, Saint-Aubin, France
*
* Component: Fluorescence
*
* %Identification
* Written by: E. Farhi
* Date:       March 2022
* Origin:     Synchrotron SOLEIL
*
* Sample model handling absorption, fluorescence, Compton and Rayleigh scattering.
*
* %Description
* Sample that models many photon-matter interactions:
* - absorption          (photon excites an electron and creates a hole)
* - fluorescence        (excited electrons emit light while falling into lower states)
* - Compton scattering  (inelastic, transfer some energy to an electron,    incoherent)
* - Rayleigh scattering (elastic,   dipolar radiation of excitated electrons, coherent)
*
* Attenuation uses the total cross section (XRayLib CSb_Total). The part of the
* photo-absorption which does not end in a fluorescence line (e.g. Auger decay,
* dominant for low-Z elements) is an additional 'absorbed' outcome of the interaction.
*
* Polarisation: when the photon has a non-zero polarisation vector (Ex,Ey,Ez), the
* Rayleigh and Compton scattering use the polarised differential cross sections
* (DCSPb_*, azimuth measured from the polarisation vector), and the scattered photon
* polarisation is the projection of the incoming one perpendicular to the new direction.
* Without polarisation (E=0), unpolarised cross sections are used. Fluorescence emission is
* isotropic and unpolarised.
*
* Fluorescence line widths are the sum of the level widths of the initial and final
* shells of the line (AtomicLevelWidth), when available. Else the K shell width is used.
*
* Use the <b>FluoPowder</b> sample component to properly handle powder diffraction with fluorescence.
*
* The 'material' specification is given as a chemical formulae, e.g. "LaB6". It
* may also be given as a file name (CIF/LAU/LAZ/FullProf format) in which case 
* the formulae is guessed (but may be approximative). Atoms from Z=5 to Z=90 are
* handled.
*
* By setting the 'order' to 1, the absorption along the scattered path is handled.
* A higher 'order' will handle multiple scattering events, and final absorption.
* For instance, a value order>=2 handles e.g. fluorescence iterative cascades 
* in the material. Leaving 'order=0' handles the single scattering only.
*
* Example: Fluorescence(material="LaB6",
*  xwidth=0.001,yheight=0.001,zdepth=0.0001, p_interact=0.99,
*  target_index=1, focus_xw=0.0005, focus_yh=0.0005)
*
* <b>Sample shape:</b>
* Sample shape may be a cylinder, a sphere, a box or any other shape
*   box/plate:       xwidth x yheight x zdepth (thickness=0)
*   hollow box/plate:xwidth x yheight x zdepth and thickness>0
*   cylinder:        radius x yheight (thickness=0)
*   hollow cylinder: radius x yheight and thickness>0
*   sphere:          radius (yheight=0 thickness=0)
*   hollow sphere:   radius and thickness>0 (yheight=0)
*   any shape:       geometry=OFF file
*
*   The complex geometry option handles any closed non-convex polyhedra.
*   It computes the intersection points of the photon ray with the object
*   transparently, so that it can be used like a regular sample object.
*   It supports the OFF, PLY and NOFF file format but not COFF (colored faces).
*   Such files may be generated from XYZ data using:
*     qhull < coordinates.xyz Qx Qv Tv o > geomview.off
*   or
*     powercrust coordinates.xyz
*   and viewed with geomview or java -jar jroff.jar (see below).
*   The default size of the object depends of the OFF file data, but its
*   bounding box may be resized using xwidth,yheight and zdepth.
*
* <b>Concentric components:</b>
* This component has the ability to contain other components when used in
* hollow cylinder geometry (namely sample environment, e.g. cryostat and
* furnace structure). Such component 'shells' should be split into input and
* output side surrounding the 'inside' components. First part must then use
* 'concentric=1' flag to enter the inside part. The component itself must be
* repeated to mark the end of the concentric zone. The number of concentric
* shells and number of components inside is not limited.
*
* COMPONENT F_in = Fluorescence(material="Al", concentric=1, ...)
* AT (0,0,0) RELATIVE sample_position
*
* COMPONENT something_inside ... // e.g. the sample itself or other materials
*
* COMPONENT F_out = COPY(F_in)(concentric=0)
* AT (0,0,0) RELATIVE sample_position
*
* <b>Enhancing computation efficiency:</b>
* * An important option to enhance statistics is to set 'p_interact' to, say,
* 30 percent (0.3) in order to force a fraction of the beam to scatter. This
* will result on a larger number of scattered events, retaining intensity.
*
* In addition, it may be desirable to define a 'target' for the fluorescence
* processes via e.g. the 'target_index' and the 'focus_xw / focus_yh' options.
* This target should e.g. be the SDD area.
*
* This sample component can advantageously benefit from the SPLIT feature, e.g.
* SPLIT COMPONENT sample = Fluorescence(...)
*
* The computation is made via the XRayLib (apt install libxrl-dev) https://github.com/tschoonj/xraylib.
*
* %Parameters
* material:  [str]    Chemical formulae, e.g. "LaB6", "Pb2SnO4". If may also be a CIF/LAZ/LAU file.
* weight:     [g/mol] Molecular weight of the 'unit' described by 'rho' (default: formula weight of material).
* density:   [g/cm^3] Density of material. rho=density/weight/1e24*N_A.
* rho:         [AA-3] Density of 'units' (formula units, or unit cells when 'weight' is that of a cell). Default is computed from density and weight.
* packing_factor: [1] How dense is the material compared to bulk 0-1. Only applied when given explicitly.
* radius:         [m] Outer radius of sample in (x,z) plane. cylinder/sphere.
* xwidth:         [m] Width for a box sample shape.
* yheight:        [m] Height of sample in vertical direction for box/cylinder shapes.
* zdepth:         [m] Depth for a box sample shape.
* thickness:      [m] Thickness of hollow sample Negative value extends the hollow volume outside of the box/cylinder.
* concentric:     [1] Indicate that this component has a hollow geometry and may contain other components. It should then be duplicated after the inside part (only for box, cylinder, sphere).
* geometry:     [str] Name of an Object File Format (OFF) or PLY file for complex geometry. The OFF/PLY file may be generated from XYZ coordinates using qhull/powercrust.
* p_interact:     [1] Force a given fraction of the beam to scatter, keeping intensity right, to enhance small signals (-1 inactivate).
* focus_xw:       [m] Horiz. dimension of a rectangular area.
* focus_yh:       [m] Vert.  dimension of a rectangular area.
* focus_aw:     [deg] Horiz. angular dimension of a rectangular area.
* focus_ah:     [deg] Vert.  angular dimension of a rectangular area.
* focus_r:        [m] Radius of disk containing target. Use 0 for full space.
* target_index:   [1] Relative index of component to focus at, e.g. next is +1.
* target_x:       [m] Position of target to focus at, along X.
* target_y:       [m] Position of target to focus at, along Y.
* target_z:       [m] Position of target to focus at, along Z.
* flag_compton:   [1] When 0, the Compton  scattering is ignored.
* flag_rayleigh:  [1] When 0, the Rayleigh scattering is ignored.
* flag_lorentzian:[1] When 1, the line shapes are assumed to be Lorentzian, else Gaussian.
* flag_kissel:    [1] When 1 (slower), handle M-lines XRF from Kissel for Z>=50 (else only K and L-lines).
* flag_low_z:     [1] When 1, enhances low concentration atoms, else uses cross-sections weighting.
* order:          [1] Limit multiple fluorescence up to given order. Last iteration is absorption only.
*
* CALCULATED PARAMETERS:
* type: scattering event type 0=FLUORESCENCE fluorescence, 1=RAYLEIGH Rayleigh, 2=COMPTON Compton, 3=DIFFRACTION Diffraction (not handled here), 4=TRANSMISSION Transmit (absorbsion), 5=ABSORPTION non-radiative photo-absorption
*
* %Link
* The XRayLib https://github.com/tschoonj/xraylib http://dx.doi.org/10.1016/j.sab.2011.09.011
* %Link
* Fluorescence https://en.wikipedia.org/wiki/Fluorescence
* %Link
* Rayleigh https://en.wikipedia.org/wiki/Rayleigh_scattering
* %Link
* Compton https://en.wikipedia.org/wiki/Compton_scattering
* %Link
* X-ray absorption edges http://skuld.bmsc.washington.edu/scatter/AS_periodic.html
* %Link
* X-ray fluorescence spectra http://www.xrfresearch.com/xrf-spectra/
* %Link
* X-ray edges and fluo lines https://physics.nist.gov/PhysRefData/XrayTrans/Html/search.html
*
* %E
***********************************************************/

DEFINE COMPONENT Fluorescence
SETTING PARAMETERS(
  string geometry=0,
  radius=0, thickness=0,
  xwidth=0, yheight=0, zdepth=0,
  int concentric=0,
  string material="LaB6", packing_factor=0, rho=0, density=0, weight=0, 
  p_interact=0, 
  target_x = 0, target_y = 0, target_z = 0, focus_r = 0,
  focus_xw=0, focus_yh=0, focus_aw=0, focus_ah=0, int target_index=0,
  int flag_compton=1, int flag_rayleigh=1, int flag_lorentzian=0,
  int flag_kissel=0,  int flag_low_z=0,
  int order=1)

/* X-ray parameters: (x,y,z,kx,ky,kz,phi,t,Ex,Ey,Ez,p) */
DEPENDENCY " @XRLFLAGS@ -DUSE_OFF "
NOACC

/* ========================================================================== */

SHARE %{
  %include "read_table-lib"
  %include "interoff-lib" // for OFF/PLY geometry

  #ifndef FLUORESCENCE_DECL
  #define FLUORESCENCE_DECL

  // WARNING: mush NOT use rand01 calls here, as they depend on _particle

  #define XRAYLIB_LINES_MAX 383
  #define FLUORESCENCE 0  // Fluo
  #define RAYLEIGH     1  // Coherent
  #define COMPTON      2  // Incoherent
  #define DIFFRACTION  3  // diffraction
  #define TRANSMISSION 4
  #define ABSORPTION   5  // photo-absorption without fluorescence line (Auger, ...)
  #define FLUO_SHELLS  31 // K,L1-3,M1-5,N1-7,O1-7,P1-5,Q1-3 (XRayLib shell indices 0..30)

  #include <ctype.h>
  #include <xraylib/xraylib.h>
  
/* See XrayLib code (c) T. Schoonjans
 * /usr/include/xraylib/xraylib-parser.h      for compoundData
 * /usr/include/xraylib/xraylib.h             for XS
 */

/* inspired from:
 * https://github.com/golosio/xrmc src/photon/photon.cpp (c) Bruno Golosio    
 */
  
  /* XRMC_CrossSections: Compute interaction cross sections in [barn/atom]
   * When kissel=1, M-lines are computed, but computation is 10x slower.
   * Computes xs[FLUORESCENCE,RAYLEIGH,COMPTON] that must have been allocated.
   * Return total cross section, given Z and E0:
   *   total_xs = XRMC_CrossSections(Z, E0, xs[ABSORPTION+1], flag_kissel);
   * xs[ABSORPTION] receives CSb_Total minus the three processes (non-radiative absorption).
   */
  double XRMC_CrossSections(int Z, double E0, double *xs, int kissel) {
    int    i_line;
    
    if (xs == NULL) return 0;
    for(i_line=0; i_line<=ABSORPTION; i_line++) xs[i_line]=0;
    
    // loop on possible fluorescence lines
    for (i_line=0; i_line<XRAYLIB_LINES_MAX; i_line++) { 
      // cumulative sum of the line cross sections
      xs[FLUORESCENCE] += kissel && Z >= 50 ?
        CSb_FluorLine_Kissel(Z, -i_line, E0, NULL) /* XRayLib lines are negative integers */
      : CSb_FluorLine(Z, -i_line, E0, NULL);
    }

    // coherent and incoherent cross sections
    xs[RAYLEIGH] = CSb_Rayl( Z, E0, NULL);
    xs[COMPTON]  = CSb_Compt(Z, E0, NULL);
    
    // total interaction cross section is CSb_Total(Z, E0, NULL) (never below the sum of the processes)
    {
      double xs_sum = xs[FLUORESCENCE] + xs[RAYLEIGH] + xs[COMPTON];
      double xs_tot = CSb_Total(Z, E0, NULL);
      xs[ABSORPTION] = xs_tot > xs_sum ? xs_tot - xs_sum : 0;
      return xs_sum + xs[ABSORPTION];
    }
  } // XRMC_CrossSections

  /* XRMC_SelectFromDistribution: select a random element from a distribution
   *   index = XRMC_SelectFromDistribution(cum_sum[N], N, r);
   * index is returned within 0 and N-1
   * The x_arr must be a continuously increasing cumulated sum, which last element is the max.
   * When the cumulated array has a leading 0 element (as built in this file), the
   * returned index is the 0-based index of the selected item, and N must be (nb items + 1).
   */
  int XRMC_SelectFromDistribution(double x_arr[], int N, double r)
  {
    if (x_arr == NULL || N <=0) return (0);
    double x = r*x_arr[N-1]; // the threshold cumulated value to search in distribution
    if (x<x_arr[0]) {    // x is smaller than lower limit
      return 0;
    }
    if (x>=x_arr[N-1]) { // x is greater or equal to upper limit
      return N-1;
    }
    int id=0, iu=N-1; // lower and upper index of the subarray to search
    while (iu-id>1) { // search until the size of the subarray to search is >1
      int im = (id + iu)/2; // use the midpoint for equal partition
      // decide which subarray to search
      if (x>=x_arr[im]) id=im; // change min index to search upper subarray
      else iu=im; // change max index to search lower subarray
    }

    return id;
  } // XRMC_SelectFromDistribution

  /* XRMC_SelectInteraction: select an item among 'nb_processes' weights, e.g. the interaction
   * type Fluo/Rayleigh/Compton/..., or a powder line (see FluoPowder).
   *   type = XRMC_SelectInteraction(xs, nb_processes, r);
   * The probability of item i is xs[i]/sum(xs). 'xs' can be unsorted (e.g. computed with
   * XRMC_CrossSections). Negative weights are ignored.
   * There is no limit on 'nb_processes': it does not allocate memory, nor build a cumulated
   * array (a single pass on 'xs' for the sum, and a second pass up to the selected item).
   * Returns the 0-based index of the selected item, e.g. one of FLUORESCENCE | RAYLEIGH | COMPTON,
   * or -1 when no item has a positive weight (or invalid arguments).
   */
  int XRMC_SelectInteraction(double *xs, int nb_processes, double r)
  {
    double sum_xs=0, cum_xs=0, x;
    int    i, last=-1;

    if (xs == NULL || nb_processes < 1) return -1;
    for (i=0; i< nb_processes; i++)
      if (xs[i] > 0) sum_xs += xs[i];
    if (sum_xs <= 0) return -1;

    x = r*sum_xs;                    // threshold on the cumulated weight
    for (i=0; i< nb_processes; i++) {
      if (xs[i] <= 0) continue;      // an item without weight is never selected
      cum_xs += xs[i];
      last    = i;
      if (cum_xs > x) return i;
    }
    return last;                     // only reached by rounding: last item with a weight
  } // XRMC_SelectInteraction

  /* XRMC_SelectFluorescenceEnergy: select outgoing fluo photon energy, when incoming with 'E0'
   * When kissel=1, M-lines are included, but computation is 10x slower
   *   Ef = XRMC_SelectFluorescenceEnergy(Z, E0, &dE, kissel, r, line_dE);
   * line_dE[XRAYLIB_LINES_MAX] are the line widths (see fluo_line_widths), or NULL to use the K shell width.
   * Returns 0 when no line can be excited at E0.
   */
  double XRMC_SelectFluorescenceEnergy(int Z, double E0, double *dE, int kissel, double r, double *line_dE)
  {
    int i_line;
    double sum_xs, cum_xs_lines[XRAYLIB_LINES_MAX+1];

    if (dE) *dE = 0;
    // compute cumulated XS for all fluo lines
    cum_xs_lines[0] = sum_xs = 0;
    for (i_line=0; i_line<XRAYLIB_LINES_MAX; i_line++) { // loop on fluorescent lines
      double xs = kissel && Z >= 50 ?
        CSb_FluorLine_Kissel(Z, -i_line, E0, NULL) /* XRayLib lines are negative integers */
      : CSb_FluorLine(Z, -i_line, E0, NULL);
      // when a line is inactive: E=xs=0
      sum_xs += xs;
      cum_xs_lines[i_line+1] = sum_xs; // cumulative sum of their cross sections
    }
    if (sum_xs <= 0) return 0; // no line excited
    // select randomly one of these lines (array has XRAYLIB_LINES_MAX+1 elements)
    i_line = XRMC_SelectFromDistribution(cum_xs_lines, XRAYLIB_LINES_MAX+1, r); // extract a line
    if (i_line >= XRAYLIB_LINES_MAX) i_line = XRAYLIB_LINES_MAX-1;
    // get the specific line width when available, else the K shell width as approximation
    if (dE) *dE = line_dE ? line_dE[i_line] : AtomicLevelWidth(Z, K_SHELL, NULL); // keV, full-width in keV

    return LineEnergy(Z, -i_line, NULL); // fluorescent line energy
  } // XRMC_SelectFluorescenceEnergy

  /* fluo_line_widths: natural width (FWHM, [keV]) of each fluorescence line of element Z.
   *   fluo_line_widths(Z, dE[XRAYLIB_LINES_MAX]);
   * A line is a transition from an initial vacancy shell to a final one, and its FWHM is
   * width(initial shell) + width(final shell) (AtomicLevelWidth). The two shells are identified
   * by matching the line energy to a difference of absorption edges (K, L, M, ... shells), which
   * avoids relying on an explicit line->shell table. Lines for which the shells or the widths
   * are not available get the K shell width.
   */
  void fluo_line_widths(int Z, double *dE)
  {
    double edge[FLUO_SHELLS], width[FLUO_SHELLS];
    double width_K;
    int    s, s_i, s_f, i_line;

    if (dE == NULL) return;
    width_K = AtomicLevelWidth(Z, K_SHELL, NULL);
    for (s=0; s<FLUO_SHELLS; s++) {
      edge[s]  = EdgeEnergy(Z, s, NULL);
      width[s] = AtomicLevelWidth(Z, s, NULL);
      if (edge[s]  < 0) edge[s]  = 0;
      if (width[s] < 0) width[s] = 0;
    }
    for (i_line=0; i_line<XRAYLIB_LINES_MAX; i_line++) {
      double E_line = LineEnergy(Z, -i_line, NULL);
      double best   = 1e30, w = 0;
      int    b_i    = -1, b_f = -1;
      dE[i_line] = 0;
      if (E_line <= 0) continue;
      for (s_i=0; s_i<FLUO_SHELLS; s_i++) {
        if (edge[s_i] <= 0) continue;
        for (s_f=0; s_f<FLUO_SHELLS; s_f++) {
          double d;
          if (s_f == s_i || edge[s_f] <= 0 || edge[s_f] >= edge[s_i]) continue;
          d = fabs(edge[s_i] - edge[s_f] - E_line);
          if (d < best) { best = d; b_i = s_i; b_f = s_f; }
        }
      }
      if (b_i >= 0 && best <= 0.05*E_line + 0.01) w = width[b_i] + width[b_f];
      dE[i_line] = w > 0 ? w : width_K;
    }
  } // fluo_line_widths

  /* fluo_pol_azimuth: azimuth phi of the outgoing direction kf around the incoming direction k,
   * measured from the polarisation vector E (projected perpendicular to k).
   * Returns 1 when the photon is polarised (phi is set), 0 when unpolarised (E=0 or E//k).
   */
  int fluo_pol_azimuth(double kx, double ky, double kz, double Ex, double Ey, double Ez,
                       double kfx, double kfy, double kfz, double *phi)
  {
    double k  = sqrt(kx*kx+ky*ky+kz*kz);
    double EE = sqrt(Ex*Ex+Ey*Ey+Ez*Ez);
    double ux, uy, uz, s, ex, ey, ez, ne, bx, by, bz;
    if (k <= 0 || EE <= 0) return 0;
    ux = kx/k; uy = ky/k; uz = kz/k;
    s  = ux*Ex + uy*Ey + uz*Ez;
    ex = Ex - s*ux; ey = Ey - s*uy; ez = Ez - s*uz;   // E perpendicular to k
    ne = sqrt(ex*ex+ey*ey+ez*ez);
    if (ne < 1e-6*EE) return 0;
    ex /= ne; ey /= ne; ez /= ne;
    bx = uy*ez - uz*ey; by = uz*ex - ux*ez; bz = ux*ey - uy*ex; // b = u x e
    if (phi) *phi = atan2(kfx*bx+kfy*by+kfz*bz, kfx*ex+kfy*ey+kfz*ez);
    return 1;
  } // fluo_pol_azimuth

  /* fluo_pol_scattered: polarisation of the scattered photon (direction kf, unit vector), as the
   * projection of the incoming polarisation E perpendicular to kf, keeping its amplitude.
   * Set to 0 (unpolarised) when the projection vanishes. Exact for Rayleigh/Thomson, and the
   * dominant component for Compton.
   */
  void fluo_pol_scattered(double kfx, double kfy, double kfz, double *Ex, double *Ey, double *Ez)
  {
    double EE = sqrt((*Ex)*(*Ex)+(*Ey)*(*Ey)+(*Ez)*(*Ez));
    double s  = kfx*(*Ex) + kfy*(*Ey) + kfz*(*Ez);
    double ex = *Ex - s*kfx, ey = *Ey - s*kfy, ez = *Ez - s*kfz;
    double ne = sqrt(ex*ex+ey*ey+ez*ez);
    if (EE <= 0 || ne < 1e-9*EE) { *Ex = *Ey = *Ez = 0; return; }
    *Ex = ex*EE/ne; *Ey = ey*EE/ne; *Ez = ez*EE/ne;
  } // fluo_pol_scattered

  // Function removing spaces (and any char which can not be part of a formula) from string.
  // Letters, digits, parentheses and decimal points are kept.
  char * removeSpacesFromStr(char *string)
  {
      // non_space_count to keep the frequency of kept characters
      int non_space_count = 0;
      if (string == NULL) return NULL;
   
      //Traverse a string and if it is a kept character then, place it at index non_space_count
      for (int i = 0; string[i] != '\0'; i++)
      {
          unsigned char c = (unsigned char)string[i];
          if (isalpha(c) || isdigit(c) || c == '(' || c == ')' || c == '.')
          {
              string[non_space_count] = string[i];
              non_space_count++; //non_space_count incremented
          }    
      }
      
      //Finally placing final character at the string end
      string[non_space_count] = '\0';
      return string;
  }

  // ok = fluo_get_material(material, formula)
  // extracts material atoms from file header
  // the result is concatenated into 'formula'
  int fluo_get_material(char *filename, char *formula) {
  
    int  ret = 0;
    char Line[65535];
    int  flag_found_cif=0;
    if (filename == NULL || formula == NULL) return (0);
    FILE *file = Open_File(filename, "r", NULL);
    if (!file)
      exit(fprintf(stderr, "%s: ERROR: can not open file %s\n", 
      __FILE__, filename));
    
    // Read the file, and search tokens in rows
    formula[0]=0;
    while (fgets(Line, sizeof(Line), file) != NULL) {
      char *token = NULL;
      int   flag_exit=0;
      char *first_non_space=NULL;
      char *next_non_space =NULL;
      // CIF: _chemical_formula_structural 'chemical_formulae'
      // CIF: _chemical_formula_sum 'chemical_formulae'
      // LAZ/LAU: # ATOM <at> <trailing>
      // LAZ/LAU: # Atom <at> <trailing>
      // LAZ/LAU: # TITLE <at> <at> ... [ trailing...]
      // CFL: Title <chemical_formulae>
      // CFL: Atom <at> <trailing>
      
      // search for CIF token
      // single line: search " '\'" delimiter after CIF token, marks reading the formula
      if (!strncasecmp(Line, "_chemical_formula_structural", 28) 
       || !strncasecmp(Line, "_chemical_formula_sum", 21) 
       || !strncasecmp(Line, "_chemical_formula_moiety", 24)
       || flag_found_cif) {
        if  (flag_found_cif) { flag_found_cif=0; /* can not span on more that 2 lines */} 
        else flag_found_cif=1;
        // search for delimiter after the CIF token
        char *first_space_after_token=strpbrk(Line, " \'\n");
        if (first_space_after_token) {
          // search for the characters that may compose the formula
          first_non_space = strpbrk(first_space_after_token, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789()[]");
          if (strchr(first_space_after_token,'?')) {
            // we have an invalid/unknown formula in the CIF. Skip CIF token/line
            flag_found_cif=0;
            continue;
          }
        }
        if (first_non_space) 
          next_non_space  = strpbrk(first_non_space+1, "\'\n\r"); // position of formula end
        if (next_non_space) { 
          flag_exit = 1;
          token = first_non_space;
        }
      } else if (!strncasecmp(Line, "# TITLE", 7) && strchr(Line, '['))
        token = Line+7;
      else if (!strncasecmp(Line, "# Atom", 6))
        token = Line+6;
      else if (!strncasecmp(Line, "Atom", 4))
        token = Line+4;
      else if (!strncasecmp(Line, "Title", 5))
        token = Line+5; // "Title" has 5 characters (was Line+7: dropped the first formula characters)
      if (!token) continue;
      if (!strncasecmp(Line, "# TITLE", 7)) {
        first_non_space = Line+7;
        next_non_space  = strchr(Line+7, '[');
        if (next_non_space) flag_exit = 1;
      }
      if (!first_non_space) first_non_space = strtok(token, " \t\n");
      if (!first_non_space) continue;
      if (!next_non_space)  next_non_space  = strtok(NULL,  " \t\n"); // end of formulae
      if (!next_non_space)  next_non_space = Line+strlen(Line);
      // remove spaces
      strncat(formula, first_non_space, next_non_space-first_non_space);
      ret++;
      if (flag_exit) break;
    }
    fclose(file);
    removeSpacesFromStr(formula);
    return(ret);
  } // fluo_get_material
  
  #endif // FLUORESCENCE_DECL
%}

/* ========================================================================== */

DECLARE %{
  struct   compoundData *compound;
  DArray1d cum_massFractions;
  DArray1d n_atoms;           // nb of atoms of each element per 'unit' (rho is a density of units)
  DArray1d line_width;        // natural line widths [keV], XRAYLIB_LINES_MAX per element
  DArray1d cum_xs_fluo;
  DArray1d cum_xs_Compton;
  DArray1d cum_xs_Rayleigh;
  DArray1d xs_fluo;
  DArray1d xs_Compton;
  DArray1d xs_Rayleigh;
  int  shape;
  off_struct offdata;
  int  n_fluo;
  int  n_Compton;
  int  n_Rayleigh;
  double p_fluo;
  double p_Compton;
  double p_Rayleigh;
  
  // cached values for SPLIT
  int    reuse_valid;
  int    reuse_nb;
  int    reuse_intersect;
  double reuse_x;
  double reuse_y;
  double reuse_z;
  double reuse_kx;
  double reuse_ky;
  double reuse_kz;
  double reuse_ki;
  double reuse_l0;
  double reuse_l1;
  double reuse_l2;
  double reuse_l3;
  double reuse_sigma_barn;
  double reuse_xs_absorb;
  DArray1d reuse_cum_xs_fluo;
  DArray1d reuse_cum_xs_Compton;
  DArray1d reuse_cum_xs_Rayleigh;
  DArray1d reuse_xs_fluo;
  DArray1d reuse_xs_Compton;
  DArray1d reuse_xs_Rayleigh;
%}

INITIALIZE %{

  /* energies en [keV], angles in [radians], XRL CSb cross sections are in [barn/atom] */
  xrl_error *error = NULL;
  int        i;
  
  XRayInit();
  
  shape=-1; /* -1:no shape, 0:cyl, 1:box, 2:sphere, 3:any-shape  */
  if (geometry && strlen(geometry) && strcmp(geometry, "NULL") && strcmp(geometry, "0")) {
    #ifndef USE_OFF
    fprintf(stderr,"Error: You are attempting to use an OFF geometry without -DUSE_OFF. You will need to recompile with that define set!\n");
    exit(-1);
    #else
    if (off_init(geometry, xwidth, yheight, zdepth, 0, &offdata)) {
      shape=3; thickness=0; concentric=0;
    }
    #endif
  }
  else if (xwidth && yheight && zdepth)  shape=1; /* box */
  else if (radius > 0 &&  yheight)       shape=0; /* cylinder */
  else if (radius > 0 && !yheight)       shape=2; /* sphere */

  if (shape < 0)
    exit(fprintf(stderr,"Fluorescence: %s: sample has invalid dimensions.\n"
                        "ERROR       Please check parameter values (xwidth, yheight, zdepth, radius).\n", NAME_CURRENT_COMP));
  
  if (!material || !strlen(material) || !strcmp(material, "NULL") || !strcmp(material, "0")) 
    exit(fprintf(stderr, "Fluorescence: ERROR: %s: Null material specification.\n", NAME_CURRENT_COMP));

  if (order > 1 && flag_lorentzian)
    fprintf(stderr, "Fluorescence: WARNING: %s: Using flag_lorentzian=1 Lorentzian line-shape with order>1 may create artifacts.\n", NAME_CURRENT_COMP);
    
  // test if the material is given as a file
  char path[1024];
  char formula[65536];
  char *mat_name = material;  // formula actually used (never write into the 'material' parameter)
  formula[0]='\0';
  FILE *file = Open_File(material, "r", path);
  if (file != NULL) {
    fclose(file);
    // open the material structure file (laz/lau/cif...)
    // search (case sensitive) along lines
    if (!fluo_get_material(material, formula))
      exit(fprintf(stderr, "ERROR: %s: file %s does not contain material formulae.\n", NAME_CURRENT_COMP, material));
    
    MPI_MASTER(
    fprintf(stderr, "Fluorescence: INFO: %s: found material %s from file %s\n", NAME_CURRENT_COMP, formula, material);
    );
    mat_name = formula;
    // CIF: _chemical_formula_structural 'chemical_formulae'
    // CIF: _chemical_formula_sum 'chemical_formulae'
    // LAZ/LAU: # ATOM <at> <trailing>
    // LAZ/LAU: # Atom <at> <trailing>
    // LAZ/LAU: # TITLE <at> <at> ... [ trailing...]
    // CFL: Title <chemical_formulae>
    // CFL: Atom <at> <trailing>
    
  }
    
  compound = CompoundParser(mat_name, &error); /* XRayLib */
  if (error != NULL) {
    exit(fprintf(stderr, "ERROR: %s: Invalid material %s: %s\n",
      NAME_CURRENT_COMP, mat_name, error->message));
  }
  xrl_error_free(error);
  
  /* compute total density for raw material and display information ========= */  
  if (weight <= 0) weight = compound->molarMass; /* g/mol */
  MPI_MASTER(
    printf("%s: Material %s mass fractions:\n", 
      NAME_CURRENT_COMP, mat_name);
  )
  
  double mat_density       = 0; /* g/cm3 */
  double sum_massFractions = 0;
  double sum_w_over_rho    = 0;
  cum_massFractions        = create_darr1d(compound->nElements+1);
  n_atoms                  = create_darr1d(compound->nElements+1);
  cum_xs_fluo              = create_darr1d(compound->nElements+1);
  cum_xs_Compton           = create_darr1d(compound->nElements+1);
  cum_xs_Rayleigh          = create_darr1d(compound->nElements+1);
  xs_fluo                  = create_darr1d(compound->nElements+1);
  xs_Compton               = create_darr1d(compound->nElements+1);
  xs_Rayleigh              = create_darr1d(compound->nElements+1);
  cum_massFractions[0]     = 0;
  
  /* print material information, and check for elements */
  for (i=0; i< compound->nElements; i++) {
    int    Z      = compound->Elements[i];
    error = NULL;
    double Z_dens = ElementDensity(Z, &error);
    if (error != NULL)
      exit(fprintf(stderr, "ERROR: %s: Z=%i %s\n", NAME_CURRENT_COMP, Z, error->message));
    if (Z_dens > 0) sum_w_over_rho += compound->massFractions[i]/Z_dens; /* volumes add, not densities */
    sum_massFractions     += compound->massFractions[i];
    cum_massFractions[i+1] = sum_massFractions;
    /* number of atoms of element i per 'unit' of mass 'weight' */
    n_atoms[i]             = compound->nAtoms[i]*weight/compound->molarMass;
    MPI_MASTER(
      printf("  | %6.2g %%: Z=%3i %3s %8.3g [g/mol] %8.3g [g/cm3]\n",
        compound->massFractions[i]*100, Z, AtomicNumberToSymbol(Z,NULL), AtomicWeight(Z, NULL),
        Z_dens);
    )
  }
  xrl_error_free(error);
  /* natural width of each fluorescence line of each element (initial + final level widths) */
  line_width = create_darr1d(compound->nElements*XRAYLIB_LINES_MAX);
  for (i=0; i< compound->nElements; i++)
    fluo_line_widths(compound->Elements[i], &line_width[i*XRAYLIB_LINES_MAX]);
  if (sum_w_over_rho > 0) mat_density = sum_massFractions/sum_w_over_rho; /* g/cm3 */
  if (density <= 0)       density     = mat_density;                      /* g/cm3 */
  if (density <= 0 && rho <= 0)
    exit(fprintf(stderr, "ERROR: %s: can not determine density of %s. Specify 'density' or 'rho'.\n",
      NAME_CURRENT_COMP, mat_name));
  
  /* molar volume [cm^3/mol] = weight [g/mol] / density [g/cm^3] */
  /* unit density per Angs^3 = [mol/cm^3] * N_Avogadro *(1e-8)^3 */
  if (!rho) rho = density/weight/1e24*NA; // unit density [units/Angs-3]
  /* packing factor only applies when explicitly given (the 'density' already accounts for it otherwise) */
  if (packing_factor > 0 && packing_factor < 1) rho *= packing_factor;
  else if (packing_factor <= 0) packing_factor = 1;
  MPI_MASTER(
    printf("%s: Material %s M=%g [g/mol] density=%g [g/cm3] rho=%g [at/Angs-3]",
      NAME_CURRENT_COMP, mat_name, weight, density, rho);
    if (fabs(packing_factor-1) > 1e-2)
      printf(" packing_factor=%g", packing_factor);
    printf("\n");
  )
  
  /* target for scattering ================================================== */
  if (!target_index && !target_x && !target_y && !target_z) target_index=1;
  if (target_index)
  {
    Coords ToTarget;
    ToTarget = coords_sub(POS_A_COMP_INDEX(INDEX_CURRENT_COMP+target_index),POS_A_CURRENT_COMP);
    ToTarget = rot_apply(ROT_A_CURRENT_COMP, ToTarget);
    coords_get(ToTarget, &target_x, &target_y, &target_z);
  }
  if (!(target_x || target_y || target_z)) {
    MPI_MASTER(
    printf("Fluorescence: %s: The target is not defined. Using 4PI.\n",
      NAME_CURRENT_COMP);
    );
  }
  
  n_fluo = n_Compton = n_Rayleigh = 0;
  p_fluo = p_Compton = p_Rayleigh = 0;
  
  // cached variables set to 0 (for SPLIT)
  reuse_valid=0;
  reuse_xs_absorb=0;
  reuse_nb=0;
  reuse_x=reuse_y=reuse_z=reuse_kx=reuse_ky=reuse_kz=0;
  reuse_intersect=0;
  reuse_ki=reuse_l0=reuse_l1=reuse_l2=reuse_l3=reuse_sigma_barn=0;
  reuse_cum_xs_fluo              = create_darr1d(compound->nElements+1);
  reuse_cum_xs_Compton           = create_darr1d(compound->nElements+1);
  reuse_cum_xs_Rayleigh          = create_darr1d(compound->nElements+1);
  reuse_xs_fluo                  = create_darr1d(compound->nElements+1);
  reuse_xs_Compton               = create_darr1d(compound->nElements+1);
  reuse_xs_Rayleigh              = create_darr1d(compound->nElements+1);
  reuse_cum_xs_fluo[0]=reuse_cum_xs_Compton[0]=reuse_cum_xs_Rayleigh[0]=0;
%}

TRACE %{

int    intersect=0;       /* flag to continue/stop */
int    reuse    =0;       /* flag raised when reusing (SPLIT) */
int    type     =-1;      /* type of interaction */
double l0,  l1,  l2,  l3; /* distances for intersections */
double dl0, dl1, dl2, dl; /* distance intervals */
int    flag_concentric = 0;
int    flag_ishollow   = 0;
int    event_counter   = 0;         /* scattering event counter (multiple fluorescence) */
int    force_transmit  = 0;         /* Flag to handle cross-section weighting in case of finite order */
double sigma_barn=0, xs[ABSORPTION+1];         /* cross sections [barn/unit] fluo/Rayleigh/Compton/diff/transmit */
double aim_x=0, aim_y=0, aim_z=1;   /* Position of target relative to scattering point */


#ifdef OPENACC
#ifdef USE_OFF
off_struct thread_offdata = offdata;
#endif
#else
#define thread_offdata offdata
#endif

double k, E;
double ki,pi;

/* Store Initial photon state */
k  = ki = sqrt(kx*kx+ky*ky+kz*kz); //  Angs-1
E  = K2E*k; // keV
pi = p;     // used to test for multiple fluo weighting and order cutoff

do { /* while (intersect) Loop over multiple scattering events */

  // test for a SPLIT event (same particle comes in: same position, direction and energy)
  l0=l1=l2=l3=dl0=dl1=dl2=0;
  if (!event_counter && reuse_valid
   && fabs(reuse_ki - ki)  < 1e-15
   && fabs(reuse_x  - x)   < 1e-15 && fabs(reuse_y  - y)  < 1e-15 && fabs(reuse_z  - z)  < 1e-15
   && fabs(reuse_kx - kx)  < 1e-15 && fabs(reuse_ky - ky) < 1e-15 && fabs(reuse_kz - kz) < 1e-15) {
    reuse     = 1;
    reuse_nb++;
    // use cached values and skip actual computation
    intersect = reuse_intersect;
    l0        = reuse_l0;
    l1        = reuse_l1;
    l2        = reuse_l2;
    l3        = reuse_l3;

  } else {
    // we have a different event: compute intersection lengths
    
    /* ========================================================================== */
    /*                                   GEOMETRY                                 */
    /* ========================================================================== */

    /* Intersection photon trajectory / sample (sample surface) */
    if (thickness >= 0) {
      if (shape==0)
        intersect=cylinder_intersect(&l0,&l3, x,y,z,kx,ky,kz, radius,yheight);
      else if (shape==1)
        intersect=box_intersect     (&l0,&l3, x,y,z,kx,ky,kz, xwidth,yheight,zdepth);
      else if (shape==2)
        intersect=sphere_intersect  (&l0,&l3, x,y,z,kx,ky,kz, radius);
      #ifdef USE_OFF
      else if (shape == 3)
        intersect=off_x_intersect(&l0, &l3, NULL, NULL, x, y, z, kx,ky,kz, thread_offdata );
      #endif
    } else {
      if (shape==0)
        intersect=cylinder_intersect(&l0,&l3, x,y,z,kx,ky,kz, radius-thickness,
          yheight-2*thickness > 0 ? yheight-2*thickness : yheight);
      else if (shape==1)
        intersect=box_intersect     (&l0,&l3, x,y,z,kx,ky,kz,
          xwidth-2*thickness > 0 ?  xwidth-2*thickness : xwidth,
          yheight-2*thickness > 0 ? yheight-2*thickness : yheight,
          zdepth-2*thickness > 0 ?  zdepth-2*thickness : zdepth);
      else if (shape==2)
        intersect=sphere_intersect  (&l0,&l3, x,y,z,kx,ky,kz, radius-thickness);
      #ifdef USE_OFF
      else if (shape == 3)
        intersect=off_x_intersect(&l0, &l3, NULL, NULL, x, y, z, kx,ky,kz, thread_offdata );
      #endif
    }


    /* Computing the intermediate lengths (always, also when p_interact<0 which only disables forcing) */
    if (intersect) {
      flag_ishollow = 0;
      if (thickness > 0) {
        if (shape==0 && cylinder_intersect(&l1,&l2, x,y,z,kx,ky,kz, radius-thickness,
          yheight-2*thickness > 0 ? yheight-2*thickness : yheight))
          flag_ishollow=1;
        else if (shape==2 && sphere_intersect   (&l1,&l2, x,y,z,kx,ky,kz, radius-thickness))
          flag_ishollow=1;
        else if (shape==1 && box_intersect(&l1,&l2, x,y,z,kx,ky,kz,
          xwidth-2*thickness > 0 ? xwidth-2*thickness : xwidth,
          yheight-2*thickness > 0 ? yheight-2*thickness : yheight,
          zdepth-2*thickness > 0 ? zdepth-2*thickness : zdepth))
          flag_ishollow=1;
      } else if (thickness<0) {
        if (shape==0 && cylinder_intersect(&l1,&l2, x,y,z,kx,ky,kz, radius,yheight))
          flag_ishollow=1;
        else if (shape==2 && sphere_intersect   (&l1,&l2, x,y,z,kx,ky,kz, radius))
          flag_ishollow=1;
        else if (shape==1 && box_intersect(&l1,&l2, x,y,z,kx,ky,kz, xwidth, yheight, zdepth))
          flag_ishollow=1;
      }
      if (l3 > 1000) l3=0;              // we passed the sample, far away
      if (!flag_ishollow) l1 = l2 = l3; /* no empty space inside */
    } /* if intersect */


    // store values for potential next SPLIT (incoming state, before any propagation)
    if (!event_counter) {
      reuse_valid     = 1;
      reuse_intersect = intersect;
      reuse_l0        = l0;
      reuse_l1        = l1;
      reuse_l2        = l2;
      reuse_l3        = l3;
      reuse_ki        = ki;
      reuse_x = x;   reuse_y = y;   reuse_z = z;
      reuse_kx = kx; reuse_ky = ky; reuse_kz = kz;
    }
    reuse           = 0;
  } // if !reuse (SPLIT)

  if (intersect) { /* the photon hits the sample */

    if (l0 > 0) {  /* we are before the sample */
      PROP_DL(l0); /* propagates photon to the entry of the sample */
    } else if (l1 > 0 && l1 > l0) { /* we are inside first part of the sample */
      /* no propagation, stay inside */
    } else if (l2 > 0 && l2 > l1) { /* we are in the hole */
      PROP_DL(l2); /* propagate to inner surface of 2nd part of sample */
    } else if (l3 > 0 && l3 > l2) { /* we are in the 2nd part of sample */
      /* no propagation, stay inside */
    }

    dl0=l1-(l0 > 0 ? l0 : 0); /* Distance in first part of hollow/cylinder/box */
    dl1=l2-(l1 > 0 ? l1 : 0); /* Distance in hole */
    dl2=l3-(l2 > 0 ? l2 : 0); /* Distance in 2nd part of hollow cylinder */

    if (dl0 < 0) dl0 = 0;
    if (dl1 < 0) dl1 = 0;
    if (dl2 < 0) dl2 = 0;

    /* initialize concentric mode */
    if (concentric && !flag_concentric && l0 >= 0
     && shape==0 && thickness) {
      flag_concentric=1;
    }

    if (flag_concentric == 1) {
      dl1=dl2=0; /* force exit when reaching hole/2nd part */
    }

    if (!dl0 && !dl2) {
      intersect = 0; /* the sample was passed entirely */
    }
  } // if intersect (geometry)

    
  /* ========================================================================== */
  /*                             INTERACTION PROCESS                            */
  /* ========================================================================== */
  xs[FLUORESCENCE]=xs[COMPTON]=xs[RAYLEIGH]=xs[TRANSMISSION]=xs[DIFFRACTION]=xs[ABSORPTION]=sigma_barn=0;
  cum_xs_fluo[0] = cum_xs_Compton[0] = cum_xs_Rayleigh[0] = 0;
  
  if (intersect) {
    double my_s;
    int    i_Z,i;
    double d_path, p_trans, p_scatt, mc_trans, mc_scatt;
    
    /* actual fluorescence calculation */
    
    /* compute total scattering cross section for incoming photon energy Ei */
    /* compute each contribution XS, per unit (atoms are weighted by their number in the unit) */
    if (!reuse) {
      for (i_Z=0; i_Z< compound->nElements; i_Z++) {
        int    Z   = compound->Elements[i_Z];
        double nat = n_atoms[i_Z];
        double xs_Z[ABSORPTION+1];

        // get Fluorescence xs
        XRMC_CrossSections(Z, E, xs_Z, flag_kissel); // [barn/atom]

        // local XS for element (Z)
        xs_fluo[i_Z+1]     = nat*xs_Z[FLUORESCENCE];
        xs_Compton[i_Z+1]  = nat*xs_Z[COMPTON];
        xs_Rayleigh[i_Z+1] = nat*xs_Z[RAYLEIGH];
        // selection on cumulated distribution xs*nat
        cum_xs_fluo[i_Z+1]     = cum_xs_fluo[i_Z]    +xs_fluo[i_Z+1];
        cum_xs_Compton[i_Z+1]  = cum_xs_Compton[i_Z] +xs_Compton[i_Z+1];
        cum_xs_Rayleigh[i_Z+1] = cum_xs_Rayleigh[i_Z]+xs_Rayleigh[i_Z+1];
        for (i=0; i<3; i++) { xs[i] += nat*xs_Z[i]; }
        xs[ABSORPTION] += nat*xs_Z[ABSORPTION]; // non-radiative absorption
      } // for Z in compound
      for (i=0; i<3; i++) sigma_barn += xs[i];
      sigma_barn += xs[ABSORPTION]; // total XS (CSb_Total)
      
      // store values into cache for SPLIT
      if (!event_counter) {
        for (i_Z=0; i_Z< compound->nElements+1; i_Z++) {
          reuse_cum_xs_fluo[i_Z]     = cum_xs_fluo[i_Z];
          reuse_cum_xs_Compton[i_Z]  = cum_xs_Compton[i_Z];
          reuse_cum_xs_Rayleigh[i_Z] = cum_xs_Rayleigh[i_Z];
          reuse_xs_fluo[i_Z]         = xs_fluo[i_Z];
          reuse_xs_Compton[i_Z]      = xs_Compton[i_Z];
          reuse_xs_Rayleigh[i_Z]     = xs_Rayleigh[i_Z];
        }
        reuse_sigma_barn = sigma_barn;
        reuse_xs_absorb  = xs[ABSORPTION];
      }

    } else {
      // reuse cached values (SPLIT), event_counter=0
      for (i_Z=0; i_Z< compound->nElements+1; i_Z++) {
        cum_xs_fluo[i_Z]      = reuse_cum_xs_fluo[i_Z];
        cum_xs_Compton[i_Z]   = reuse_cum_xs_Compton[i_Z];
        cum_xs_Rayleigh[i_Z]  = reuse_cum_xs_Rayleigh[i_Z];
        xs_fluo[i_Z]          = reuse_xs_fluo[i_Z];
        xs_Compton[i_Z]       = reuse_xs_Compton[i_Z];
        xs_Rayleigh[i_Z]      = reuse_xs_Rayleigh[i_Z];
      }
      // the total per process is the last element of the cumulated sums
      xs[FLUORESCENCE] = cum_xs_fluo[compound->nElements];
      xs[COMPTON]      = cum_xs_Compton[compound->nElements];
      xs[RAYLEIGH]     = cum_xs_Rayleigh[compound->nElements];
      xs[ABSORPTION]   = reuse_xs_absorb;
      sigma_barn = reuse_sigma_barn;
    }
//    printf("DEBUG: pi=%g p=%g ; ki=%g k=%g ; xs=[%g %g %g] type=FOLLOW sigma_barn=%g\n",
//        pi, p, ki, k, xs[0], xs[1], xs[2], sigma_barn);
    
    /* probability to absorb/scatter */
    my_s   = rho*100*sigma_barn; /* mu, 100: convert from barns*Angs-3 to m-1. my_s in [1/m] */
    d_path = ( dl0 +dl2 );  /* total path lenght in sample */
    
    /* Proba of transmission/interaction along length d_path */    
    p_trans = exp(-my_s*d_path); /* probability to not-interact (transmit) */
    p_scatt = 1 - p_trans;       /* portion of beam which scatters */
    
    /* force a given fraction of the beam to scatter */
    if (!event_counter && p_interact>0 && p_interact<=1) {
      /* we force a portion of the beam to interact */
      /* This is used to improve statistics */
      mc_trans = 1-p_interact;
    } else {
      mc_trans = p_trans; /* 1 - p_scatt */
    }
    mc_scatt = 1 - mc_trans; /* portion of beam to scatter (or force to) */
    /* when mc_scatt<=0 nothing can scatter: the photon is simply transmitted below */
    
    if (!force_transmit && mc_scatt > 0 && (mc_scatt >= 1 || rand01() < mc_scatt)) {
      /* we "scatter" with one of the interaction processes */
        
      dl = -log(1 - rand0max((1 - exp(-my_s*d_path)))) / my_s; /* length */

      /* If t0 is in hole, propagate to next part of the hollow cylinder */
      if (dl1 > 0 && dl0 > 0 && dl > dl0) dl += dl1;

      /* photon propagation to the scattering point */
      PROP_DL(dl);
      p *= fabs(p_scatt/mc_scatt); /* account for p_interact, lower than 1 */
      
    } else { // force_transmit
      /* we go through the material without interaction, and exit */
      if (type <0) type = TRANSMISSION; // transmission
      intersect = 0;
      PROP_DL(dl0+dl1+dl2); /* up to the exit point (includes the hole, if any) */
      /* attenuate beam by portion which is scattered (and left along) */
      p *= p_trans;
      if (!event_counter && p_interact>0 && p_interact<=1) p /= mc_trans;
//      printf("DEBUG: pi=%g p=%g ; ki=%g k=%g ; xs=[%g %g %g] type=TRANSMIT\n",
//        pi, p, ki, k, xs[0], xs[1], xs[2]);
      break; // end while (intersect)
    }
    
  } /* if intersect (propagate) */

  if (intersect) { /* scattering event */
    int    i_Z, Z;
    double solid_angle=0;
    double theta, dsigma, sigma_Z, cos_theta;
    double phi1=0;           // azimuth from the polarisation vector
    int    polarised=0;     // 1 when the photon has a polarisation vector
    double Ef, dE;
    double kf=k, kf_x, kf_y, kf_z;  // next particle direction

    /* MC choose process from cross sections 'xs': fluo, Rayleigh, Compton  */
    type = XRMC_SelectInteraction(xs, ABSORPTION+1, rand01()); // up to ABSORPTION (xs[DIFFRACTION|TRANSMISSION]=0)
    if (type != FLUORESCENCE && type != RAYLEIGH && type != COMPTON) ABSORB;
    if (type == RAYLEIGH && !flag_rayleigh) ABSORB;
    if (type == COMPTON  && !flag_compton)  ABSORB;
    
    /* choose Z (element) on associated XS, taking into account the number of atoms */
    if (flag_low_z) {
      /* uniform choice of element, weighted back by the true probability */
      double xs_sel;
      i_Z = (int)floor(compound->nElements * rand01());
      if (i_Z >= compound->nElements) i_Z = compound->nElements-1;
      switch (type) {
        case FLUORESCENCE: xs_sel = xs_fluo[i_Z+1];     break;
        case RAYLEIGH:     xs_sel = xs_Rayleigh[i_Z+1]; break;
        default:           xs_sel = xs_Compton[i_Z+1];  break;
      }
      if (xs_sel <= 0 || xs[type] <= 0) ABSORB;
      /* true probability xs_sel/xs[type], sampled with 1/nElements */
      p *= compound->nElements*xs_sel/xs[type];
    } else {
      switch (type) {
        case FLUORESCENCE:
          i_Z = XRMC_SelectFromDistribution(cum_xs_fluo,     compound->nElements+1, rand01());
          break;
        case RAYLEIGH:
          i_Z = XRMC_SelectFromDistribution(cum_xs_Rayleigh, compound->nElements+1, rand01());
          break;
        default: /* COMPTON */
          i_Z = XRMC_SelectFromDistribution(cum_xs_Compton,  compound->nElements+1, rand01());
          break;
      }
      if (i_Z >= compound->nElements) i_Z = compound->nElements-1;
    }
    Z   = compound->Elements[i_Z];
    
    /* select outgoing vector (kf_x, kf_y, kf_z) and |kf| */
    if ((target_x || target_y || target_z)) {
      aim_x = target_x-x;       /* Vector pointing at target (anal./det.) */
      aim_y = target_y-y;
      aim_z = target_z-z;
    }
    if(focus_aw && focus_ah) {
      randvec_target_rect_angular(&kf_x, &kf_y, &kf_z, &solid_angle,
        aim_x, aim_y, aim_z, focus_aw, focus_ah, ROT_A_CURRENT_COMP);
    } else if(focus_xw && focus_yh) {
      randvec_target_rect(&kf_x, &kf_y, &kf_z, &solid_angle,
        aim_x, aim_y, aim_z, focus_xw, focus_yh, ROT_A_CURRENT_COMP);
    } else {
      randvec_target_circle(&kf_x, &kf_y, &kf_z, &solid_angle, aim_x, aim_y, aim_z, focus_r);
    }
    p *= solid_angle/(4*PI); // correct for selected solid-angle

    NORM(kf_x, kf_y, kf_z);  // normalize the outout direction |kf|=1
    
    // scattering angle (clamped, to avoid NaN from rounding)
    cos_theta = scalar_prod(kf_x,kf_y, kf_z, kx,ky,kz)/k;
    if (cos_theta >  1) cos_theta =  1;
    if (cos_theta < -1) cos_theta = -1;
    theta = acos(cos_theta);
    // azimuth around the incoming direction, from the polarisation vector (before k is updated)
    polarised = fluo_pol_azimuth(kx,ky,kz, Ex,Ey,Ez, kf_x,kf_y,kf_z, &phi1);
    
    // determine final energy (kf)
    switch (type) {
      case FLUORESCENCE: /* 0 Fluo: choose line */
        Ef      = XRMC_SelectFluorescenceEnergy(Z, E, &dE, flag_kissel, rand01(), &line_width[i_Z*XRAYLIB_LINES_MAX]); // dE full-width in keV
        if (Ef <= 0) ABSORB; // no line can be excited
        if (dE) {
          if (flag_lorentzian) dE = dE/2*tan(PI/2*randpm1()); // Lorentzian: HWHM=FWHM/2
          else                 dE = dE/(2*sqrt(2*log(2.0)))*randnorm(); // Gaussian: sigma=FWHM/2.355
          Ef = Ef + dE;
          if (Ef <= 0) ABSORB;
        }
        kf      = Ef*E2K;
        /* Fluorescence emission is isotropic and (to a good approximation) unpolarised:
           no angular factor, only the solid-angle weight applied above. */
        Ex = Ey = Ez = 0;
        n_fluo++;
        p_fluo += p;
        break;
        
      case RAYLEIGH:     /* 1 Rayleigh: Coherent, elastic */
        sigma_Z    = CSb_Rayl(Z, E, NULL);              // [barn/atom]
        if (sigma_Z <= 0) ABSORB;
        dsigma     = (polarised ? DCSPb_Rayl(Z, E, theta, phi1, NULL) : DCSb_Rayl(Z, E, theta, NULL));     // [barn/at/st]
        p         *= 4*PI*dsigma/sigma_Z;
        /* scattered polarisation: projection of the incoming one (stays unpolarised otherwise) */
        if (polarised) fluo_pol_scattered(kf_x,kf_y,kf_z, &Ex,&Ey,&Ez);
        n_Rayleigh++;
        p_Rayleigh += p;
        break;
      
      case COMPTON:      /* 2 Compton: Incoherent: choose final energy */
        sigma_Z    = CSb_Compt(Z, E, NULL);             // [barn/atom]
        if (sigma_Z <= 0) ABSORB;
        dsigma     = (polarised ? DCSPb_Compt(Z, E, theta, phi1, NULL) : DCSb_Compt(Z, E, theta, NULL));    // [barn/at/st] (DCS_Compt would be cm2/g/st)
        kf         = ComptonEnergy(E, theta, NULL)*E2K; /* XRayLib, fraction of emc2=511 keV */
        p         *= 4*PI*dsigma/sigma_Z;
        /* scattered polarisation: projection of the incoming one (stays unpolarised otherwise) */
        if (polarised) fluo_pol_scattered(kf_x,kf_y,kf_z, &Ex,&Ey,&Ez);
        n_Compton++;
        p_Compton += p;
        break;
    }
    
    kx = kf*kf_x;
    ky = kf*kf_y;
    kz = kf*kf_z;
    k  = kf;
    E  = k*K2E;
    SCATTER;
    event_counter++;
    
    /* exit if multiple scattering order has been reached */
    if (!order) break; // skip final absorption
    // stop when order has been reached, or weighting is very low
    if (order && (event_counter >= order || p/pi < 1e-15)) { force_transmit=1; }
 
  } // if intersect (scatter)
  
//  if (type>=0)
//  printf("DEBUG: pi=%g p=%g ; ki=%g k=%g ; xs=[%g %g %g] type=%i sigma_barn=%g %s\n",
//    pi, p, ki, k, xs[0], xs[1], xs[2], type, sigma_barn, reuse ? "SPLIT" : "");

} while(intersect); /* end do (intersect) (multiple scattering loop) */



%}

FINALLY %{
  FreeCompoundData(compound);

  if (n_fluo || n_Compton || n_Rayleigh)
    MPI_MASTER(
      printf("INFO: %s: scattered intensity: fluo=%g Compton=%g Rayleigh=%g\n",
             NAME_CURRENT_COMP, p_fluo, p_Compton, p_Rayleigh);
    );
%}

DISPLAY %{
    if (shape == 0)        {  /* cyl */
      cylinder (0, 0, 0, radius, yheight, 0, 0, 1, 0);
    } else if (shape == 1) {  /* box */
      box (0, 0, 0, xwidth, yheight, zdepth, 0, 0, 1, 0);
    } else if (shape == 2) {  /* sphere */
      sphere (0, 0, 0, radius);
    } else if (shape == 3) {  /* OFF file */
      off_display(offdata);
    }
%}

END
