#include <farfalla.h>
#include <eventNode.h>
#include <stopNode.h>
#include <dream.h>
#include <iomanip.h>

extern eventNode *ev;
static stopNode *stopBank;

void dreamMakeStopNodes() 
{
  union {int i[1000]; short s[2000];} data; 

  int index[3], ierr[3]; 
  static int iSM;
  static int MVAX;
  // First check to see if there are STOP equips in any microvax

  dsaget_("DECO",1,40,1,index[0],ierr[0]);
  dsaget_("DECO",2,40,1,index[1],ierr[1]);
  dsaget_("DECO",3,40,1,index[2],ierr[2]);

  // If every mVax returns -1 bail 
  if ((ierr[0]!=0) && (ierr[1]!=0) && (ierr[2]!=0)) return;
//  cout << "found some stop nodes" << endl;

  F_addChild(ev,stopBank);	// Make the STOP node
//  cout << "Added a stop node" << endl;

  for (MVAX=0; MVAX < 3; MVAX++)
  {
    //If this particular MVAX is empty then initialize both SMs to zero
    if ( ierr[MVAX] )
    {
      for (iSM=0; iSM<2; iSM++)
      {
	// zero the trigger times and register
	stopBank->trigRegister[2*MVAX+iSM]=0;
	for(int trigger=0;trigger<=7;trigger++)
	  stopBank->trigTime[2*MVAX+iSM][trigger]=0;

	// zero the tohm face times and register
	stopBank->tohmRegister[2*MVAX+iSM]=0;
	for(int tohmface=0;tohmface <=7; tohmface++)
	  stopBank->faceTime[2*MVAX+iSM][tohmface]=0;
      }
    }
    else
    {
      int ierr;
// read a word to get the equip length
      dsaget_("RAWW",1,index[MVAX],1,data.i[0],ierr);
      int length = data.s[0];
// now read the entire block (skipping the length word)
      dsaget_("RAWW",1,index[MVAX]+2,length,data.i[0],ierr);
      for (iSM=0; iSM<2; iSM++)
      {
	// The Stop Master Manual and the CAMAC list aggree on the 
	// following order in data  (everything is a short)
	// trigger register1, tohm1,erp1,stmono1,fmt1,cspam1,lip1,hip1,spare1
	// CIT register1, c1, b1, w1, e1, ns1, t1, sm1-, sm1+
	// trigger register2, tohm2,erp2,stmono2,fmt2,cspam2,lip2,hip2,spare2
	// CIT register2, c2, b2, w2, e2, ns2, t2, sm2-, sm2+
	stopBank->trigRegister[2*MVAX+iSM]=data.s[iSM*18+0];
	for(int trigger=0;trigger <=7; trigger++)
	  stopBank->trigTime[2*MVAX+iSM][trigger]=data.s[iSM*18+1+trigger];

	stopBank->tohmRegister[2*MVAX+iSM]=data.s[iSM*18+9];
	for(int tohmFace=0;tohmFace<=7; tohmFace++)
	  stopBank->faceTime[2*MVAX+iSM][tohmFace]=data.s[iSM*18+10+tohmFace]; 

     }     // For loop
    } // if else
  } // for loop
}

  
