/*******************************************************************************
* Instrument: MCPL_filter_wavelength
*
* %I
* Written by: Peter Willendrup <pkwi@fysik.dtu.dk>
* Date: 2019-03
* Origin: DTU
* %INSTRUMENT_SITE: Tools
*
* Filtering-by-wavelength instrument file for processing MCPL input files
*
* %D
* 
* Example: Split an MCPL file at a wavelength of 0.5 AA
* mcrun MCPL_filter_wavelength MCPLfile=my.mcpl.gz wavelength=0.5
*
* %P
* MCPLfile:   [str] Defines the MCPL input file to process
* wavelength: [AA]  Defines a threshold wavelength to split the MCPLfile at
* min:        [AA]  Minimum wavelength in Monitor_nD plots
* max:        [AA]  Maximum wavelength in Monitor_nD plots
* bins:       [1]   Number of bins in Monitor_nD plots
*
* %L
* <reference/HTML link>
* MCPL website at <a href="https://mctools.github.io/mcpl/">https://mctools.github.io/mcpl/</a>
* %E
*******************************************************************************/
DEFINE INSTRUMENT MCPL_filter_wavelength(string MCPLfile="my.mcpl.gz", wavelength=0.5, max=20, min=0, int bins=100)

DECLARE
%{
  char monopts1[128];
  char monopts2[128];
%}

USERVARS
%{
  double Wavelength;
%}

INITIALIZE
%{
  sprintf(monopts1,"previous lambda limits=[%g %g] bins=%i",min, wavelength, bins);
  sprintf(monopts2,"previous lambda limits=[%g %g] bins=%i",wavelength, max, bins);
%}

TRACE

COMPONENT Origin = Progress_bar()
AT (0, 0, 0) ABSOLUTE

/* read neutrons from an mcpl file*/

COMPONENT MCPLinput = MCPL_input(filename=MCPLfile,verbose=1)
AT(0,0,0) RELATIVE PREVIOUS

COMPONENT Calc = Arm()
AT(0,0,0) RELATIVE PREVIOUS
EXTEND %{
  Wavelength = (2*PI/V2K)/sqrt(vx*vx + vy*vy + vz*vz);
%}
  
COMPONENT MCPLlow = MCPL_output(filename="L_low")
WHEN (Wavelength < wavelength) AT (0,0,0) RELATIVE PREVIOUS

COMPONENT MCPLhigh = MCPL_output(filename="L_high")
WHEN (Wavelength >= wavelength) AT (0,0,0) RELATIVE PREVIOUS


COMPONENT Llow = Monitor_nD(filename="L_low", options=monopts1)
WHEN (Wavelength < wavelength) AT (0,0,0) RELATIVE PREVIOUS

COMPONENT Lhigh = Monitor_nD(filename="L_high", options=monopts2)
WHEN (Wavelength >= wavelength) AT (0,0,0) RELATIVE PREVIOUS
  
FINALLY
%{
%}

END
