/*******************************************************************************
*
* McStas, neutron ray-tracing package
*         Copyright 1997-2002, All rights reserved
*         Risoe National Laboratory, Roskilde, Denmark
*         Institut Laue Langevin, Grenoble, France
*
* Component: Monitor
*
* %I
* Written by: Kim Lefmann
* Date: October 4, 1997
* Version: $Revision: 1.21 $
* Origin: Risoe
* Release: McStas 1.6
*
* Simple single detector/monitor.
*
* %D
* Sums neutrons (0th, 1st, and 2nd moment of p) flying through
* the rectangular monitor opening. May also be used as detector.
*
* Example: Monitor(xmin=-0.1, xmax=0.1, ymin=-0.1, ymax=0.1)
*
* %P
* INPUT PARAMETERS:
*
* xmin: Lower x bound of opening [m]
* xmax: Upper x bound of opening [m]
* ymin: Lower y bound of opening [m]
* ymax: Upper y bound of opening [m]
* xwidth:   Width/diameter of detector (x). Overrides xmin,xmax. (m)
* yheight:  Height of detector (y). Overrides ymin,ymax. (m)
*
* OUTPUT PARAMETERS:
*
* Nsum:  Number of neutron hits
* psum:  Sum of neutron weights
* p2sum: 2nd moment of neutron weights
*
* %E
*******************************************************************************/

DEFINE COMPONENT Monitor
DEFINITION PARAMETERS ()
SETTING PARAMETERS (xmin=0, xmax=0, ymin=0, ymax=0, xwidth=0, yheight=0)
OUTPUT PARAMETERS (Nsum, psum, p2sum)
STATE PARAMETERS (x,y,z,vx,vy,vz,t,s1,s2,p)
DECLARE
  %{
    double Nsum;
    double psum, p2sum;
  %}
INITIALIZE
  %{
    psum = 0;
    p2sum = 0;
    Nsum = 0;

    if (xwidth  > 0) { xmax = xwidth/2;  xmin = -xmax; }
    if (yheight > 0) { ymax = yheight/2; ymin = -ymax; }

    if ((xmin >= xmax) || (ymin >= ymax)) {
            printf("Monitor: %s: Null detection area !\n"
                   "ERROR    (xwidth,yheight,xmin,xmax,ymin,ymax). Exiting",
           NAME_CURRENT_COMP);
      exit(0);
    }
  %}
TRACE
  %{
    PROP_Z0;
    if (x>xmin && x<xmax && y>ymin && y<ymax)
    {
      Nsum++;
      psum += p;
      p2sum += p*p;
      SCATTER;
    }
  %}
SAVE
  %{
    DETECTOR_OUT_0D("Single monitor " NAME_CURRENT_COMP, Nsum, psum, p2sum);
  %}

MCDISPLAY
%{
  magnify("xy");
  multiline(5, (double)xmin, (double)ymin, 0.0,
               (double)xmax, (double)ymin, 0.0,
               (double)xmax, (double)ymax, 0.0,
               (double)xmin, (double)ymax, 0.0,
               (double)xmin, (double)ymin, 0.0);
%}

END
