/****************************************************************************
 *  F i l e   D a t a                                                        
 *  $Id: RM_RunManager_INFN.c,v 1.138 2005/03/23 10:22:56 sebastiani Exp $
 *  $Revision: 1.138 $ 
 *  $Date: 2005/03/23 10:22:56 $
 *  $RCSfile: RM_RunManager_INFN.c,v $
 *                                                                           
 ****************************************************************************
 *  S W   D e v e l o p m e n t   E n v i r o n m e n t                      
 *                                                                           
 *  $Author: sebastiani $
 *               :                                                           
 ****************************************************************************
 *  U p d a t i n g                                                          
 *                                                                           
 *  $Log: RM_RunManager_INFN.c,v $
 *  Revision 1.138  2005/03/23 10:22:56  sebastiani
 *  RM_Init_ParamBuffers called in RM_Init
 *
 *  Revision 1.137  2005/03/21 13:46:49  faber
 *  TRIG_II software introeduces as emtpy commands.
 *  DNLK_TIM started at start downlink in order to be sure end of download.
 *
 *  Revision 1.136  2005/03/20 18:25:59  sebastiani
 *  new formato of run header. better logging. PRH_VAR_TB_OK removed
 *
 *  Revision 1.135  2005/03/15 17:28:55  faber
 *  TRIG_II level first introduced
 *
 *  Revision 1.134  2005/03/14 16:12:58  sebastiani
 *  WS3 debugging:some fixes
 *
 *  Revision 1.133  2005/03/13 18:13:38  sebastiani
 *  RM_OP_DOWNLOAD_HEADER operation introduced to write haader for the VRL (instead of mashroute)
 *
 *  Revision 1.132  2005/03/06 14:54:46  sebastiani
 *  version running on 06 03 2005
 *
 *  Revision 1.131  2005/02/22 18:09:25  sebastiani
 *  various bugfixes
 *
 *  Revision 1.130  2005/02/21 08:58:29  sebastiani
 *  all log comments completed
 *
 *  Revision 1.129  2005/02/19 10:19:38  sebastiani
 *  ALM_S4_CALIB_00_HARD,ALM_S4_CALIB_00_SOFT,ALM_S4_128TRIGGER_0 added
 *
 *  Revision 1.127  2005/01/11 13:59:48  faber
 *  *** empty log message ***
 *
 *  Revision 1.126  2005/01/10 14:02:13  faber
 *  TRG,AC_1,AC_2,TOF Error Handler reviewed
 *
 *  Revision 1.125  2005/01/10 09:48:35  sebastiani
 *  fix warning
 *
 *  Revision 1.124  2005/01/07 15:41:51  sebastiani
 *  fix alarm precedure
 *  add exp 64 delay patch
 *  removed unused sleep
 *
 *  Revision 1.123  2004/12/21 17:44:55  faber
 *  CAL_DSP_MASK into RunHeader
 *
 *  Revision 1.122  2004/12/21 16:35:54  faber
 *  DUMMY command introduced into ACQ command queue in case of ACQ_After_Calib
 *  and TRK_OK
 *
 *  Revision 1.121  2004/12/21 14:14:16  sebastiani
 *  RM_TaskSuspendUnlessSINT bug fix if time is zero
 *
 *  Revision 1.120  2004/12/21 11:14:09  faber
 *  {Var,Arr,Tab}  not stored in mass memory re now dumped in the Flush procedure
 *
 *  Revision 1.119  2004/12/20 14:02:04  faber
 *  @LOG entry introduced in all ALM_WriteLog occurrences
 *
 *  Revision 1.118  2004/12/20 10:02:12  faber
 *  TRK initialization/calibration/acq procedure fixes
 *
 *  Revision 1.117  2004/12/17 16:20:59  faber
 *  *** empty log message ***
 *
 *  Revision 1.116  2004/12/17 12:46:40  faber
 *  ALARM REGISTER aligned to be 32 bit. memory aling core dump (should be) fixed
 *
 *  Revision 1.115  2004/12/15 14:13:28  faber
 *  femask and acq_build_info introduced in Run header
 *
 *  Revision 1.114  2004/12/15 09:29:43  sebastiani
 *  FT_piChangeAcqMode(SM_DAQSETUP); removed from Send_ForceIDAQ; '|0x0002' removed in  khb_status=ALM_FE_Acquisition_Check() | 0x0002; new information in the run header
 *
 *  Revision 1.113  2004/12/02 10:43:38  sebastiani
 *  fix AC
 *  fix CAL
 *  fix HK BUFTYPE
 *
 *  Revision 1.112  2004/11/30 12:50:14  faber
 *  *** empty log message ***
 *
 *  Revision 1.111  2004/11/30 11:51:53  faber
 *  AC+AC2 software moved into AC_1 AC_2
 *  new calibration and initialization for AC
 *  first version,never run
 *
 *  Revision 1.110  2004/11/19 15:14:52  sebastiani
 *  PRH_EXTERN_{VAR,ARR,TABLE} removed and put them on the autogenerated parameter heeader file
 *
 *  Revision 1.109  2004/11/10 17:00:00  sebastiani
 *  - GS_COMPILE directive introduced and be undef by default
 *  - automatic flush mechanism by run manager mailbox timeout
 *
 *  Revision 1.108  2004/11/05 16:43:07  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.107  2004/11/05 09:36:35  sebastiani
 *  first version of the PM state machine. tried but not deeply tested
 *
 *  Revision 1.106  2004/11/02 15:41:39  faber
 *  *** empty log message ***
 *
 *  Revision 1.105  2004/10/11 07:28:14  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.104  2004/10/08 15:57:51  sebastiani
 *  fix power hot cold variables settings.
 *  fix ws
 *  added function to set khb hot or cold
 *
 *  Revision 1.103  2004/10/04 15:57:05  faber
 *  Run Trailer
 *
 *  Revision 1.102  2004/10/04 13:59:05  alfarano
 *  fixed some return code in run manager
 *
 *  Revision 1.101  2004/10/01 09:20:23  alfarano
 *  AC2 and little bug fix on S4 return code
 *
 *  Revision 1.100  2004/10/01 08:48:10  sebastiani
 *  TRD alarma renamed TRD_S4  - S4 Alarm renamed S4_POWER
 *  Callback function into DAQ_SendCmd2PIFWaitDAQReply_internal
 *
 *  Revision 1.99  2004/09/28 15:36:25  sebastiani
 *  interrupt manager fix
 *
 *  Revision 1.98  2004/09/22 15:54:54  alfarano
 *  S4 functions
 *
 *  Revision 1.97  2004/09/17 15:01:00  faber
 *  LU_INFN_LOG flags fixing
 *
 *  Revision 1.96  2004/09/13 14:16:53  faber
 *  ErrorHandler for TOF/TRG + Test function TOF/TRG
 *
 *  Revision 1.95  2004/09/09 14:52:55  sebastiani
 *  using PreparePage to send cmd to idaq/FE
 *  added some test
 *  added trigger param
 *  added/tested Force Send KHB_to_FE
 *  added/tested Send Cmd to IDAQ/FE
 *
 *  Revision 1.94  2004/09/08 10:39:12  faber
 *  *** empty log message ***
 *
 *  Revision 1.93  2004/08/31 09:08:35  sebastiani
 *  fix warning
 *
 *  Revision 1.92  2004/08/30 07:08:18  sebastiani
 *  little modify
 *
 *  Revision 1.91  2004/08/26 16:54:34  sebastiani
 *  version work fine
 *
 *  Revision 1.90  2004/08/13 14:42:19  sebastiani
 *  Add Neutron detector!
 *  need add file ND_READ_ACQ.dat on site ...
 *
 *  Revision 1.89  2004/08/05 16:19:07  sebastiani
 *  fix close run
 *  add cal handler error
 *  fix tmtc
 *  ok protocol betwen pm-rm-scm
 *
 *  Revision 1.88  2004/08/04 13:25:21  sebastiani
 *  first fix allarm procedure
 *
 *  Revision 1.87  2004/08/02 15:49:47  alfarano
 *  alarm handling , scm & pm communication rewrite
 *
 *  Revision 1.86  2004/08/02 09:28:29  faber
 *  Stamp management into SMH_SetParam
 *  TS_PamManger TM_RMTest moved respectively into PM and RM as PM_MCMDTest and
 *  RM_MCMDTEst. TS_Test_INFN.c will be deleted soon.
 *
 *  Revision 1.85  2004/07/28 17:19:01  sebastiani
 *  better loggin status
 *
 *  Revision 1.84  2004/07/28 09:03:36  sebastiani
 *  bufgix unmask khb mask all
 *
 *  Revision 1.83  2004/07/27 17:30:17  faber
 *  OBT can be now in second or milliseconds, depending of the situazion.
 *  OBT_s is used for FM compatibility, OBT_ms basically for MM infos
 *
 *  Revision 1.82  2004/07/27 08:35:42  sebastiani
 *  fix bug WS1
 *  add test CPU idle
 *  fix PADDING
 *
 *  Revision 1.81  2004/07/26 15:04:54  faber
 *  CM_BIT_REVERSE and OS_PROTECTED_INT introduced
 *
 *  Revision 1.80  2004/07/21 14:08:32  sebastiani
 *  Fix close RUN we wait a event to close the run
 *  PM send Sint and don't wait for SintOK
 *  Header'Trailer Initialization
 *  FixPacketCounter
 *
 *  Revision 1.79  2004/07/20 14:36:26  sebastiani
 *  AC/CAL/TRK/TOF/TRG unmaksed all KHB alarms
 *  RM: Close Run before RunTrailer (send page 2)
 *
 *  Revision 1.78  2004/07/15 10:50:28  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.77  2004/07/15 10:39:42  faber
 *  *** empty log message ***
 *
 *  Revision 1.76  2004/07/15 08:21:26  faber
 *  *** empty log message ***
 *
 *  Revision 1.75  2004/07/14 13:02:35  alfarano
 *  update calorimeter func
 *
 *  Revision 1.74  2004/07/12 09:51:49  faber
 *  external_data dir added with all commands inside. tgz creation rules remove.
 *  AUTO mode introduced:
 *
 *  Revision 1.73  2004/07/08 16:23:41  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.72  2004/07/02 09:47:42  alfarano
 *  modifiche antic
 *
 *  Revision 1.71  2004/06/30 07:26:52  sebastiani
 *  TOF fixing,WS fixing
 *
 *  Revision 1.70  2004/06/25 09:54:41  alfarano
 *  *** empty log message ***
 *
 *  Revision 1.69  2004/06/24 16:32:50  alfarano
 *  TOF stuff
 *
 *  Revision 1.68  2004/06/22 11:05:43  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.67  2004/06/22 09:34:52  faber
 *  *** empty log message ***
 *
 *  Revision 1.66  2004/06/22 08:57:01  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.65  2004/06/15 16:48:27  sebastiani
 *  Check AC functions OK ( fix some little bugs)
 *  fix flows in RM
 *
 *  Revision 1.64  2004/06/15 08:24:37  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.63  2004/06/09 11:23:22  alfarano
 *  EEPROM Formatting/Checking/Reading/writing functions. not tested
 *
 *  Revision 1.62  2004/06/04 14:24:38  sebastiani
 *  clear some files
 *
 *  Revision 1.61  2004/06/01 16:41:19  sebastiani
 *  EventReceive ANY
 *
 *  Revision 1.60  2004/05/28 07:07:10  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.59  2004/05/27 17:50:40  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.58  2004/05/26 17:48:25  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.57  2004/05/26 15:31:54  sebastiani
 *  some fixing on CAL/TRK/ACQ
 *
 *  Revision 1.56  2004/05/26 11:15:16  sebastiani
 *  SentTrigger() introduced; RM_TaskSuspendUnlessSINT() introduced
 *
 *  Revision 1.55  2004/05/25 14:49:48  faber
 *  *** empty log message ***
 *
 *  Revision 1.54  2004/05/25 14:07:18  faber
 *  *** empty log message ***
 *
 *  Revision 1.53  2004/05/24 10:27:32  faber
 *  *** empty log message ***
 *
 *  Revision 1.52  2004/05/20 16:03:52  faber
 *  ACQ flow dev continuing
 *
 *  Revision 1.50  2004/05/19 08:44:38  sebastiani
 *  fix trk init and calib
 *
 *  Revision 1.49  2004/05/17 10:01:37  faber
 *  *** empty log message ***
 *
 *  Revision 1.48  2004/05/13 10:57:51  faber
 *  *** empty log message ***
 *
 *  Revision 1.47  2004/05/13 10:47:17  faber
 *  hid the HB_Store funcion in favour of wrapped funcions
 *
 *  Revision 1.46  2004/05/12 14:46:14  faber
 *  *** empty log message ***
 *
 *  Revision 1.45  2004/05/06 15:51:16  faber
 *  devel goes on...
 *
 *  Revision 1.44  2004/05/06 12:13:34  faber
 *  *** empty log message ***
 *
 *  Revision 1.43  2004/05/06 08:52:24  faber
 *  development goes on..
 *
 *  Revision 1.42  2004/05/04 17:20:51  sebastiani
 *  new GOM TEST mode introduced. Entry point in TS_RM_Test(c1,c2)
 *
 *  Revision 1.41  2004/04/29 10:18:26  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.40  2004/04/29 07:46:29  sebastiani
 *  compilation ok
 *
 *  Revision 1.39  2004/04/29 07:13:04  faber
 *  Working schedule development goes on...
 *
 *  Revision 1.38  2004/04/23 14:16:58  tassa
 *  - change for donwloading procedures vrl handling
 *  - fix little bug in error case in DoRun
 *  - add ForceBreakPoint selectmode
 *
 *  Revision 1.37  2004/04/20 14:51:16  alfarano
 *  #ifdef temporaneo su TRK
 *
 *  Revision 1.36  2004/03/03 11:17:50  tassa
 *  resolved merging conflict by hand
 *
 *  Revision 1.35  2004/03/03 11:13:58  sebastiani
 *  gen_mcmd.pl bugfixes,other bugfixes
 *
 *  Revision 1.34  2004/02/18 16:37:14  alfarano
 *  update calorimeter
 *
 *  Revision 1.33  2004/02/17 12:34:51  faber
 *  USERDATA2BUF USERDATA2{ARR,TAB} introduced with CRC.
 *  Never tested.
 *  Some adjustment in Logging in SHM module
 *
 *  Revision 1.32  2004/02/13 10:11:30  alfarano
 *  calorimeter initialization func and more
 *
 *  Revision 1.31  2004/02/05 11:38:16  sebastiani
 *  RM_DoRun changed to work better
 *
 *  Revision 1.30  2004/01/22 10:10:25  faber
 *  *** empty log message ***
 *
 *  Revision 1.29  2004/01/13 15:07:35  tassa
 *  add send forced idaq cmd!
 *
 *  Revision 1.28  2004/01/12 17:51:28  tassa
 *  manca solo la parte di invio e ricezione sulla/dalla IDAQ
 *
 *  Revision 1.27  2004/01/09 17:29:34  tassa
 *  add the force command queue procedure
 *
 *  Revision 1.26  2003/11/27 17:53:23  faber
 *  -Power management poweron procedure done and some tested in the simulator
 *  -history entry 5 now takes OBT
 *
 *  Revision 1.25  2003/11/19 15:48:37  faber
 *  *** empty log message ***
 *
 *  Revision 1.24  2003/11/13 16:13:55  sebastiani
 *  dump_parameters flag added to WriteHBInfos(); Important bugfixed and better management with ChangeAcqMode and SetNotifyTask_SKETCHBOARD()
 *
 *  Revision 1.23  2003/11/10 16:24:09  faber
 *  bugfix HB_Store/Write2PIF
 *
 *  Revision 1.22  2003/11/10 12:16:49  sebastiani
 *  new HB management / SetNotifyTask now put before the DoRun() invocation / some other bugfix around
 *
 *  Revision 1.21  2003/11/06 10:27:12  faber
 *  HB_HKBuffer now implemented as multibuffer (as specified in the
 *  mass memory format). Only compilation, not tested
 *
 *  Revision 1.20  2003/10/31 17:21:29  sebastiani
 *  bug fix on read and write function in TM_TMTCManager: added busy flag control on each read & write
 *  CRC functions updated in the SRAMPageManager
 *
 *  Revision 1.19  2003/10/29 17:41:48  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.18  2003/10/28 18:31:24  sebastiani
 *  Some fix about the KHB driver
 *
 *  Revision 1.17  2003/10/27 18:58:52  sebastiani
 *  Enabling/Disabling sample/storing TMTC data
 *  BC2RM code fix
 *
 *  Revision 1.16  2003/10/21 13:17:44  sebastiani
 *  more sofisticated tests (via test_debug SOM)
 *
 *  Revision 1.15  2003/10/20 15:31:12  sebastiani
 *  MCMDS autogenerated
 *
 *  Revision 1.14  2003/10/17 10:10:41  sebastiani
 *  SKETCHBOARD_FREE event introduced, better LOG
 *
 *  Revision 1.13  2003/09/25 16:53:03  alfarano
 *  buffer 16K 128K added.
 *
 *  Revision 1.12  2003/09/25 11:57:53  faber
 *  used MC_SetState instead of SM_AcqSetMode
 *
 *  Revision 1.11  2003/09/25 08:57:55  faber
 *  *** empty log message ***
 *
 *  Revision 1.10  2003/09/23 09:53:43  alfarano
 *  fixed a bug in calling CalibTracker
 *
 *  Revision 1.8  2003/09/22 09:59:35  faber
 *  new select mode definitions
 *
 *  Revision 1.7  2003/09/19 15:57:35  faber
 *  Large development update INFN software
 *
 *  Revision 1.6  2003/09/12 16:34:59  alfarano
 *  Tracker files rewrite
 *
 *  Revision 1.5  2003/09/10 16:15:52  faber
 *  PRH_EXTERN_VAR(XX_LOGMASK) removed (not needed any more)
 *
 *  Revision 1.4  2003/09/10 11:55:07  faber
 *  LU_MASK introduced. Log mask for module is now an unique array (PRH_ARR_LOG_MASK) indexed by __FILEID__
 *
 *  Revision 1.3  2003/09/10 10:32:37  faber
 *  Large implementation of PamManager/RunManager Pam Sowfare. (compiled,never rokun)
 *
 *  Revision 1.2  2003/08/22 07:57:08  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.1.1.1  2003/08/04 09:40:22  sebastiani
 *  Imported sources laben rel. 19.06.2003 integrated with pam2
 *
 *  Revision 1.6  2003/07/17 11:15:52  sebastiani
 *  idaq manager
 *  new print for logging in minicom
 *
 *  Revision 1.5  2003/07/10 07:05:14  sebastiani
 *  first IDAQ driver import
 *
 *  Revision 1.4  2003/06/23 15:40:10  sebastiani
 *  Trakcer added: First Compilation of tracker
 *
 *  Revision 1.3  2003/06/20 13:42:29  sebastiani
 *  Pam/Run manager first prototype release
 *
 *  Revision 1.2  2003/06/18 16:53:20  sebastiani
 *  Pam/Run Manager development update. ExpSeq sequence is receiven from the RunManager (simulator mode)
 *
 *  Revision 1.1  2003/06/16 08:08:28  sebastiani
 *  Moved RunManager's files in the RunManager dir
 *
 *  Revision 1.2  2003/06/13 16:44:27  sebastiani
 *  new version updated. develop continuing
 *
 *  Revision 1.1  2003/06/09 17:00:29  sebastiani
 *  Run Manager first scheleton
 *
 *                                                                           
 *****************************************************************************/


/*============================= Include File ================================*/

#include <src/INFN/LU_SourceFileID_INFN.h>
#define __FILEID__ _RM_RunManager_INFN__c

#include <src/INFN/LU_LogUtility_INFN.h>
#include <src/INFN/PRH_ParamHandler_INFN_auto.h>
#include <src/INFN/PRH_ParamHandler_INFN_autopri.h>
#include <src/INFN/PM_PamManager_INFN.h>
LU_DECL_MASK();

#include <src/SRAMManager/SRAMPageManager/SM_SRAMPageManager_p.h>
#include <src/FileManager/MMSUManager/FT_MMSUManager_p.h>

#include <src/INFN/RM_RunManager_INFN.h>
#include <src/INFN/HB_HKBuffer_INFN.h>
#include <src/INFN/CH_CommandHandler_INFN.h>
#include <src/INFN/OS_rtems_INFN_p.h>
#include <src/INFN/WS_WorkingSchedule_INFN.h>
#include <src/INFN/DAQ_IDAQ_INFN.h>
#include <src/INFN/TRK_Tracker_INFN.h>
#include <src/INFN/CAL_Calorimeter_INFN.h>
#include <src/INFN/AC_Anticoincidence_INFN.h>
#include <src/INFN/S4_INFN.h>
#include <src/INFN/OS_rtems_INFN_p.h>
#include <src/INFN/KHB_Driver_INFN.h>
#include <src/INFN/HK_Manager_INFN.h>
#include <src/INFN/TRG_Trigger_INFN.h>
#include <src/INFN/TOF_TimeOfFlight_INFN.h>
#include <src/INFN/ALM_Alarm_INFN.h>
#include <src/INFN/PRH_ParamHandler_INFN.h>
#include <src/INFN/MH_ModeHandler_INFN.h>

/*============================ Global define ================================*/


/*============================== global types  ==============================*/



/*****************************************************************************/
/*=========================== Structure define ==============================*/


/*****************************************************************************/
/*============================ Enumerate define =============================*/

typedef enum {
  IPM1,
  IPM2,
  IPM3,
  IPM4,
  IPM5,
  IPM6,
  IPM_MAX
} IPM;



/*****************************************************************************/

/*=== RunManager   P R O V I D E D    I N T E R F A C E ==*/

/*****************************************************************************/

/* DAQ buffer */
DAQ_DECLBUF(RM_buf_cmd,SM_SRAMPAGESIZE);
DAQ_DECLBUF(RM_buf_misc,HB_BUF_MISC_SIZE);
DAQ_DECLBUF(RM_buf_data,SM_DAQPKTSIZE);
//DAQ_DECLBUF(RM_buf_cmd2,SM_SRAMPAGESIZE);
//DAQ_DECLBUF(RM_buf_cmd3,SM_SRAMPAGESIZE);
//DAQ_DECLBUF(RM_buf_cmd4,SM_SRAMPAGESIZE);
DAQ_DECLBUF(RM_128K_Buffer,SM_DAQPKTSIZE);


/* Force Idaq commands */
DAQ_DECLBUF(force_idaq_cmd_queue,SM_SRAMPAGESIZE);


/* Pre-Cooked commands */
DAQ_DECLBUF(nd_acq_buf,2);


/* the standard Make acquisition command : */
/*
DAQ_DECLBUF(PM_buf_make_acq_full,8);
DAQ_DECLBUF(PM_buf_make_acq_compress,100);
DAQ_DECLBUF(PM_buf_make_acq,1024);
DAQ_DECLBUF(PM_buf_init_run,1024);
DAQ_DECLBUF(PM_buf_data,1024);
*/

/* this variables come from the calorimeter calibration */
extern PRH_VAR_TYPE CAL_DSP_MASK;
extern PRH_VAR_TYPE CAL_FE_MASK;


extern UINT32 TRK_ALARM_MASK[2];
#define TRK_MASK_BASE_ID CH_TRK_MASK_064
#define TRK_MASK_BASE_OFFSET 64


static RM_OPCODES RM_TaskStatus;

static BOOL RM_Run_Is_In_Progress;
static UINT32  RM_Initialization_Counter;
static BOOL RM_use_nd=TRUE;

/* this var counts the number of Run done after an ascending node. 
   the value is reset after an ascending node.
   it have nothing to do with the calibration 
*/
static BOOL RM_Is_Run_After_Ascending_Node;

/* a counter of the number of run since the boot */
static UINT32 RM_Run_Counter;

/* a counter of number of run with no pkt since the boot */
static UINT32 RM_Init_Run_With_No_Pkt;
/* a counter of the number of calibrations since the  boot */
static UINT32 RM_Calibration_Counter;

/* counters for events (OS_EVENT_XXX) and other pkt result of the run routine */
static UINT32 	 RM_PktReady_Counter;
static UINT32 	 RM_ETO_Counter;
static UINT32    RM_TIMEOUT_Counter;
static UINT32 	 RM_SINT_Counter;

static RM_ACQ_SETTING  RM_Acq_setting_mode;
static TI_TIME         RM_run_real_duration_ms;
static TI_TIME         RM_end_of_run_obt_s;

static BOOL      RM_Rate_meter_check;
static BOOL      RM_Acq_After_Calib;
BOOL      RM_Init_Before_Calib;
static UINT32    RM_Calibration_Counter;
static UINT32    RM_Acq_Cmd_Queue_len;

static BOOL RM_acqcheck_flag;

#ifdef DEBUG
static BOOL RM_storeram = DAQ_STORE_RAM;
#else
static BOOL RM_storeram = DAQ_NO_STORE_RAM;
#endif


static unsigned char RM_AcqExitIfError_FILEID;

static DAQ_CMD_BUF TRIG_II_INIT;
static DAQ_CMD_BUF TRIG_II_ACQ;


static DAQ_CMD_BUF IDAQ_DSP_SET;




void RM_Init_ParamBuffers() {
#warning  DAQ_INIT_BUF_FROM_PARAMBUF(IDAQ_DSP_SET);
  DAQ_INIT_BUF_FROM_PARAMBUF(TRIG_II_INIT);
  DAQ_INIT_BUF_FROM_PARAMBUF(TRIG_II_ACQ);
}


/*****************************************************************************/
/* @Function: RM_piInitRunManager_INFN                                        */
/* @Purpose :                                                                */
/*  Provided Interface to initialize the RunManager object.                   */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  status_code          OUT     Return code                                 */
/* @@                                                                        */
/*****************************************************************************/

status_code RM_Init_AtoEto() {
#warning ETO ATO TBD here !
  CH_PARAMBUF_SET_ATO_ETO(IDAQ_DSP_SET,2,2);
  #warning CH_SetAtoEto(CH_IDAQ_DSP_START_PROGRAM,2,2);
  #warning CH_SetAtoEto(CH_IDAQ_DSP_DATA_READ,2,2);
  return CM_RC_SUCCESSFUL;
}

status_code RM_InitRunManager_INFN(void) {
  status_code status;
  unsigned int  OldPriority;
  
    status  =SUCCESSFUL;
    
    /* Task initialization                           */
    if ((status=OS_piTaskReady_INFN(RM_INFN_TASK,RM_tkRunManager_INFN)) != SUCCESSFUL)
      {
        /*@LOG Task is not correctly started */
	LU_INFN_LOG(LU_FATAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
	// HA_piLogHistoryEntry10(HA_E10_SW_MD,HA_E10_TSK_READY_ERR,status);    
	status  =UNSATISFIED;
      }
    if ((status=OS_piTaskPriority_INFN(RM_INFN_TASK,RM_INFN_PRIORITY,&OldPriority)) != SUCCESSFUL)
      {

	// HA_piLogHistoryEntry10(HA_E10_SW_MD,HA_E10_TSK_PRIORITY_ERR,status);    

	/*@LOG Task priority is not correctly updated */
	LU_INFN_LOG(LU_CRITICAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
	status  =UNSATISFIED;
      }
  
    /* init all declared command buffers: */

    RM_TaskStatus = RM_OP_IDLE;
    RM_Run_Is_In_Progress = FALSE;
    RM_Is_Run_After_Ascending_Node = FALSE;
    RM_Run_Counter = 0;
    RM_Calibration_Counter = 0;

    RM_PktReady_Counter=0;
    RM_ETO_Counter=0;
    RM_SINT_Counter=0;
    RM_Init_Run_With_No_Pkt=0;
    RM_TIMEOUT_Counter=0;

    RM_Acq_setting_mode=RM_ACQ_SETTING_NULL;
    RM_run_real_duration_ms=0;

    RM_Rate_meter_check=FALSE;
    RM_Acq_After_Calib=FALSE;
    RM_Calibration_Counter=0;
    DAQ_BUFFER_INIT(RM_buf_cmd);
    DAQ_BUFFER_INIT(RM_buf_misc);
    DAQ_BUFFER_INIT(RM_128K_Buffer);
    DAQ_BUFFER_INIT(RM_buf_data);

    DAQ_BUFFER_INIT(nd_acq_buf);
    nd_acq_buf.len=2;
    nd_acq_buf.buf[0]=0;
    nd_acq_buf.buf[1]=0;
    nd_acq_buf.eto=2;
    nd_acq_buf.ato=1;
    RM_Init_ParamBuffers();
    RM_Init_AtoEto();
    return (status);
}



status_code RM_SendCodeRunManager(RM_OPCODES code) {
  MsgTsk SndMsg;
  SndMsg.Code = code;
  return RM_SndMsgRunManager_INFN(&SndMsg);
}


status_code RM_SendTest(UINT32 code1,UINT32 code2,UINT32 code3) {
  MsgTsk SndMsg;
  BYTE *p=SndMsg.Info;
  SndMsg.Code = RM_OP_TEST;
  CM_WRITE_BE_UINT32(p,code1);
  CM_WRITE_BE_UINT32(p,code2);
  CM_WRITE_BE_UINT32(p,code3);
  return RM_SndMsgRunManager_INFN(&SndMsg);
}


status_code RM_CancelACQTimers() {
  OS_piCancelTimer_INFN(STOPACQ_TIM);
  OS_piCancelTimer_INFN(RM_WS3_TIM);
  return SUCCESSFUL;
}

status_code RM_SndMsgRunManager_INFN(MsgTsk* SndMsg) {
rtems_status_code status;


    /* Send message to HouseKeeping Manager  task mailbox                */
    status =OS_piMsgQueueSend_INFN(RM_INFN_MAILBOX,(void*)SndMsg,sizeof(MsgTsk));
    if (status != SUCCESSFUL)
    {
      /*@LOG Error Sending message to Run Manager */
      LU_INFN_LOG(LU_FATAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);      
      //HA_piLogHistoryEntry10(HA_E10_SW_MD,HA_E10_SEND_MSG_ERR,status); 
    }
    return (status);
}

status_code RM_SendSINT() {
  status_code status;
  if( (status = OS_piEventSend(RM_INFN_TASK,OS_EVENT_SINT)) != SUCCESSFUL) {
    /*@LOG Error Sending Event SINT to Run Manager */
    LU_INFN_LOG(LU_INTERNAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    return status;
  }
  if( (status = RM_SendCodeRunManager(RM_OP_SINT)) != SUCCESSFUL)
    /*@LOG ErrorSending message SINT to Run Manager */
    LU_INFN_LOG(LU_INTERNAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
  return status;
}

status_code RM_SendHBStoreRequest() {
  status_code status = SUCCESSFUL;

  if( RM_RunIsInProgress() )
    {
      if( (status = OS_piEventSend(RM_INFN_TASK,OS_EVENT_FLUSH_HB)) != SUCCESSFUL) {
	/*@LOG Error Sending Event FLUSH_HB to Run Manager */
	LU_INFN_LOG(LU_INTERNAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
      }
    }else{
      if( (status = RM_SendCodeRunManager(RM_OP_FLUSH_HB)) != SUCCESSFUL)
	/*@LOG Error Sending Message FLUSH_HB to Run Manager */
	LU_INFN_LOG(LU_INTERNAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    }
  return status;    
}

/* return true if a SINT had been received and clear the event 
   this function must be called only by the RunManager
 */

BOOL RM_CheckSINT() {
  rtems_event_set unused;
  BOOL ret;
  ret=OS_piEventReceive(OS_EVENT_SINT,RTEMS_NO_WAIT,0,&unused) == RTEMS_SUCCESSFUL;
  if(ret)
    RM_SINT_Counter++;
  return ret;
}

/* suspend for a certain tics and return TIMEOUT. if a SINT event come meanwhile, returns CM_RC_SINT immediatelly */
status_code RM_TaskSuspendUnlessSINT(UINT32 timeout) {
  status_code s;
  rtems_event_set evout;
  s=OS_piSuspendUnlessEvent(OS_EVENT_SINT,
			    timeout,
			    &evout );
  if(s==SUCCESSFUL && (evout | OS_EVENT_SINT))
    return CM_RC_SINT;
  return CM_RC_SUCCESSFUL;
}


task RM_tkRunManager_INFN (task_argument unused) {

  MsgTsk        RxMsg;
  BOOL flush_req;
  status_code   mboxstatus;
  status_code     op_ret_code;
  unsigned int  MsgSize;
  UINT32 async_flush_req=0;
  status_code status;

  while(FOREVER) {
    /* clear the SINT event: */
    RM_CheckSINT();

    RM_TaskStatus = RM_OP_IDLE;

    mboxstatus = OS_piMsgQueueReceive_INFN (RM_INFN_MAILBOX,(void*)&RxMsg,
					    &MsgSize,WAIT, 
					    PRH_VAR_RM_FLUSH_TIMEOUT ? PRH_VAR_RM_FLUSH_TIMEOUT : NO_TIMEOUT);
    
    if (mboxstatus == SUCCESSFUL) {
      RM_TaskStatus = RxMsg.Code;
      
      if(MH_DownloadIsInProgress()) 
	{
	  /*@LOG Command arrived while a downling */
	  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_TaskStatus);
	  MH_SetLastIgnoredOpDuringDownload(RM_TaskStatus);
	  // return a special exit code: this will be ignored by the PM state machine (PM_DecodeCode)
	  op_ret_code=CM_RC_DOWNLOAD_IS_IN_PROGRESS;
	}
      else
	switch(RM_TaskStatus) {
	case  RM_OP_INITIALIZATION:
	  // MC_piSetState(MC_ACTIVE_STATE);
	  /*@LOG RUN Manager Initialization started */
	  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RxMsg.Code);	
	  op_ret_code=RM_Initialization();
	  break;
	case  RM_OP_CALIBRATION:
	  /*@LOG RUN Manager Calibration started */
	  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RxMsg.Code);	
	  op_ret_code=RM_Calibration();
	  break;
	case  RM_OP_ACQUISITION:
	  /*@LOG RUN Acquisition Initialization started */
	  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RxMsg.Code);	
	  op_ret_code=RM_Acquisition();
	  break;
	case RM_OP_DOWNLOAD_HEADER:
	  /*@LOG RUN Download Header write */
	  {
	    static BOOL first_time=1;
	    if(first_time){
	      first_time=0;
	      OS_piTaskSuspend(1000);
	      MC_piSetState(MC_ACTIVE_STATE);	      
	      OS_piTaskSuspend(1000);
	      DAQ_ResetPIF(DAQ_DEFAULT_ETO_TICS,DAQ_DEFAULT_DTO_TICS,SM_DAQSETUP,HB_PKTTYPE_RSV_RUN_MANAGER_INIT);
	      OS_piTaskSuspend(1000);
	    }
	  }
	  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RxMsg.Code);
	  op_ret_code=RM_WriteDownloadHeader(PRH_VAR_DOWNLOAD_HEADER++);
	  break;
	case RM_OP_FLUSH_HB:
	  // do nothing here: is done at the end.
	  /*
	  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RxMsg.Code);	
	  if( (op_ret_code=RM_WriteHBInfos(TRUE)) != SUCCESSFUL ) 
	    LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,op_ret_code);	
	  op_ret_code = CM_RC_SUCCESSFUL;
	  */
	  break;
	case RM_OP_FORCE_IDAQCMD:
	  /*@LOG RUN Manager ForceIDAQCommand started */
	  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RxMsg.Code);
	  op_ret_code=RM_Send_ForceIdaqCmd();
	  if (op_ret_code)
	    /*@LOG RUN Manager SendForceIdaqCmd failed */
	    LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,op_ret_code);	
	  op_ret_code = CM_RC_SUCCESSFUL;
	  break;
	case RM_OP_SINT:
	  /*@LOG Run Manager SINT received */
	  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RxMsg.Code);	
	  /* must do nothing, only gets such a messages,
	     clear the SINT event, and notify a SINT_OK */
	  RM_CheckSINT();
	  op_ret_code = OS_piEventSend(PM_INFN_TASK,OS_EVENT_SINT_OK);
	  if(op_ret_code != SUCCESSFUL)
	    /*@LOG error sending event OS_EVENT_SINT_OK to  Pam Manager*/
	    LU_INFN_LOG(LU_INTERNAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,op_ret_code);	
	  op_ret_code = CM_RC_SUCCESSFUL;
	  break;
	case RM_OP_TEST:
	  {
	    UINT32 value1,value2,value3;
	    BYTE tmp;
	    BYTE *p=RxMsg.Info;
	    CM_READ_BE_UINT32(p,value1,tmp);
	    CM_READ_BE_UINT32(p,value2,tmp);
	    CM_READ_BE_UINT32(p,value3,tmp);
#ifdef DEBUG
	    RM_MCMDTest(value1,value2,value3);
#endif
	    op_ret_code=CM_RC_SUCCESSFUL;
	  }
	  break;
	default:
	  op_ret_code=CM_RC_SUCCESSFUL;
	  /* bad/unrecognized operation here. If a bad op comes here, it's internal error beacuse 
	     the PamManager should check and filter the code before */
	  /*@LOG Bad operation */
	  LU_INFN_LOG(LU_INTERNAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,RxMsg.Code);	
	  break;
	}

      RM_BC2PM(RM_TaskStatus,op_ret_code);
    }

    if(op_ret_code=HB_GetFlushRequestFlag(&flush_req) )
      /*@LOG HB_GetFlushRequestFlag failed in Run Manager */
      LU_INFN_LOG(LU_FATAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,op_ret_code);	
    if( (flush_req || RM_TaskStatus==RM_OP_FLUSH_HB ||  RM_TaskStatus == RM_OP_CALIBRATION) 
	&& !MH_DownloadIsInProgress() ) {
      async_flush_req++;
      if( (op_ret_code=RM_WriteHBInfos( RM_TaskStatus == RM_OP_CALIBRATION ? TRUE : (PRH_VAR_RM_NO_FLUSH_PARAM_DUMP ? async_flush_req % PRH_VAR_RM_NO_FLUSH_PARAM_DUMP == 0 : FALSE ))) != SUCCESSFUL ) 
	/*@LOG WriteHB Infos failed in Run Manager */
	LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,op_ret_code);	
      else {
	HB_ResetFlushRequestCounter();
	/*@LOG WriteHB Infos successfull in Run Manager */
	LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xAAAF1055);	
      }
    }
    /* do this in any case: both at end of operation or in a IDLE timeout */
  }
}


/* this is the user routine of the WS3 Timer, 

*/
rtems_timer_service_routine RM_WS3_ISR(
  rtems_id   timer_id,
  void      *unused
  ) {
  RM_Rate_meter_check=TRUE;
}

rtems_timer_service_routine RM_StopAcq_ISR(
  rtems_id   timer_id,
  void      *run_counter
  ) {
  PM_SendCommand(PM_INFN_NEXTRUN);
}


rtems_timer_service_routine RM_AcqCheck_ISR(
  rtems_id   timer_id,
  void      *unused
  ) {
  RM_acqcheck_flag=TRUE;
}

status_code RM_WS3_ProgramTimer() {
  RM_Rate_meter_check=FALSE;
  /*@LOG WS3 programming timer*/
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,PRH_VAR_RM_WS3_TIMER_FIRE_AFTER);
  OS_piStartTimer_INFN(RM_WS3_TIM,
		       PRH_VAR_RM_WS3_TIMER_FIRE_AFTER,
		       RM_WS3_ISR,
		       NULL);
}


#define RM_EXIT_IFSINT() do { \
  if (RM_CheckSINT()) \
    return CM_RC_SINT; \
} while(0)

void RM_Set_AcqExitIfError_FILEID(unsigned short fileid) {
  RM_AcqExitIfError_FILEID = fileid;
}

status_code RM_AcqExitIfError(unsigned short line,status_code s)
{
  if(s != CM_RC_SUCCESSFUL) {
    LU_INFN_LOG(LU_CRITICAL|LU_HA,LU_MASK(RM_AcqExitIfError_FILEID),RM_AcqExitIfError_FILEID,line,s);
    return s;
  }
  RM_EXIT_IFSINT();
  return CM_RC_SUCCESSFUL;
}

status_code RM_InitExitError(unsigned short line,status_code s)
{
  if(s != CM_RC_SUCCESSFUL) {
    LU_INFN_LOG(LU_CRITICAL|LU_HA,LU_MASK(RM_AcqExitIfError_FILEID),RM_AcqExitIfError_FILEID,line,s);
    return s;
  }
  RM_EXIT_IFSINT();
  return CM_RC_SUCCESSFUL;
}


status_code RM_AcqExitIfError_CallBack(unsigned short line,status_code s,status_code (*callback)() )
{
  if(s != CM_RC_SUCCESSFUL) {
    callback();
    LU_INFN_LOG(LU_CRITICAL|LU_HA,LU_MASK(RM_AcqExitIfError_FILEID),RM_AcqExitIfError_FILEID,line,s);
    return s;
  }
  RM_EXIT_IFSINT();
  return CM_RC_SUCCESSFUL;
}


#define RM_ACQ_EXIT_IFERROR(status) RM_EXIT_IFERROR(status)

#define RM_INI_EXIT_IFETO(status) do\
{\
  if(status=RM_AcqExitIfError_CallBack(__LINE__,status,RM_WriteInitializationTrailer)) \
     return(status);\
} while (0)

#define RM_CAL_EXIT_IFETO(status) do\
{\
  if(status=RM_AcqExitIfError_CallBack(__LINE__,status,RM_WriteCalibrationTrailer)) \
     return(status);\
} while (0)



status_code RM_GetRateMeterS1(DAQ_CMD_BUF *buf,int *rate_meters_s1) {
  BYTE b1;
  BYTE b2;
  if(buf==NULL || rate_meters_s1==NULL)
    return CM_RC_INTERNAL_ERR;
  b1=buf->buf[SM_PKTHEADER_LEN];
  b2=buf->buf[SM_PKTHEADER_LEN+1];
  CM_BIT_REVERSE_8(b1);
  CM_BIT_REVERSE_8(b2);
  *rate_meters_s1=b1 | ((b2 & 0xF)<<8);
  return CM_RC_SUCCESSFUL;
}

static status_code RM_DoRun(WS ws) {
  BOOL breakRun = FALSE;
  BOOL fullPIF  = FALSE;
  UINT32 pkt_count=0;
  UINT32 etoCounter=0;
  SM_ACQMODE oldmode;
  status_code status = SUCCESSFUL;
  status_code ret = SUCCESSFUL;
  rtems_event_set evout;
  unsigned int intLevel;
  /* this variable is static because is used by the RM_StopFullAcq: */
  DAQ_CMD_BUF *buf;
  BOOL ws3_check,is_ws3=(ws==WS_3);
  int rate,rm_s1_reg;
  BOOL last_event=FALSE;
  UINT16 khb_status,khb_status_check;
  UINT32 counterleftold=0,counterleft,khb_alarm;	

  RM_Set_AcqExitIfError_FILEID(__FILEID__);
  RM_Run_Is_In_Progress = TRUE;
  RM_Run_Counter++;

  RM_acqcheck_flag=TRUE;
    
  /* "run" is the external loop */

  // PM_pi_UseCalibrationPage(SM_CALEXP2);

  // SD_piSetEventTimeout(PRH_VAR_RM_ACQ_PIF_EVENT_TIMEOUT);

  /*
  OS_piInterDisable(&intLevel);
  SD_piClearInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);		
  SD_piUnMaskInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);		
  OS_piInterEnable(intLevel);
  */
  
  khb_status=0;
  ret=CM_RC_SUCCESSFUL;
  while(!breakRun) {

    OS_PROTECTED_INT(intLevel,ws3_check=is_ws3 && RM_Rate_meter_check);
    status = DAQ_SendCmd2PIFWaitDAQReply_NoSINT(SM_CALEXP1,
						DAQ_STORE_MM,&RM_128K_Buffer,ws3_check);
    
    switch(status) {
    case CM_RC_SUCCESSFUL:
      pkt_count++;
      RM_PktReady_Counter++;
      OS_PROTECTED_INT(intLevel,PRH_VAR_TRIG=0);
      if(RM_CheckSINT()) {
	breakRun=TRUE;
	ret=CM_RC_SINT;
	RM_acqcheck_flag=TRUE;
      }
      if(RM_acqcheck_flag){
	RM_acqcheck_flag=FALSE;
	if((khb_status_check=khb_status=ALM_FE_Acquisition_Check()) && !breakRun) {
#warning "modifica 28/2/2005"
	  khb_status_check &= KHB_STATUS_ALL_FE_IDAQ ;
	  if(khb_status_check == KHB_STS_ALARM_S4_ADC_AC_2) {
	    status = HK_ReadKHBAlarmRegister(&khb_alarm);
	    if(status == CM_RC_SUCCESSFUL) 
	      breakRun= 
		(((khb_alarm & KHB_ALARM_S4_ADC)) && ( (PRH_VAR_S4_OK && (PRH_VAR_S4_WORKING || PRH_VAR_S4_ATTEMPT)))) ||
		(((khb_alarm & KHB_ALARM_AC_2)) && PRH_VAR_AC_2_OK);
	    else
	      breakRun=TRUE;
	  }else
	    breakRun=TRUE;
	}
	if(!breakRun)
	  OS_piStartTimer_INFN(RM_ACQCHECK_TIM,
			       PRH_VAR_RM_ACQCHECK_PERIOD,
			       RM_AcqCheck_ISR,
			       NULL);	
      }
      if(!breakRun && ws3_check){

	RM_GetRateMeterS1(&RM_128K_Buffer,&rm_s1_reg);
	rate=rm_s1_reg - (int)(PRH_ARR_RM_RATE_METER_S1_TRH[RM_Acq_setting_mode-1]);
	if((rate > 0 && RM_Acq_setting_mode == RM_ACQ_SETTING_A) ||
	   (rate <=0 && RM_Acq_setting_mode == RM_ACQ_SETTING_B))
	  {
	    ret=CM_RC_DO_AGAINACQ;
	    WS_3_SetNextAcqMode(RM_Acq_setting_mode == RM_ACQ_SETTING_B ? RM_ACQ_SETTING_A : RM_ACQ_SETTING_B); 
	    breakRun=TRUE;
	  }
	
	if(!breakRun)
	  RM_WS3_ProgramTimer();
      }
      break;
    case CM_RC_UNCOMPLETED_CMDIF:
      khb_status=ALM_FE_Acquisition_Check();
      while(counterleftold!=(counterleft=SD_piGetCMDCounterLeft()))
	{
	  OS_piTaskSuspend(1);
	  counterleftold=counterleft;
	}
      if(counterleft)
	status=CM_RC_RUNTIMEOUT;
      else
	status=CM_RC_SUCCESSFUL;      
      breakRun=TRUE;
      break;
    default: 
      // ETO | TIMEOUT | STOREERROR | UNSATISFIED | uncompleted....  
      breakRun=TRUE;
    }
  }

  RM_Run_Is_In_Progress = FALSE;

  if(status)
      {
	/*@LOG Run stops with error */
	ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_EVENT_ACQ);
	if(status!=CM_RC_UNCOMPLETED_CMDIF)
	  ret = ALM_Eto_Acquisition();
      }
    else{
      
      DAQ_ResetPIF(DAQ_ACQ_ETO_TICS,DAQ_DEFAULT_DTO_TICS,SM_DAQSETUP,HB_PKTTYPE_PHYS_ENDRUN);
      
      //    PM_pi_SetPktType(HB_PKTTYPE_PHYS_ENDRUN);
      status = DAQ_SendCmd2PIFWaitDAQReply_NoSINT(SM_CALEXP2,
						  DAQ_STORE_MM,NULL,FALSE);
      if(status == CM_RC_UNCOMPLETED_CMDIF){
	khb_status=ALM_FE_Acquisition_Check();
	status=CM_RC_SUCCESSFUL;	 
      }
      if(status){
	ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_STOP_RUN);
	ret = ALM_Eto_Acquisition();
      }
      else{
	if(khb_status){
	  /*@LOG alarm on KHB status register after END of RUN command queue */
	  ALM_WriteLog(ALM_TRACE_ID,ALM_FE_ACQ_ERR);
	  if(( ret = ALM_FE_AlarmAction(khb_status)) == CM_RC_SUCCESSFUL)
	    ret = CM_RC_DO_AGAINACQ;
	}
      }    
    }
  
  if(status=RM_CloseRun(pkt_count))
    /*@LOG CloseRun return unsuccessful*/
    LU_INFN_LOG(LU_CRITICAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
  return (ret);
}

status_code RM_AssembleCmd(DAQ_CMD_BUF* idaqcmd,DAQ_CMD_BUF* cmdbuffer,DAQ_FE link) {
    return DAQ_Format_Fe2Daq(idaqcmd,cmdbuffer,link);
}

status_code RM_Acquisition() {
  status_code runcode;

  TI_TIME duration_run,t; // duration of the run
  WS ws;
  status_code status;


  DAQ_CMD_BUF *p_tb_trigger_selection,*pbuf;
  DAQ_FE fe;
  UINT16 i,j;
  UINT32 cal_fe;
  UINT32 acq_build_info=0;

  RM_Set_AcqExitIfError_FILEID(__FILEID__);

  DAQ_ResetPIF(DAQ_ACQ_ETO_TICS,DAQ_DEFAULT_DTO_TICS,SM_DAQSETUP,HB_PKTTYPE_PHYS_PKT);

  RM_Rate_meter_check=FALSE;
  WS_SetEffectiveWorkingSchedule(PRH_VAR_RM_TIME_MAX_RUN,&RM_Acq_setting_mode,&duration_run);
  ws=WS_Effective();
  switch(ws) {
  case WS_3:
    RM_WS3_ProgramTimer();
    // Other action TBD
    break;
  case WS_2:
    
    break;
  case WS_1:

    break;
  case WS_0:    

    break;
  default:
    /*@LOG bad working schedule. using WS0 */
    LU_INFN_LOG(LU_INTERNAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,ws);
    ws=WS_0;
    break;
  }
  


  if(PRH_VAR_TRIG_II) {
    status=DAQ_StoreCmdQueue2PIF(SM_CALEXP3,&TRIG_II_INIT);
    RM_ACQ_EXIT_IFERROR(status);
    status=DAQ_SendCmdQueue2CMDIF(SM_CALEXP3);
    RM_ACQ_EXIT_IFERROR(status);
    
  }
  

  DAQ_BUFFER_INIT(RM_buf_cmd);

  switch(RM_Acq_setting_mode) {
  case RM_ACQ_SETTING_A:
    status=CH_GetBuf(CH_TB_SET_TRIGGER_CONF_01+PRH_VAR_TRIGGER_MODE_A-1,&p_tb_trigger_selection);
    break;
  case RM_ACQ_SETTING_B:
    status=CH_GetBuf(CH_TB_SET_TRIGGER_CONF_01+PRH_VAR_TRIGGER_MODE_B-1,&p_tb_trigger_selection);
    break;
  default:
    p_tb_trigger_selection = NULL;
    status=CM_RC_SUCCESSFUL;
    /*@LOG bad ACQSettintMode: do nothing*/
    LU_INFN_LOG(LU_INTERNAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,ws);
    break;
  }
  
  
  if(p_tb_trigger_selection != NULL) {
    status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,p_tb_trigger_selection,
			     DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
    RM_ACQ_EXIT_IFERROR(status);
  }

  CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
  status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
  RM_ACQ_EXIT_IFERROR(status);			   

  status=CH_GetBuf(CH_TB_SET_BUSY_CONTROL_0+PRH_VAR_TRIGGER_BUSY_CONTROL,
		   &p_tb_trigger_selection);
  RM_ACQ_EXIT_IFERROR(status);

  if(p_tb_trigger_selection) {
    status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,
			     p_tb_trigger_selection,
			     DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));

  }
  RM_ACQ_EXIT_IFERROR(status);

  CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
  status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
  RM_ACQ_EXIT_IFERROR(status);

  if(PRH_VAR_TRK_OK) {    
    for(i=1;i<=2;i++){
      
	TRK_ALARM_MASK[i-1]|=0xc0;
	if(PRH_VAR_TB_LINK == 1 /* HOT */) 
	  TRK_ALARM_MASK[i-1] &= 0xBF;
	else
	  TRK_ALARM_MASK[i-1] &= 0x7F;
	CH_GetBuf(TRK_MASK_BASE_ID-TRK_MASK_BASE_OFFSET+TRK_ALARM_MASK[i-1],&pbuf );
	fe = i==1 ? DAQ_FE_TRK_1 : DAQ_FE_TRK_2;
	status=RM_AssembleCmd(&RM_buf_cmd,pbuf,fe);
	RM_ACQ_EXIT_IFERROR(status);
      
	CH_GetBuf(CH_TRK_GENERAL_RESET,&pbuf);
	status=RM_AssembleCmd(&RM_buf_cmd,pbuf,fe);
	RM_ACQ_EXIT_IFERROR(status);


	for(j=0;j<=5;j++)
	if(PRH_TAB_TRK_DSP_OK[i-1][j]) {

	  status=CH_GetBuf(CH_TRK_START_0+j,&pbuf);
	  //fe = i==1 ? DAQ_FE_TRK_1 : DAQ_FE_TRK_2;
	  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,fe);
	  RM_ACQ_EXIT_IFERROR(status);

	  TRK_Get_TRK_NUMBER_DSP(i,j,&pbuf);
	  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,fe);
	  RM_ACQ_EXIT_IFERROR(status);

	  if(RM_Acq_After_Calib) {
	    TRK_Get_TRK_OPMODE_SPEC(j,&pbuf);
	  }else{
	    TRK_Get_TRK_OPMODE_COMP(j,&pbuf);
	  }

	  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,fe);
	  RM_ACQ_EXIT_IFERROR(status);
	}
    }
  }


  if(RM_Acq_After_Calib) {
    CH_GetBuf(CH_CAL_FULL,&pbuf);
  }else{
    CH_GetBuf(CH_CAL_COMPRESS,&pbuf);
  }

  if(PRH_VAR_CAL_OK) {
    cal_fe = 1;
    for(i=1;i<=4;i++) {
      if(cal_fe & CAL_DSP_MASK) {	
	status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_CAL(i));
	RM_ACQ_EXIT_IFERROR(status);
      }
      cal_fe <<= 1;
    }
  }
  


  
  // other detectors here ...

  status=CH_GetBuf(CH_TB_START_ACQ,&pbuf);
  status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);

#if 0
  if(PRH_VAR_RM_IDAQONLYACQ) {
    /* write data into idaq , overwrite cmd queue */
    static UINT32 i;
    DAQ_BUFFER_INIT(RM_buf_data); 
    DAQ_BUFFER_INIT(RM_128K_Buffer); 
    RM_buf_data.eto=0; 
    RM_buf_data.ato=0;
    RM_128K_Buffer.eto=0;
    RM_128K_Buffer.ato=0;
    DAQ_BUFFER_INIT(RM_buf_cmd);
    status |= DAQ_Format_Ram_SetAddress(&RM_buf_data,0);
    status |= DAQ_Format_Cmd2Ram(&RM_buf_cmd,&RM_buf_data);

    for(i=0;i<PRH_VAR_RM_IDAQONLYACQ_BLOCKSIZE;i++,RM_128K_Buffer.buf[i]=i);
    RM_128K_Buffer.len=PRH_VAR_RM_IDAQONLYACQ_BLOCKSIZE;

    status |= DAQ_Format_Ram_WriteData(&RM_buf_data,&RM_128K_Buffer);
    status |= DAQ_Format_Cmd2Ram(&RM_buf_cmd,&RM_buf_data);
    status |= DAQ_Format_Ram_EndBlock(&RM_buf_data);
    status |= DAQ_Format_Cmd2Ram(&RM_buf_cmd,&RM_buf_data);
    if(status)
      LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
  }
#endif

  status=DAQ_StoreCmdQueue2PIF(SM_CALEXP0,&RM_buf_cmd);
  RM_ACQ_EXIT_IFERROR(status);

  if(
     (PRH_VAR_TRK_OK == 1 || 
      (CAL_DSP_MASK != 0 /* CAL in raw mode */ && PRH_VAR_CAL_OK == 1)
      ) 
     ) {
    status=DAQ_SendCmd2PIFWaitDAQReply(SM_CALEXP0,DAQ_NO_STORE_MM,&RM_buf_data,RM_storeram);
  }else{
    /* answer not expected from DAQ/IF */
    status=DAQ_SendCmdQueue2CMDIF(SM_CALEXP0);
  }

  if (status)
    {
      /*@LOG EtoStartRun in Acquistion */
      ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_START_RUN);
      status = ALM_Eto_Reset();
      RM_ACQ_EXIT_IFERROR(status);
    }

  // START OF ACQUISITION CMD QUEUE
  
  DAQ_BUFFER_INIT(RM_buf_cmd);

  status=DAQ_Format_ReleaseBusy(&RM_buf_cmd);

  
  status=CH_GetBuf(CH_TB_READ_PMT_PLANE,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
    
  status=CH_GetBuf(CH_TB_READ_EVENT_COUNT,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
    
  status=CH_GetBuf(CH_TB_READ_TRIGGER_RATE,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
    
  status=CH_GetBuf(CH_TB_READ_D_L_TIME,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
    
  status=CH_GetBuf(CH_TB_READ_S4_CAL_COUNT,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
    
  status=CH_GetBuf(CH_TB_READ_PMT_COUNT1,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
    
  status=CH_GetBuf(CH_TB_READ_PMT_COUNT2,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
    
  status=CH_GetBuf(CH_TB_READ_PATTERN_BUSY,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
    
  status=CH_GetBuf(CH_TB_READ_PATTERN_TRIGGER,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
    
  status=CH_GetBuf(CH_TB_READ_TRIGGER_CONF,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
  
  

  if (PRH_VAR_TOF_OK){

    if( PRH_ARR_TOF_PLAN[0] ) {
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_1,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_2,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_RESET_1,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_TOF_PLAN_1;
    }

    if( PRH_ARR_TOF_PLAN[1] ) {
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_3,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_4,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_RESET_2,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_TOF_PLAN_2;
    }

    if(PRH_ARR_TOF_PLAN[2]) {
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_5,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_6,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_RESET_3,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_TOF_PLAN_3;
    }
    
    if(PRH_ARR_TOF_PLAN[3]) {
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_7,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_8,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_RESET_4,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_TOF_PLAN_4;
    }

    if(PRH_ARR_TOF_PLAN[4]) {
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_9,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_10,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_RESET_5,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_TOF_PLAN_5;
    }
    
    if(PRH_ARR_TOF_PLAN[5]) {
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_11,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_TDC_ACQ_12,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_TOF_FE_RESET_6,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
      RM_ACQ_EXIT_IFERROR(status);
      CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
      status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_TOF_PLAN_6;
    }

    CH_GetBuf(CH_TOF_FE_CLEAR,&pbuf);
    status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_TOF);
    RM_ACQ_EXIT_IFERROR(status);
  }

  if(PRH_VAR_AC_1_OK && (PRH_VAR_AC_1_ON || PRH_VAR_AC_1_CHECK)) {
      CH_GetBuf(CH_AC_READ_EVENT,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_AC_1);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_AC_1;
  }


  if(PRH_VAR_AC_2_OK && (PRH_VAR_AC_2_ON || PRH_VAR_AC_2_CHECK)) {
      CH_GetBuf(CH_AC_READ_EVENT,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_AC_2);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_AC_2;
  }
  
  if(PRH_VAR_CAL_OK) {
    cal_fe = 1;
#warning is this name correct? the flow chart only says CAL_READ_EVENT
    status=CH_GetBuf(CH_CAL_READ_EVENT_DATA,&pbuf);
    for(i=1;i<=4;i++) {
      if(cal_fe & (CAL_FE_MASK | PRH_VAR_CAL_CHECK_FE)) {
	status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_CAL(i));
	RM_ACQ_EXIT_IFERROR(status);
	acq_build_info |= 1<<(RM_ACQBI_CAL_BASE+i-1);
      }
      cal_fe <<= 1;
    }
  }
  
  if(PRH_VAR_TRK_OK) {
    
    if(RM_Acq_After_Calib) 
      {
	CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
	for(i=0;i<PRH_VAR_RM_NO_DUMMY_CMD_BEFORE_SPECIAL_TRK_ACQ;i++) {
	  status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
	  RM_ACQ_EXIT_IFERROR(status);
	}
      }
    

    for(i=1;i<=2;i++)
      for(j=0;j<=5;j++)
	if(PRH_TAB_TRK_DSP_OK[i-1][j]) {
	  status=CH_GetBuf(CH_TRK_EVENT_ACQ_0+j,&pbuf);
	  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRK(i));
	  RM_ACQ_EXIT_IFERROR(status);
	  acq_build_info |= 1<<(RM_ACQBI_TRK_BASE+(i-1)*6+j);
	}    
  }

  if (PRH_VAR_S4_OK && (PRH_VAR_S4_WORKING || PRH_VAR_S4_ATTEMPT))
    {
      status=CH_GetBuf(CH_S4_ACQUISITION,&pbuf);
      status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_FE_S4);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_S4;
    }

  if( PRH_VAR_ND_OK && (PRH_VAR_ND_ATTEMPT || RM_use_nd) ) {    
    // status=CH_GetBuf(CH_ND_READ_ACQ,&pbuf);
    for(i=0;i<PRH_VAR_ND_CMDS;i++){
      status=RM_AssembleCmd(&RM_buf_cmd,&nd_acq_buf,DAQ_FE_ND);
      RM_ACQ_EXIT_IFERROR(status);
      acq_build_info |= 1<<RM_ACQBI_ND;
    }
  }

  RM_ACQ_EXIT_IFERROR(status);

  RM_Acq_Cmd_Queue_len=RM_buf_cmd.len;
  
  if(PRH_VAR_TRIG_II) {
    status=DAQ_StoreCmdQueue2PIF(SM_CALEXP1,&TRIG_II_ACQ);
  }else{
    status=DAQ_StoreCmdQueue2PIF(SM_CALEXP1,&RM_buf_cmd);
  }
  RM_ACQ_EXIT_IFERROR(status);

  // START OF "END OF RUN" CMD QUEUE

  DAQ_BUFFER_INIT(RM_buf_cmd);

  status=CH_GetBuf(CH_TB_STOP_ACQ,&pbuf);
  status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);

  CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
  status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
  RM_ACQ_EXIT_IFERROR(status);

  if(PRH_VAR_CAL_OK) {
    cal_fe = 1;
    for(i=1;i<=4;i++) {
      if(cal_fe & (CAL_FE_MASK | PRH_VAR_CAL_CHECK_FE)) {
	CH_GetBuf(CH_CAL_READ_HK,&pbuf);
	status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_CAL(i));
	RM_ACQ_EXIT_IFERROR(status);

	for(j=0; j < 7; j++)
	  {
	    status=CH_GetBuf(CAL_CAL_READ_FPGA_REG_BASE_ID+j,&pbuf);
	    RM_ACQ_EXIT_IFERROR(status);
	    status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_CAL(i));
	    RM_ACQ_EXIT_IFERROR(status);
	  }
      }
      cal_fe <<= 1;
    }
  }


  RM_ACQ_EXIT_IFERROR(status);

  CH_GetBuf(CH_TB_READ_ALARM_MASK,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);

  CH_GetBuf(CH_TB_READ_PMT_MASK,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);

  CH_GetBuf(CH_TB_READ_S4_CAL_MASK,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);

  CH_GetBuf(CH_TB_READ_BUSY_MASK,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
  
  CH_GetBuf(CH_TB_READ_TRIGGER_CONF,&pbuf);
  status=RM_AssembleCmd(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);
  
  CH_GetBuf(CH_TB_GIVE_ME_TRIGGER,&pbuf);
  status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_SELECT_TRIG(PRH_VAR_TB_LINK));
  RM_ACQ_EXIT_IFERROR(status);

  CH_GetBuf(CH_DUMMY_COMMAND,&pbuf);
  status=DAQ_Format_Cmd2Fe(&RM_buf_cmd,pbuf,DAQ_FE_SPARE);
  RM_ACQ_EXIT_IFERROR(status);
  
  status=DAQ_StoreCmdQueue2PIF(SM_CALEXP2,&RM_buf_cmd);
  RM_ACQ_EXIT_IFERROR(status);

  status=RM_WriteRunHeader(acq_build_info);
  RM_ACQ_EXIT_IFERROR(status);

  //pippo1();
  if(RM_Acq_After_Calib) {
    RM_Acq_After_Calib=FALSE;
    RM_run_real_duration_ms=PRH_VAR_RM_TIME_SPECIAL_RUN;
  }else{
    RM_run_real_duration_ms=duration_run;
    if(PRH_VAR_EXP64_MODE)
      DAQ_ResetPIF(DAQ_ACQ_ETO_TICS,DAQ_DEFAULT_DTO_TICS,SM_EXP64,HB_PKTTYPE_PHYS_PKT);
  }
  //pippo2();
  TI_piGetTimeInfo_s(&t);
  RM_end_of_run_obt_s = t + RM_run_real_duration_ms/1000;
  OS_piStartTimer_INFN(STOPACQ_TIM,
		       RM_run_real_duration_ms,
		       RM_StopAcq_ISR,
		       NULL);
  //pippo3();
  RM_ACQ_EXIT_IFERROR(status);
  runcode=RM_DoRun(ws);

  return runcode;
}


BOOL RM_RunIsInProgress() {
  return RM_Run_Is_In_Progress;
}



/* this function enable the "RunAfterAscendingNode" flag, that means
   is the first run after the ascending node.
   this function should be called after an ascending node
*/
status_code RM_EnableRunAfterAscendingNode() {
  RM_Is_Run_After_Ascending_Node  = TRUE;
}


UINT32 RM_GetCalibrationCounter() {
  return RM_Calibration_Counter;
}

void RM_LogStatus() {
  static UINT32 last_RM_PktReady_Counter=0;
  static TI_TIME ms1=0;
  TI_TIME ms2,diff,end_of_run_left_s,obt_s;
  UINT32 rate;
  WS ws;
  UINT32 npkt = RM_PktReady_Counter-last_RM_PktReady_Counter;
  TI_piGetTimeInfo_ms(&ms2);
  TI_piGetTimeInfo_s(&obt_s);
  diff=ms2-ms1;
  rate=  (npkt*1000*100) / diff;
  if(RM_end_of_run_obt_s<obt_s)
    end_of_run_left_s=0;
  else
    end_of_run_left_s=RM_end_of_run_obt_s-obt_s;
  /*@LOG Run Manager Status */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_TaskStatus);
  /*@LOG Run is in progress flag */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_Run_Is_In_Progress);
  /*@LOG Run counter */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_Run_Counter);
  ws=WS_Favourite();
  /*@LOG Favourite WS */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,ws);
  ws=WS_Effective();
  /*@LOG Effective WS */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,ws);
  /*@LOG Acq setting */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_Acq_setting_mode);
  /*@LOG Real duration of the run (ms) */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_run_real_duration_ms);
  /*@LOG estimated OBT of the End of run (s) */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_end_of_run_obt_s);
  /*@LOG time left to the end of run (s) */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,end_of_run_left_s);
  /*@LOG ETO counter */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_ETO_Counter);
  /*@LOG Timeout counter */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_TIMEOUT_Counter);
  /*@LOG SINT counter */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_SINT_Counter);
  /*@LOG Is run after ascending node? (flag) */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_Is_Run_After_Ascending_Node);
  /*@LOG Physics Packets Counter since boot */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_PktReady_Counter);
  /*@LOG Physics Packet Counter in the previus LogStatus */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,last_RM_PktReady_Counter);
  /*@LOG Number of Physics Packet since previous LogStatus */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,npkt);
  /*@LOG Millisecons since previous LogStatus */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,diff);
  /*@LOG Rate since previous LogStatus - Hz * 100 */
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,rate);

  last_RM_PktReady_Counter=RM_PktReady_Counter;
  ms1=ms2;
}

status_code RM_CloseRun(UINT32 pkt_count) {
  status_code status=CM_RC_SUCCESSFUL;
  status=RM_WriteRunTrailer(pkt_count);
  return status;
}


#define DUMMY32 0xCAFECAFE

status_code RM_WriteDownloadHeader(PRH_VAR_TYPE c) {
  BYTE i;
  DAQ_BUFFER_EMPTY(RM_buf_misc);
  for(i=0;i<HB_BUF_RAW_SIZE;i++)
    DAQ_WRITE_BE_UINT8(RM_buf_misc,c);
  HB_StoreRaw(&RM_buf_misc);
  return HB_WriteToPIF(HB_RAW);
}

status_code RM_WriteInitializationHeader() {
  DAQ_BUFFER_EMPTY(RM_buf_misc);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,DUMMY32);
  HB_StoreMisc(HB_PKTTYPE_INITHEADER,&RM_buf_misc);
  return RM_WriteHBInfos(FALSE);
}

status_code RM_WriteInitializationTrailer() {
  DAQ_BUFFER_EMPTY(RM_buf_misc);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,DUMMY32);
  HB_StoreMisc(HB_PKTTYPE_INITTRAILER,&RM_buf_misc);
  return RM_WriteHBInfos(FALSE);
}


status_code RM_WriteCalibrationHeader() {
  DAQ_BUFFER_EMPTY(RM_buf_misc);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,DUMMY32);
  HB_StoreMisc(HB_PKTTYPE_CALIBHEADER,&RM_buf_misc);
  return RM_WriteHBInfos(FALSE);
}

status_code RM_WriteCalibrationTrailer() {
  DAQ_BUFFER_EMPTY(RM_buf_misc);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,DUMMY32);
  HB_StoreMisc(HB_PKTTYPE_CALIBTRAILER,&RM_buf_misc);
  return RM_WriteHBInfos(FALSE);
}

status_code RM_WriteRunTrailer(UINT32 pkt_count) {
  status_code s;
  TI_TIME obt,ts;
  TI_piGetTimeSyncInfo_s(&obt,&ts);
  DAQ_BUFFER_EMPTY(RM_buf_misc);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,pkt_count);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,RM_PktReady_Counter);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,obt);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,ts);
  HB_StoreMisc(HB_PKTTYPE_RUNTRAILER,&RM_buf_misc);
  return RM_WriteHBInfos(FALSE);
}

status_code RM_WriteRunHeader(UINT32 acq_build_info) {
  status_code s;
  TI_TIME obt,ts;
  UINT32 trk_calib_used;
  UINT16 acq_var_info=0;
  UINT32 compilestamp=LU_GetCompilationTimeStamp();
  BYTE ws;
  DAQ_BUFFER_EMPTY(RM_buf_misc);
  TRK_Get_CalibUsed(&trk_calib_used);
  // TI_piGetTimeInfo_ms(&obt);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,compilestamp);
  DAQ_WRITE_BE_UINT8(RM_buf_misc,RM_Acq_setting_mode);
  TI_piGetTimeSyncInfo_s(&obt,&ts);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,obt);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,ts);
  ws=WS_Favourite();
  DAQ_WRITE_BE_UINT8(RM_buf_misc,ws);
  ws=WS_Effective();
  DAQ_WRITE_BE_UINT8(RM_buf_misc,ws);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,PRH_VAR_TRIGGER_MODE_A);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,PRH_VAR_TRIGGER_MODE_B);
  DAQ_WRITE_BE_UINT8(RM_buf_misc,RM_Acq_After_Calib);
  DAQ_WRITE_BE_UINT32(RM_buf_misc,trk_calib_used);  


  acq_var_info = 
    (PRH_VAR_TOF_OK     ? 1<<0  : 0 ) |
    (PRH_VAR_AC_1_OK    ? 1<<1  : 0 ) |
    (PRH_VAR_AC_2_OK    ? 1<<2  : 0 ) |
    (PRH_VAR_CAL_OK     ? 1<<3  : 0 ) |
    (PRH_VAR_TRK_OK     ? 1<<4  : 0 ) |
    (PRH_VAR_S4_OK      ? 1<<5  : 0 ) |
    (PRH_VAR_S4_WORKING ? 1<<6  : 0 ) |
    (PRH_VAR_S4_ATTEMPT ? 1<<7  : 0 ) |
    (PRH_VAR_ND_OK      ? 1<<8  : 0 ) |
    (RM_use_nd          ? 1<<9  : 0 ) |
    (PRH_VAR_ND_ATTEMPT ? 1<<10 : 0 ) |
    (PRH_VAR_POWER_KHB  ? 1<<11 : 0 ) |
    (PRH_VAR_TB_LINK-1  ? 1<<12 : 0 ) |
    ((PRH_VAR_POWER_MODE & 0x3) <<13 )
;

  DAQ_WRITE_BE_UINT32(RM_buf_misc,acq_build_info);
  DAQ_WRITE_BE_UINT16(RM_buf_misc,acq_var_info);
  DAQ_WRITE_BE_UINT8(RM_buf_misc,CAL_DSP_MASK);
  HB_StoreMisc(HB_PKTTYPE_RUNHEADER,&RM_buf_misc);
  return RM_WriteHBInfos(FALSE);
}

/* write infos of HB into the PIF.
   This function doesnt change the ACQ mode of the PIF, assuming that is already correctly set */
status_code  RM_WriteHBInfos(BOOL dump_parameters) {
  status_code s,s2;
  BOOL mm;
  BYTE id;

#define all HB_SKETCHBOARD
  
  /* compilation time control: 
     check if the SKETCHSIZE cannot contain all the parameter dump infos: */

#if ((PRH_TOTAL_SIZE + PRH_VAR_MAX + PRH_ARR_MAX + PRH_TAB_MAX) > HB_SKETCHSIZE)
#warning maybe the Parameter DUMP is too big for SKETCHSIZE ? 
#endif
  
  s=HB_StoreSketchboard();
  if(dump_parameters) {

    s=HB_StoreVarDump();
    if(s != SUCCESSFUL) {
      /*@LOG StoreVarDump error*/
      LU_INFN_LOG(LU_WARNING|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
      s2=HB_WriteToPIF(all);
      if(s2)
	/*@LOG Write error for Var Dump*/
	LU_INFN_LOG(LU_WARNING|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,s2);
    }

    s=HB_StoreArrDump();
    if( s != SUCCESSFUL) {
      /*@LOG StoreArrDump error*/
      LU_INFN_LOG(LU_WARNING|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
      s2=HB_WriteToPIF(all);
      if(s2)
	/*@LOG Write error for Arr Dump*/
	LU_INFN_LOG(LU_WARNING|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,s2);
    }
    
    s=HB_StoreTabDump();
    if( s != SUCCESSFUL) {
      /*@LOG StoreTabDump error*/
      LU_INFN_LOG(LU_WARNING|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
      s2=HB_WriteToPIF(all);
      if(s2)
	/*@LOG Write error for Tab Dump*/
	LU_INFN_LOG(LU_WARNING|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,s2);
    }

    

  }
  
  s2=HB_WriteToPIF(all);
  if(s2)
    /*@LOG Write error for HB_Write2PIF */
    LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,s2 );
  
  if(dump_parameters)
    { 
      /* Variabile  Dump not stored in MM */
      if(PRH_VAR_RM_DUMP_ALL_PARAMS & HB_DUMP_ALL_PARAMS_VAR) 
	for(id=0;id<PRH_VAR_MAX;id++)  
	  { 
	    if(PRH_int_var_is_in_mm(id,&mm) == CM_RC_SUCCESSFUL && !mm)  
	      { 
		s=HB_StoreVar(id); 
		if(s==CM_RC_SUCCESSFUL) { 
		  s2=HB_WriteToPIF(all); 
		  if(s2 != CM_RC_SUCCESSFUL) {
		    /*@LOG HB_WriteToPIF Error for variables not stored in MM */
		    LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,s2);
		  }
		}else{ 
		  /*@LOG HB_StoreVar Error for variables not stored in MM - id */
		  LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,id);
		  /*@LOG HB_StoreVar Error for variables not stored in MM - status */
		  LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
		}
	      }
	  }

      /* Arrayes  Dump not stored in MM */
      if(PRH_VAR_RM_DUMP_ALL_PARAMS & HB_DUMP_ALL_PARAMS_ARR) 
	for(id=0;id<PRH_ARR_MAX;id++)
	  { 
	    if(PRH_int_arr_is_in_mm(id,&mm) == CM_RC_SUCCESSFUL && !mm)  
	      { 
		s=HB_StoreArr(id); 
		if(s==CM_RC_SUCCESSFUL) { 
		  s2=HB_WriteToPIF(all); 
		  if(s2 != CM_RC_SUCCESSFUL) {
		    /*@LOG HB_WriteToPIF Error for arrays not stored in MM */
		    LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,s2);
		  }
		}else{ 
		  /*@LOG HB_StoreArr Error for arrays not stored in MM - id */
		  LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,id);
		  /*@LOG HB_StoreArr Error for arrays not stored in MM - status */
		  LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
		}
	      }
	  }

      /* Tables  Dump not stored in MM */
      if(PRH_VAR_RM_DUMP_ALL_PARAMS & HB_DUMP_ALL_PARAMS_TAB) 
	for(id=0;id<PRH_TAB_MAX;id++)  
	  { 
	    if(PRH_int_tab_is_in_mm(id,&mm) == CM_RC_SUCCESSFUL && !mm)  
	      { 
		s=HB_StoreVar(id); 
		if(s==CM_RC_SUCCESSFUL) {
		  s2=HB_WriteToPIF(all); 
		  if(s2 != CM_RC_SUCCESSFUL) {
		    /*@LOG HB_WriteToPIF Error for tabs not stored in MM */
		    LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,s2);
		  }
		}else{ 
		  /*@LOG HB_StoreArr Error for tables not stored in MM - id */
		  LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,id);
		  /*@LOG HB_StoreArr Error for tables not stored in MM - status */
		  LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
		}
	      }
	  }
      
      
      s=CM_RC_SUCCESSFUL;
            
    }
  else
    s=s2;
  
  return s;
}

#undef all

status_code RM_ND_Initialization() {
  status_code status;
  UINT16 sw;
  DAQ_BUFFER_INIT(RM_buf_cmd);
  RM_Set_AcqExitIfError_FILEID(__FILEID__);
  status = DAQ_ResetPIF(DAQ_DEFAULT_ETO_TICS,DAQ_MAX_DTO_TICS,SM_DAQSETUP,HB_PKTTYPE_ND_INIT);
  RM_ACQ_EXIT_IFERROR(status);
  
  RM_AssembleCmd(&RM_buf_cmd,&nd_acq_buf,DAQ_FE_ND);
  status = DAQ_StoreCmdQueue2PIF(SM_CALEXP2,&RM_buf_cmd);	    
  RM_ACQ_EXIT_IFERROR(status);
  status = DAQ_SendCmd2PIFWaitDAQReply(SM_CALEXP2,DAQ_STORE_MM,&RM_buf_data,DAQ_NO_STORE_RAM);
  if(status != CM_RC_SUCCESSFUL) {
    RM_use_nd=FALSE;
    // clear the idaq alarm:
    status=DAQ_ReadStatusWord(&sw);
    /*@LOG ND_Initialization read error / read IDAQ status word - idaq_st_word << 16 | status */
    LU_INFN_LOG(LU_WARNING,LU_MASK(__FILEID__),__FILEID__,__LINE__,sw << 16 | status);
    RM_ACQ_EXIT_IFERROR(status); 
    status=CM_RC_SUCCESSFUL;
  }
  return status;
}

status_code RM_BC2PM(RM_OPCODES opcode,status_code code) {
  status_code status;
  MsgTsk      SndMsg;
  unsigned char *pc;
  /* goes to idle because the RM is still not waiting in the queue, but wakes up the PamManager */
  SndMsg.Code = PM_INFN_RUNMANAGER_MSG;

  pc = SndMsg.Info;
  *(RM_OPCODES*)pc = opcode;        pc += sizeof(RM_OPCODES);
  *(status_code*)pc = code;  pc += sizeof(status_code);

  SndMsg.LlInfo = sizeof(RM_OPCODES) + sizeof(status_code);
  /*@LOG Send Code Back to Pam Manager - code */ 
  LU_INFN_LOG(LU_DEBUG_TRACE|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,code);
  status=PM_SndMsgPamManager_INFN(&SndMsg);
  return status;
}

RM_OPCODES RM_WhatIsDoing() {
  return RM_TaskStatus;
}

static status_code RM_InitIDAQ_TrigII() {
  // TBD 
  return CM_RC_SUCCESSFUL;
}


status_code RM_Initialization(){
  status_code status = CM_RC_SUCCESSFUL,hs,ts;
  RM_Initialization_Counter++;

  RM_Init_Before_Calib=FALSE;
  RM_Set_AcqExitIfError_FILEID(__FILEID__);
  status = HK_KHB_InitBoard();
  
  if (status)
    {
      /*@LOG Initialization: Error Initializing do power off-on - status */
      LU_INFN_LOG(LU_CRITICAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
      return(CM_RC_DO_POWER_OFF_ON);
    } 
  
  DAQ_ResetPIF(DAQ_DEFAULT_ETO_TICS,DAQ_DEFAULT_DTO_TICS,SM_DAQSETUP,HB_PKTTYPE_RSV_RUN_MANAGER_INIT);
  
  hs=RM_WriteInitializationHeader();
#if 0
#ifdef DEBUG
  {
    extern unsigned int IM_GetCalled(int);
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,IM_GetCalled(11 /* IM_INT4 */ ));  
  }
#endif
#endif


  if(PRH_VAR_TRIG_II) {
    status=RM_InitIDAQ_TrigII();
    
    if (status)
      {
        /*@LOG IDAQ TRIG II mode Initialization failed */
        ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_IDAQ_INIT);
        status = ALM_Eto_Reset();
      }
    else
      status = ALM_FE_Alarm_Check(KHB_STS_ALARM_IDAQ,ALM_FE_IDAQ_INIT);
    
    RM_INI_EXIT_IFETO(status);
  }



  /*@LOG TRG Initialization ...*/
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  
  status=TRG_Initialization();
  
  if (status)
    {
      /*@LOG TRG Initialization failed */
      ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_TRG_INIT);
      status = ALM_Eto_Reset();
      RM_INI_EXIT_IFETO(status);
    }
  else
    status = ALM_FE_Alarm_Check(KHB_STS_ALARM_TRG,ALM_FE_TRG_INIT);

  if(PRH_VAR_AC_1_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG AC 1 Initialization ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  
      
      status=AC_1_Initialization();
      
      if (status)
	{
	  /*@LOG AC 1 Initialization failed */
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_AC_1_INIT);
	  status = ALM_Eto_Reset();
	  RM_INI_EXIT_IFETO(status);
	}
      else
	status = ALM_FE_Alarm_Check(KHB_STS_ALARM_AC_1,ALM_FE_AC_1_INIT);
    }


  if(PRH_VAR_AC_2_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG AC 2 Initialization ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  
      status=AC_2_Initialization();
      
      if (status)
	{
	  /*@LOG AC_2 Initialization failed */
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_AC_2_INIT);
	  status = ALM_Eto_Reset();
	  RM_INI_EXIT_IFETO(status);
	}
      else
	status = ALM_FE_Alarm_Check_general(KHB_STS_ALARM_S4_ADC_AC_2,
					    ALM_FE_AC_2_INIT,
					    KHB_ALARM_AC_2
					    );
    }

  
  if(PRH_VAR_CAL_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG CAL Initialization ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=CAL_Initialization();
      if (status)
	{
	  /*@LOG CAL Initialization failed */
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_CAL_INIT);
	  status = ALM_Eto_Reset();
	  RM_INI_EXIT_IFETO(status);
	}
      else
	status = ALM_FE_Alarm_Check(KHB_STS_ALARM_CALO,ALM_FE_CAL_INIT);
    }

  if(PRH_VAR_TRK_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG TRK Initialization ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=TRK_Initialization();
      
      if (status)
	{
	  /*@LOG TRK Initialization failed */
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_TRK_INIT);
	  status = ALM_Eto_Reset();
	  RM_INI_EXIT_IFETO(status);
	}
      else
	status = ALM_FE_Alarm_Check(KHB_STS_ALARM_TRK,ALM_FE_TRK_INIT);
    }


  if(PRH_VAR_TOF_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG TOF Initialization ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=TOF_Initialization();
      
      if (status)
	{
	  /*@LOG TOF Initialization failed */
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_TOF_INIT);
	  status = ALM_Eto_Reset();
	  RM_INI_EXIT_IFETO(status);
	}
      else
	status = ALM_FE_Alarm_Check(KHB_STS_ALARM_TOF,ALM_FE_TOF_INIT);
    }

  RM_use_nd=TRUE;

  if( PRH_VAR_ND_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG ND Initialization ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=RM_ND_Initialization();

      if (status)
	{
	  /*@LOG ND Initialization failed */
	  ALM_WriteLog(ALM_TRACE_ID,ALM_FE_ND_INIT);
	  status = ALM_Eto_Reset();
	  RM_INI_EXIT_IFETO(status);
	}
    }

  if( PRH_VAR_S4_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG S4 Initialization ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=S4_Initialization();
      
      if (status)
	{
	  if (status != CM_RC_DO_POWER_OFF_ON)
	    {
	      /*@LOG S4 Initialization failed */
	      ALM_WriteLog(ALM_TRACE_ID,ALM_FE_S4_INIT);
	      status = ALM_Eto_Reset();
	      RM_INI_EXIT_IFETO(status);
	    }
	}
      else
	status = ALM_FE_Alarm_Check_general(KHB_STS_ALARM_S4_ADC_AC_2,
					    ALM_FE_S4_INIT,
					    KHB_ALARM_S4_ADC);
    }
  
  ts=RM_WriteInitializationTrailer();

  if (ts)
    /*@LOG Write initialization header error - status*/
    LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,ts);
									  
  return status;
}

status_code  RM_Calibration(){  
  status_code status=CM_RC_SUCCESSFUL,cts;
  RM_Calibration_Counter++;
  RM_Init_Before_Calib = TRUE;

  RM_Set_AcqExitIfError_FILEID(__FILEID__);

  DAQ_ResetPIF(DAQ_DEFAULT_ETO_TICS,DAQ_DEFAULT_DTO_TICS,SM_DAQSETUP,HB_PKTTYPE_RSV_RUN_MANAGER_CALIB);

  RM_WriteCalibrationHeader();
  


  if(PRH_VAR_TRIG_II) {
    status=RM_InitIDAQ_TrigII();
    
    if (status)
      {
        /*@LOG IDAQ TRIG II mode Initialization failed during calibration */
        ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_IDAQ_INIT_CALIB);
        status = ALM_Eto_Reset();
      }
    else
      status = ALM_FE_Alarm_Check(KHB_STS_ALARM_IDAQ,ALM_FE_IDAQ_INIT_CALIB);
    
    RM_INI_EXIT_IFETO(status);
  }
  
  
  if(PRH_VAR_AC_1_OK || PRH_VAR_AC_2_OK) {
    if(PRH_VAR_AC_1_OK) {
      /*@LOG AC 1 Initialization ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=AC_1_Initialization();
      if (status)
	{
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_AC_1_INIT_CALIB); /* AC_1 Initialization failed insiede calibration */
	  status = ALM_Eto_Reset();
	  RM_CAL_EXIT_IFETO(status);
	}
    }
    if(PRH_VAR_AC_2_OK) {
      /*@LOG AC 2 Initialization ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=AC_2_Initialization();
      if (status)
	{
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_AC_2_INIT_CALIB); /* AC_2 Initialization failed inside calibration */
	  status = ALM_Eto_Reset();
	  RM_CAL_EXIT_IFETO(status);
	}
    }
    /*@LOG AC Calibration 1 ...*/
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

    status=AC_Calibration1();
    if (status)
      {
	ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_AC_CALIB1); /* AC_Calibration1 failed inside calibration */
	status = ALM_Eto_Reset();
	RM_CAL_EXIT_IFETO(status);
      }
    else
      status = ALM_FE_Alarm_Check_general(KHB_STS_ALARM_AC_1 | KHB_STS_ALARM_S4_ADC_AC_2 | KHB_STS_ALARM_IDAQ,
					  ALM_FE_AC_CALIB,
					  KHB_ALARM_AC_2);
  }

  if(PRH_VAR_CAL_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG CAL Initialization  ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  
      
      status=CAL_Initialization();
      if (status)
	{
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_CAL_INIT_CALIB); /* CAL Initialization failed inside Calibration */
	  status = ALM_Eto_Reset();
	  RM_CAL_EXIT_IFETO(status);
	}  
      /*@LOG CAL Calibration  ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=CAL_Calibration();  
      if (status)
	{
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_CAL_CALIB); /* CAL Calibration failed inside Calibration */
	  status = ALM_Eto_Reset();
	  RM_CAL_EXIT_IFETO(status);
	}
      else
	status = ALM_FE_Alarm_Check(KHB_STS_ALARM_CALO | 
				    KHB_STS_ALARM_IDAQ | 
				    KHB_STS_ALARM_TRG,
				    ALM_FE_CAL_CALIB);
    }
  
  if(PRH_VAR_TRK_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG TRK Initialization  ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=TRK_Initialization();
      if (status)
	{
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_TRK_INIT_CALIB); /* TRK Initialization failed inside Calibration */
	  status = ALM_Eto_Reset();
	  RM_CAL_EXIT_IFETO(status);
	}
      /*@LOG TRK Calibration  ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=TRK_Calibration(PRH_VAR_TRK_CALIB_MODE);
      if (status)
	{
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_TRK_CALIB); /* TRK Calibration failed inside Calibration */
	  status = ALM_Eto_Reset();
	  RM_CAL_EXIT_IFETO(status);
	}
      else
	status = ALM_FE_Alarm_Check(KHB_STS_ALARM_TRK | KHB_STS_ALARM_IDAQ | KHB_STS_ALARM_TRG,ALM_FE_CAL_CALIB);
    }

  if( (PRH_VAR_AC_1_OK || PRH_VAR_AC_2_OK) && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG AC Calibration 2  ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status=AC_Calibration2();
      if (status)
	{
	  ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_AC_CALIB2); /* AC Calibration2 failed inside Calibration */
	  status = ALM_Eto_Reset();
	  RM_CAL_EXIT_IFETO(status);
	}
      else
	status = ALM_FE_Alarm_Check(KHB_STS_ALARM_S4_ADC_AC_2 |
				    KHB_STS_ALARM_AC_1 | 
				    KHB_STS_ALARM_IDAQ,ALM_FE_AC_CALIB2);      
      
      
    }


  if(PRH_VAR_S4_OK && status == CM_RC_SUCCESSFUL)
    {
      /*@LOG S4 Initializtion  ...*/
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

      status = S4_Initialization();
      
      if (status == CM_RC_SUCCESSFUL)
	{
	  if (PRH_VAR_S4_WORKING || PRH_VAR_S4_ATTEMPT)
	    {
	      /*@LOG S4 Calibration  ...*/
	      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

	      status = S4_Calibration();
	      
	      if (status)
		{
		  if (status != CM_RC_DO_POWER_OFF_ON)
		    {
		      /*@LOG S4 Calibration failed inside Calibration */
		      ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_S4_CALIB); 
		      status = ALM_Eto_Reset();
		      RM_CAL_EXIT_IFETO(status);
		    }
		}
	      else {
		status = ALM_FE_Alarm_Check_general(KHB_STS_ALARM_S4_ADC_AC_2 | KHB_STS_ALARM_IDAQ, 
						    ALM_FE_S4_CALIB,
						    KHB_ALARM_S4_ADC); 
		if(status)
		  /*@LOG S4 Calibration: AlarmCheck failed inside Calibration - status */
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);  

	      }
	    }
	}
      else
	if (status != CM_RC_DO_POWER_OFF_ON)
	  {
	    /*@LOG S4 Initialization failed inside Calibration */
	    ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_S4_INIT_CALIB);
	    status = ALM_Eto_Reset();
	    RM_CAL_EXIT_IFETO(status);
	  }
    }

  if(PRH_VAR_ND_OK) {
    /*@LOG ND Initialization ...*/
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xbabe);  

    status=    RM_ND_Initialization() ;
    if (status)
      {
	/*@LOG ND Initialization failed inside Calibration */
	ALM_WriteLog(ALM_TRACE_ID,ALM_ETO_ND);
	status = ALM_Eto_Reset();
	RM_CAL_EXIT_IFETO(status);
      }
  }
  
  cts=RM_WriteCalibrationTrailer();
  switch(status) {
  case CM_RC_SUCCESSFUL:
    RM_Calibration_Counter++;
    RM_Acq_After_Calib=TRUE;
    RM_Init_Before_Calib=FALSE;
    break;
  default:
    
  }
  
  if (cts)
    /*@LOG WriteCalibrationTrailer failed - status */
    LU_INFN_LOG(LU_CRITICAL,LU_MASK(__FILEID__),__FILEID__,__LINE__,cts);
  
  return status;
}


status_code RM_Set_ForceIdaqCmd(HB_BUF bufid,UINT16 crc) {
  /* check if the buffer force_idaq_cmd_queue is available */
  if(RM_TaskStatus != RM_OP_FORCE_IDAQCMD) {
    DAQ_BUFFER_INIT(force_idaq_cmd_queue);  
    return HB_Userdata2Buf(bufid,&force_idaq_cmd_queue,crc);
  }else
    return CM_RC_UNAVAILABLE_BUFFER;
      
}

status_code RM_Set_ForceFeCmd(HB_BUF bufid,UINT16 crc,BYTE eto,BYTE ato,DAQ_FE fe) {
  /* check if the buffer force_idaq_cmd_queue is available */
  status_code status;
  if(RM_TaskStatus != RM_OP_FORCE_IDAQCMD) {
    DAQ_BUFFER_INIT(force_idaq_cmd_queue);  
    status = HB_Userdata2Buf(bufid,&RM_buf_cmd,crc);
    RM_buf_cmd.eto=eto;
    RM_buf_cmd.ato=ato;
    if(status==CM_RC_SUCCESSFUL)
      status = DAQ_Format_Fe2Daq(&force_idaq_cmd_queue,&RM_buf_cmd,fe);
  }else
    status = CM_RC_UNAVAILABLE_BUFFER;
  return status;
}


status_code RM_LogBuffer_128_DoLog(UINT32 offset,UINT32 count) {
  UINT32 i;
  /*@LOG Interal buffer dump : len*/
  LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_128K_Buffer.len);
  for(i=0;i<count;i++)
    if(offset+i < RM_128K_Buffer.len)
      /*@LOG Interal buffer dump : data(offset+i)*/
      LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,RM_128K_Buffer.buf[offset+i]);
    else {
      /*@LOG Interal buffer dump error: offset*/
      LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,offset);
      /*@LOG Interal buffer dump error: i*/
      LU_INFN_LOG(LU_NORMAL_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,i);
      return CM_RC_INVALID_BUFFER_SIZE;
    }
  return CM_RC_SUCCESSFUL;
}

/*******************************
 * RM_Send_ForceIdaqCmd:
 * Do a acquisition sending a forced cmd-queue sent from ground (within a MCMD). 
 * 
 *******************************/

status_code RM_Send_ForceIdaqCmd()
{
  SM_ACQMODE oldmode;
  status_code status = SUCCESSFUL;
  rtems_event_set evout;
  unsigned int intLevel;
  BOOL fullPIF  = FALSE;
  static BOOL store_ram=1;

  if(force_idaq_cmd_queue.len == 0) {
    /*@LOG ForceIdaqCMD command has zero lenght */
    LU_INFN_LOG(LU_CRITICAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    return  status;
  }

  DAQ_ResetPIF(DAQ_MAX_ETO_TICS,DAQ_MAX_DTO_TICS,SM_DAQSETUP,HB_PKTTYPE_FORCED_FECMD);
  
  status = DAQ_StoreCmdQueue2PIF(SM_CALEXP0,&force_idaq_cmd_queue);
  if(status != SUCCESSFUL){
    /*@LOG SendForceIdaqCmd: error sending command - status*/
    LU_INFN_LOG(LU_CRITICAL|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    return status;
  }
  RM_128K_Buffer.len=0;
  status = DAQ_SendCmd2PIFWaitDAQReply(SM_CALEXP0,TRUE,&RM_128K_Buffer,store_ram);

  return status;
}

/*
status_code ND_Init(){
CH_SetAtoEto(CH_ND_READ_ACQ,1,2);
return CM_RC_SUCCESSFUL;
}
*/
#if 0 // NOT USED 
status_code RM_SendMultipleCommand2CMDIF(SM_PAGEID page0,SM_PAGEID page1,SM_PAGEID page2,SM_PAGEID page3)
{
  status_code status;
  SM_PAGEID last = SM_PAGEDUMMY;
  SM_PAGEID pages[4];
  int i;

  pages[0] = page0; pages[1] = page1; pages[2] = page2; pages[3] = page3;

  for(i = 0; i < 4; i++)
    if (pages[i] < SM_CALEXP0 || pages[i] > SM_CALEXP3)
      return(CM_RC_BADPAGE);
    
  for(i = 0; i < 4; i++)
    if (pages[i] != SM_PAGEDUMMY) 
      last = pages[i];
  
  PM_pi_SetExpPktCpyFlag(TRUE);

  for(i = 0; i < 4; i++)
    if (pages[i] != SM_PAGEDUMMY)
      {
	PM_pi_UseCalibrationPage(pages[i]);
	PM_piPreparePage((pages[i] == last) ? SM_WITHDAQ : SM_WITHNODAQ);
      }
  
   return(CM_RC_SUCCESSFUL);
}
#endif // 0 NOT USED

#if DEBUG
void RM_MCMDTest(UINT32 c1,UINT32 c2,UINT32 c3) {
  static UINT32 blen=64*1024;
  static UINT32 w=0;
  static UINT32 pattern=0xAA;
  status_code status,s;
  UINT32 i;
  UINT16 sw;
  SM_ACQMODE oldmode;
  DAQ_DECLBUF(hbuf,1024*64);
  switch(c1) {
  case 1:
    //oldmode = PM_pi_GetAcqMode();
    FT_piChangeAcqMode(SM_DIRECT);
    DAQ_BUFFER_INIT(hbuf);
    switch(w) {
    case 0:
      for(i=0;i<hbuf.size;i++)
	hbuf.buf[i]=(BYTE)(i & 0xff);
      hbuf.len=blen;
      break;
    case 1:
      for(i=0;i<hbuf.size/4;i++)
	((unsigned int*)hbuf.buf) [i]= pattern;
      hbuf.len=blen;
      break;
    case 2:
      {
	static unsigned long rampacounter=0; 
	*(unsigned long*)&(hbuf.buf[0])=rampacounter++;
	for(i=4;i<hbuf.size;i++)
	  hbuf.buf[i]=(BYTE)(i & 0xff);
	hbuf.len=blen;
      }
      break;
    }
    status = DAQ_SaveBuffer2MM(&hbuf,FS_HK,1000);
    /*@LOG Trace:DAQ_SaveBuffer2MM: - status */
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    //FT_piChangeAcqMode(oldmode);
    break;
  case 2:
    TRK_Initialization();
    break;
  case 3:
    TRK_Calibration(PRH_VAR_TRK_CALIB_INIT);
    break;
  case 4:
    {
      UINT32 value;
      HK_ReadKHBAlarmRegister(&value);
      /*@LOG KHB Alarm Register */
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,value);
    }
    break;
  case 5:
    {
      UINT16 value;
      HK_ReadKHBStatusRegister(&value);
      /*@LOG KHB Status register */
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,value);
    }
    break;
  case 6:
    CAL_Initialization();
    break;
  case 7:
    CAL_Calibration();
    break;
  case 8:
    TRG_Initialization();
    break;
  case 9:
    RM_LogBuffer_128_DoLog(c2,c3);
    break;
  case 10:                                        // formatta eprom quando sto in default mode 
    status = PRH_FormatEEPROM();
    /*@LOG Format EEPROM finisced - status*/
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    break;
  case 11:                                        // legge i valori correnti della eeprom e li mette in mem 
    status = PRH_ReadCurrentParam();
    /*@LOG ReadCurrentParam - status */
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    break;
  case 12:
    status = PRH_ReadDefaultParam();
    /*@LOG ReadDefaultParam - status */
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    break;
  case 13:
    status = PRH_WriteCurrentParam();
    /*@LOG WriteCurrentParam (save) - status */
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    break;
  case 15:
    status=DAQ_ReadStatusWord(&sw);
    if(status)
      /*@LOG error reading IDAQ status word  - status */
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    else
      /*@LOG IDAQ status word  - status_word */
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,sw);
    break;
  case 16:
    MC_piSetState(MC_ACTIVE_STATE);
    break;
  case 17:
    MC_piSetState(MC_MAINTENANCE_STATE);
    break;
  case 18:
    status = OS_piResourceRelease_INFN (TEST_RES);
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    break;
  case 19:
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0xffff);
    status = OS_piResourceObtain_INFN(TEST_RES,WAIT,NO_TIMEOUT);
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    break;
  case 20:
    { 
      UINT32 lev;
      OS_piInterDisable(&lev);
      ERC32_MEC.Control =0x1288801B;
      OS_piInterEnable(lev);
    }
    break;
  case 21:
    {
      status_code status = CM_RC_SUCCESSFUL;
      static int len21=1024*50;
      int j;
      DAQ_ResetPIF(DAQ_ACQ_ETO_TICS,DAQ_DEFAULT_DTO_TICS,SM_DAQSETUP,0xFF);
      SD_opSetCalibrationHeaderLength(0);
      SD_piSetSRAMRWAddress(0);
      for(j=0;j<len21;j++) {
	status=SD_piWriteSRAM( (j & 0xFF00 )>> 8);
	status=SD_piWriteSRAM(  j & 0xFF         );
      }
      while(!status && !RM_CheckSINT()){
        while(!PM_pi_ExpPageAvail()){
          {
            volatile UINT32 i;
            for(i=0;i<10000000/5489;i++); // 1ms = 10000000/5489
          }
        }
	status=PM_opPreparePage_dummy();
	status = FT_piSavePage(SM_CALPAGE, len21*2, FS_FILE1);
        /*
          {
          static valore_di_wait_dto=500*1000000;
          volatile UINT32 i;
          for(i=0;i<valore_di_wait_dto/5489;i++);
          }
        */	
      }
    }
    break;
  case 22:
    { 
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,ERC32_MEC.Control);
    }
    break;
  default:
    break;
  }
}
#endif // DEBUG








