/*******************************************************************************
*
* McStas, neutron ray-tracing package
*         Copyright 1997-2002, All rights reserved
*         Risoe National Laboratory, Roskilde, Denmark
*         Institut Laue Langevin, Grenoble, France
*
* Component: Scatter_log_iterator_stop.comp
*
* %I
*
* Written by: Erik B Knudsen
* Date: November 2012
* Version: $Revision: 1.21 $
* Release: McStas 2.1
* Origin: DTU Physics
*
* Iteration stop element for a Scatter_log
*
* %D
*
* This component marks the end of the trace-region in which pseudo-neutrons are handled. 
*   Please see the Scatter_log_iterator-component for more details.
*
* N.B. This component must be immediately followed by a construction like:
*   COMPONENT iter1 = Scatter_log_iterator(...)
*   ...
*   COMPONENT iter2 = Scatter_log_iterator_stop(iterator="iter1") AT (...)
*   COMPONENT a1 = Arm()
*   AT (0,0,0) ABSOLUTE
*   JUMP a0 WHEN(COMP_GETPAR(iter2, loop))
*
* This is to extract the value of the loop variable from the innards of this component
*
* %P
* Input parameters:
*
* iterator: [string] Instance name of the Scatter_log_iterator log component preceeding this one.
*
* %E
*******************************************************************************/

DEFINE COMPONENT Scatter_log_iterator_stop

SETTING PARAMETERS (string iterator)

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

DECLARE
%{
  int loop;
%}

INITIALIZE
%{
  loop=1;
%}


TRACE
%{
  scatter_iterator_stop:
  loop=1;
  struct Generalized_State_t *s1 = COMP_GETPAR3(Scatter_log_iterator, iterator, s1);

  if (s1->_p==-1){
    /*we have reached the end - unset loop and reset neutron state to whatever it was before we entered the pseudo neutron iterator*/
    loop=0;
    double *ns = COMP_GETPAR3(Scatter_log_iterator, iterator, nstate_initial);
    x=ns[0];y=ns[1];z=ns[2];
    vx=ns[3];vy=ns[4];vz=ns[5];
    t=ns[6];
    sx=ns[7];sy=ns[8];sz=ns[9];
    p=ns[10];

    free(ns);
    ns = NULL;

    /* Restore std ABSORB */
#undef mcabsorb
#define mcabsorb mcabsorbAll
  }
%}

MCDISPLAY
%{
  /* A bit ugly; hard-coded dimensions. */

  line(0,0,0,0.2,0,0);
  line(0,0,0,0,0.2,0);
  line(0,0,0,0,0,0.2);
%}

END
