/*  Module       : TestUtility                                               */
/*  C.I. No.     :                                                           */
/*  Revision     :                                                           */
/*  Date         :                                                           */
/*  Belonging to :                                                           */
/*               :                                                           */
/*  File Name    : TS_Test_INFN_p.c                                          */
/*  Program Type :                                                           */
/*  Sub-modules  :                                                           */
/*                                                                           */
/*****************************************************************************/
/*  S W   D e v e l o p m e n t   E n v i r o n m e n t                      */
/*                                                                           */
/*  Host system  :                                                           */
/*  SW Compiler  :                                                           */
/*  Author                                                                   */
/*               :                                                           */
/*****************************************************************************/
/*  U p d a t i n g                                                          */
/*                                                                           */
/*  Revision     :                                                           */
/*                                                                           */
/*                                                                           */
/*****************************************************************************/
 

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

#ifdef DEBUG
#define DURTY_MODE
#else
#undef DURTY_MODE 
#endif

#include <src/INFN/LU_SourceFileID_INFN.h>
#define __FILEID__ _TS_Test_INFN__c
#include <src/INFN/PRH_ParamHandler_INFN_auto.h>
#include <src/INFN/PRH_ParamHandler_INFN.h>
#include <src/INFN/LU_LogUtility_INFN.h>

LU_DECL_MASK();
LU_DECL_TRACE();


#include <src/INFN/TS_Test_INFN.h>
#include <src/MCMDManager/MCMDArea/MA_MCMDArea_p.h>
#include <src/HKManager/HistoryArea/HA_HistoryArea_p.h>
#include <src/ModeManager/ModeCoordinator/MC_ModeCoordinator_p.h>
#include <src/SRAMManager/SRAMPageManager/SM_SRAMPageManager_p.h>
#include <src/SRAMManager/SRAMDriver/SD_SRAMDriver_p.h>
#include <src/FileManager/MMSUManager/FT_MMSUManager_p.h>
#include <src/SRAMManager/SRAMDriver/SD_SRAMDriver_p.h>
#include <src/BasicSW/TimingInfo/TI_TimingInfo_op.h> /** for  TM_CYCLIC_ACQUISITION (TMTC) **/

#ifdef IOLIB
#include <stdio.h>
#endif

#include <src/TM_TCManager/TMTCManager/TM_TMTCManager_op.h>
#include <src/FileManager/MMSUManager/FT_MMSUManager_op.h>
#include <src/SRAMManager/SRAMPageManager/SM_SRAMPageManager_op.h>
#include <src/SRAMManager/SRAMPageManager/SM_SRAMPageManager_p.h>

#include <src/SRAMManager/SRAMDriver/SD_SRAMDriver_op.h>
#include <src/INFN/OS_rtems_INFN_p.h>
#include <src/INFN/DAQ_IDAQ_INFN.h>
#include <src/MCMDManager/MCMDDispatcher/MD_MCMDDispatcher_p.h>
#include <src/FileManager/MMSUManager/FT_MMSUManager_int.h>
#include <src/ModeManager/ModeCoordinator/MC_ModeCoordinator_p.h>
#include <src/INFN/HB_HKBuffer_INFN.h>
#include <src/INFN/LU_LogUtility_INFN.h>
#include <src/INFN/SCM_Manager_INFN.h>
#include <src/INFN/CH_CommandHandler_INFN.h>
#include <src/INFN/MH_ModeHandler_INFN.h>
#include <src/INFN/RM_RunManager_INFN.h>
#include <src/INFN/PM_PamManager_INFN.h>
#include <src/INFN/KHB_Driver_INFN.h>
#include <src/INFN/GS_Gas_INFN.h>
#include <src/INFN/PWR_PowerHandler_INFN.h>
#include <src/INFN/SNS_SensorsBoard_INFN.h>
#include <src/INFN/TRK_Tracker_INFN.h>
#include <src/INFN/HK_Manager_INFN.h>
#include <src/INFN/CAL_Calorimeter_INFN.h>
#include <src/INFN/TRG_Trigger_INFN.h>
#include <src/QualitySystem/DiagSupervisor/QS_DiagSupervisor_p.h>

#ifdef SIMULATOR
#include <src/BasicSW/Bus1553B/BI_Bus1553B_op.h>
#endif

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

#define HPC_PEND_INTREG_MASK   0x40
#define NCYC_PEND_INTREG_MASK  0x20
#define CYC_PEND_INTREG_MASK   0x10

#define TM_NCYCLIC_BUSY_MASK   0x8000
// #define TM_CYCLIC_BUSY_MASK    0x4000
#define TM_HPC_STATUS_MASK     0x0400
#define TM_NCYC_ERR_MASK       0x0100

#define TM_HPC_PW_MASK         0x0700
#define TM_HPC_PW_MAX          0x0007

#define PEND_INT_TIMEOUT       1000000
#define PEND_CYC_TIMEOUT       500000

#define TIMEOUT_CMD_LOOP       1000           // time out on CMD I/F

typedef unsigned char          UBYTE;
typedef unsigned short int     UWORD;
typedef unsigned long  int     UDWORD;

typedef struct
{
  unsigned int  pw;
  unsigned int  par;
}
HPC_PULSE;

static HPC_PULSE               hpcPulse[8] = 
  {
    {0x0000,  0x8000},        // 0 ms, no emission
    {0x0100,  0x0000},        // 12.5 ms    
    {0x0200,  0x0000},        // 25 ms
    {0x0300,  0x8000},        // 50 ms
    {0x0400,  0x0000},        // 100 ms
    {0x0500,  0x8000},        // 200 ms
    {0x0600,  0x8000},        // 400 ms
    {0x0700,  0x0000}         // 800 ms
  };


//Global variables

MA_HEADER_MCMD                 McMd;
static MsgTsk                  FrameMsg;

// This CustomPar should be used to allow parametrized operation 
// without the need to recompile. Please Update the list in case of changes.
// Maurizio 09/12/2002
// CustomPar[0] ----> First page to cycle on (default = 0x00) 
// CustomPar[1] ----> Last  page to cycle on (default = 0x07) 
// CustomPar[2] ----> Page size (default = 0x4000)
// CustomPar[3] ----> Page offeset (default = 0x0000)
// CustomPar[4] ----> Save pages in MM looping CustomPar[3]-times (default = 0x0001)
// CustomPar[5] ----> Length of the data packet (default = 0x4000)

static UINT32                  CustomPar      [50];
static char                    static_buff    [100];
static volatile unsigned short confStatRegVal [100];
               
static boolean                 isCycAcqActive;

extern const unsigned short*   TM_TMTCReg     [];  /* used in case 10 */
extern const TM_TC             TM_TCtable     []; /* used in case 10 */
extern const TM_TM             TM_TMtable     []; /* used in case 12 */



#ifdef DURTY_MODE

static UINT32  errors[2][0x8000];




static unsigned int checkdata=0;
static unsigned char aspettatodisp=0x55;
static unsigned char aspettatopari=0xaa;
static unsigned char aspettato[]={
  0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55,
  0xaa,0x55
};
static int aspettata_len = 55;

PRH_EXTERN_VAR(TS_kilo_104);
PRH_EXTERN_VAR(TS_readaddr_104);
PRH_EXTERN_VAR(TS_writeaddr_104);
PRH_EXTERN_VAR(TS_khb_idaq_cmd);
PRH_EXTERN_VAR(TS_len);
PRH_EXTERN_VAR(TS_104rate_n);
PRH_EXTERN_VAR(TS_104rate_wait);
PRH_EXTERN_VAR(TS_104pifwrite);
PRH_EXTERN_VAR(TS_104ramcopyfreq);
/*****************************************************************************/


static rtems_interval FULL_time_start,FULL_time_stop;
static rtems_task_priority FULL_priority,FULL_dummy;
static UINT32 FULL_level;

#define FULL_CPU_OBTAIN() do { \
  rtems_task_set_priority(RTEMS_SELF,1,&FULL_priority); \
  rtems_interrupt_disable(FULL_level); \
  rtems_clock_get(RTEMS_CLOCK_GET_TICKS_SINCE_BOOT,&FULL_time_start); \
} while(0);

#define FULL_CPU_RELEASE() do { \
    rtems_clock_get(RTEMS_CLOCK_GET_TICKS_SINCE_BOOT,&FULL_time_stop); \
    rtems_interrupt_enable(FULL_level); \
    rtems_task_set_priority(RTEMS_SELF,FULL_priority,&FULL_dummy); \
} while (0)

#define FULL_CPU_DURATION() (FULL_time_stop-FULL_time_start)


/*============= S W _ T E S T   I N T E R N A L   F U N C T I O N ===========*/

/*****************************************************************************/
/*  prototype
 * 
 *
 *  Description
 *  
 *
 *  Input parameters:   
 *                      
 *                      
 *
 *  Output parameters:  rtems_status_code
 *
 */
/*****************************************************************************/

#define MIN(A, B) (((A) < (B)) ? (A) : (B))  


#endif // DURTY_MODE

status_code TS_TestInit_INFN (void)
{
  status_code    status;
  unsigned int   OldPriority;
  unsigned int   transiz;
  unsigned char* pRc;

  status   =SUCCESSFUL;
#ifdef DURTY_MODE
  status  |=OS_piTaskReady_INFN(TS_INFN_TASK,TS_tkTest_INFN);
  status  |=OS_piTaskPriority_INFN(TS_INFN_TASK,20,&OldPriority);
#endif // DURTY_MODE
  isCycAcqActive = FALSE;

  return (status);

}


DAQ_DECLBUF(hbuf,1024*64);
static unsigned int bufsel = 4;

#ifdef DURTY_MODE

status_code TS_SndTestCode_INFN(unsigned int code) {
  MsgTsk SndMsg;
  SndMsg.Code=code;
  SndMsg.LlInfo=0;
  TS_SndMsgTest_INFN(&SndMsg);
}


int TS_TM_All(unsigned int s,unsigned int e,TI_TIME *diff) {
  unsigned int i,c;
  TI_TIME        Time_begin,Time_end,Time_diff;
  TI_piGetTimeInfo_ms(&Time_begin);
  for(i=s; i<=e ;i++) {
    HK_GetTMValue (i,&c);
  }
  TI_piGetTimeInfo_ms(&Time_end);
  *diff = Time_end - Time_begin;
}

unsigned int a,b,c,intLevel,d;
SM_ACQMODE oldmode,amode;
rtems_event_set evout;




DAQ_DECLBUF(dest,1024*128);
DAQ_DECLBUF(idaqbuf,1024*64);

DAQ_DECLBUF(cmdbuf,1024*16);
DAQ_DECLBUF(ac_idaqbuf,1024);
DAQ_DECLBUF(data,1024);
DAQ_DECLBUF(data2,1024);
DAQ_DECLBUF(idaq2,1024);
DAQ_DECLBUF(idaqcmd,16*1024);
DAQ_DECLBUF(ram_readdata,1);
DAQ_DECLBUF(flash_readdata,1);
DAQ_DECLBUF(dsp_readdata,1);
DAQ_DECLBUF(release_busy,4+1);

#endif // DURTY_MODE

/*****************************************************************************/
/*  TS_tkTest_INFN
 *
 *
 *  Input parameters:  NONE
 *
 *  Output parameters:  NONE
 *
 */
/*****************************************************************************/




#ifdef DEBUG
/* this funcion is used to force break point in case of message timeout */
unsigned int TS_FORCE_BREAKPOINT() {
  unsigned int s=SUCCESSFUL;
  return s;
}
#endif


#ifdef DURTY_MODE

status_code TS_GetCustomReadWriteRamBig(DAQ_CMD_BUF *b,UINT32 addr,UINT32 size,UINT32 *pattern) {
  DAQ_DECLBUF(all,16*1024);
  status_code s=0;
  UINT32 i,j;
  DAQ_BUFFER_INIT(all);
  for(i=0;i<size;i++) {
    all.buf[i]=(BYTE)((*pattern)++);
  }
  all.len=size;
  s|=DAQ_Format_Cmd2Ram_WriteData(b,&all);
  return s;
}

status_code TS_GetCustomWriteRam(DAQ_CMD_BUF *b,UINT32 addr,
				 UINT16 n,BYTE b1,BYTE b2,BYTE b3,BYTE b4) {
  DAQ_DECLBUF(all,16*1024);
  status_code s=0;
  UINT32 i,j;
  DAQ_BUFFER_INIT(all);
  for(i=0,j=0;i<n;i++) {
    all.buf[j++]=b1;
    all.buf[j++]=b2;
    all.buf[j++]=b3;
    all.buf[j++]=b4;
  }
  all.len=n*4;
  s|=DAQ_Format_CMD_Empty(b);
  s|=DAQ_Format_Cmd2Ram_SetAddress(b,addr);
  s|=DAQ_Format_Cmd2Ram_WriteData(b,&all);
  s|=DAQ_Format_Cmd2Ram_EndBlock(b);
  return s;
}

status_code TS_GetCustomReadRam(DAQ_CMD_BUF *b,UINT32 addr) {
  status_code s=0;
  DAQ_DECLBUF(ram_readdata,10);
  DAQ_BUFFER_INIT(ram_readdata);
  s|=DAQ_Format_CMD_Empty(b);
  s|=DAQ_Format_Cmd2Ram_SetAddress(b,addr);
  s!=DAQ_Format_Ram2Daq_ReadData(b);
  return s;
}




void TS_BF(void) {
  GS_REPLY_STRUCT s;
  UINT16 *w=(UINT16*)&s;
  UINT32 size=sizeof(s);
  UINT16 static x=0xFFFF;
  UINT16 static y=0xF0F0;
  UINT32 static dump[12];
  BYTE   *b;
  UINT32 i;
#define DUMP  for(b=(BYTE*)&s,i=0;i<12;i++,b++) dump[i]=*b;
#define ZERO  for(b=(BYTE*)&s,i=0;i<12;i++,b++) *b=0;
  ZERO;
  s.valid=x;
  DUMP;

  ZERO;
  s.command=x;
  DUMP;

  ZERO;
  s.valve_conf=x;
  DUMP;

  ZERO;
  s.curr_state=x;
  DUMP;

  ZERO;
  s.conf_soglie=x;
  DUMP;

  ZERO;
  s.err_fpga=x;
  DUMP;

  ZERO;
  s.err_pscu=x;
  DUMP;

  ZERO;
  s.cont=x;
  DUMP;

  ZERO;
  s.com=x;
  DUMP;

  y=x;
}

#define LOG_DURATION() do { \
  t=FULL_CPU_DURATION(); \
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,t>>16); \
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,t); \
} while(0)


void TS_FULL_CPU_TESTS() {
  rtems_interval t;
  UINT32 i,j,k;
  UINT32 n=20;
  DAQ_BUFFER_INIT(cmdbuf);
  for(i=0;i<cmdbuf.size;i++)
    cmdbuf.buf[i]=i;
  cmdbuf.len=cmdbuf.size;

  FULL_CPU_OBTAIN();
  // test CRC8 in 16KB buffer
  for(i=0;i<n;i++)
    DAQ_Compute_CRC16(&cmdbuf);
  FULL_CPU_RELEASE();
  LOG_DURATION();


  FULL_CPU_OBTAIN();
  // test CRC16 in 16KB buffer
  for(i=0;i<n;i++)
    DAQ_Compute_CRC16(&cmdbuf);
  FULL_CPU_RELEASE();
  LOG_DURATION();

  FULL_CPU_OBTAIN();


}

void TS_CRC() {
  static BYTE a[20] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
  BYTE bcrc = 0,b2;
  UINT16 wcrc,w2 = 0;
  static UINT16 x =0;
  UINT32 i1,i2;
  static unsigned int len=20;
  DAQ_CMD_BUF *sub;
  
  /*
  CH_GetBuf(CH_data,&sub);
  w2 = CM_Compute_CRC16(0,sub->buf,sub->len);

  return CM_Compute_CRC16(0,sub->buf,w2);
  */
  bcrc = i1 = CM_Compute_CRC8_8(0,a,len);
  wcrc = i2 = CM_Compute_CRC16(0,a,len);

  b2 = CM_Compute_CRC8_8(0,a,len);
  w2 = CM_Compute_CRC16(0,a,len);
  x =  bcrc + wcrc + b2 +w2;
  x++;
  /*
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,bcrc);
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,i1);
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,wcrc);
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,i2);
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,b2);
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,w2);
  */
}


#endif

task TS_tkTest_INFN (task_argument unused)
{

#ifdef DURTY_MODE

#define TEST_DATALEN 1024*128
  //int databuf[TEST_DATALEN];
  DAQ_DECLBUF(databuffer,TEST_DATALEN);

  status_code        status;
  unsigned int       MsgSize;
  unsigned int       counter;
  unsigned int       level,a,b,c,d,e,f,g,h,i,s;
  TI_TIME        Time_begin,Time_end,Time_diff[10];
  unsigned int timeout;
  UINT32 msg_timeout;
  MsgTsk             RxMsg;
  unsigned char  	   buf[100];
  SD_DAQ_WRESULT     pageInfo;

#define K 1024
  static UINT32 pkt_counter=0;
  static UINT32 pkt_wrong_counter=0;
  static UINT32 pkt_delta_wrong[K];
  BYTE fileid=__FILEID__;
  for(a=0;a<K;a++)
    pkt_delta_wrong[a]=0;

  LU_INFN_LOG(LU_WARNING,0xffffffff,__FILEID__,__LINE__,PRH_TOTAL_VAR_SIZE);
  LU_INFN_LOG(LU_WARNING,0xffffffff,__FILEID__,__LINE__,PRH_TOTAL_ARR_SIZE);
  LU_INFN_LOG(LU_WARNING,0xffffffff,__FILEID__,__LINE__,PRH_TOTAL_TAB_SIZE);
  LU_INFN_LOG(LU_WARNING,0xffffffff,__FILEID__,__LINE__,PRH_TOTAL_SIZE);

  LU_TRACE(__FILEID__,__LINE__);

  counter =1;
  FrameMsg.Code = TS_FRAMEWORK;
  FrameMsg.LlInfo = 0;
  CustomPar[0] = 0x0000;
  CustomPar[1] = 0x0007;
  CustomPar[2] = 0x4000;
  CustomPar[3] = 0x0000;
  CustomPar[4] = 0x0001;
  CustomPar[5] = 0x4000;


  DAQ_BUFFER_INIT(idaqbuf);
  DAQ_BUFFER_INIT(dest);
  DAQ_BUFFER_INIT(idaq2);
  DAQ_BUFFER_INIT(data);
  DAQ_BUFFER_INIT(data2);
  DAQ_BUFFER_INIT(ram_readdata);
  DAQ_BUFFER_INIT(dsp_readdata);
  DAQ_BUFFER_INIT(flash_readdata);
  DAQ_BUFFER_INIT(release_busy);

  s = DAQ_Format_Ram_ReadData(&ram_readdata);
  s = DAQ_Format_Dsp_ReadData(&dsp_readdata);
  s = DAQ_Format_Flash_ReadData(&flash_readdata);
  
  s = DAQ_Format_ReleaseBusy(&release_busy);


#ifdef DEBUG
#ifdef SIMULATOR
  msg_timeout=5000;
#else
  msg_timeout=0;
#endif // SIMULATOR
#endif      

  
  while( FOREVER )
    {
      // Check mailbox queue

      RxMsg.Code =NULL_MSG_TS_INFN;
            
      status =OS_piMsgQueueReceive_INFN (TS_INFN_MAILBOX,(void*)&RxMsg,&MsgSize,WAIT,msg_timeout);
#ifdef DEBUG
      if(status == RTEMS_TIMEOUT) 
	RxMsg.Code=TS_FORCE_BREAKPOINT();
#endif
      LU_INFN_LOG(LU_WARNING,0xffffffff,__FILEID__,__LINE__,RxMsg.Code);


      {
	switch (RxMsg.Code)
	  {
	  case 1924:
	    s = DAQ_Format_CMD_Fill(&data,300,0xbb);
	    for(i=0;i<100;i++) {
	      /*
	      if(HB_Store((HB_BUF)(i%HB_MAX),(i*123)%1024,data.buf,0) == SUCCESSFUL)
		s=1;
	      else
		s=4;
	      */
	    }
	    s = 0;
	    break;
	  case 1923:
	    { 
	      volatile int a=0x7fffffff;
	      volatile int m=0xffffffff;
	      volatile unsigned int x=23;
	      volatile unsigned int y=32;
	      volatile int b = x - y;
	      volatile int c = y - x;
	      a++;
	      m++;
	      b++;
	      a=34;
	      b=0;
	      if(a % b == 0)
		c=0;
	      if(b != 0 && a % b == 0)
		c=1;
	      c=3;
	    }
	    break;
	  case 444: {
	    unsigned int d;
	    rtems_time_of_day timeb;
	    d=rtems_clock_set(&timeb);
	    OS_piTaskSuspend(1000);
	    d=rtems_clock_get(RTEMS_CLOCK_GET_TOD , &timeb);
	  }
	    break;
	  case TS_FRAMEWORK: {         

	    // write to PIF, read back and store to MM

	    UINT32         loop;
	    UINT32         pageCounter;
	    UINT32         value, tst_value;
	    char         * RAMStartAddr;
	    char         * runAddr;
	    unsigned int intLevel;

	    RAMStartAddr = (char *) malloc(CustomPar[2] * sizeof(char));
	    if (RAMStartAddr == NULL)
	      break; 

	    if (PM_pi_GetAcqMode() == SM_EXP64/*it was SM_EXPERIMENT*/)
	      {
		TI_piGetTimeInfo_ms(&Time_begin);

		//SM_EnableStoreET = FALSE;
		OS_piInterDisable(&intLevel);
		//	  SD_piClearInt(SD_DATA_TO);
		//      ERC32_Clear_interrupt(ERC32_INTERRUPT_EXTERNAL_2);
		SD_piMaskInt(SD_WPB_EOT);
		OS_piInterEnable(intLevel);

		// Loop on pages

		for(pageCounter=CustomPar[0]; pageCounter <= CustomPar[1]; pageCounter++)
		  {
		  		  
		    // Write to the whole page

		    SD_piSetSRAMRWAddress((UINT32)((pageCounter * CustomPar[2]) + CustomPar[3]));		    

		    for(loop=0; loop < CustomPar[2]; loop++) {
		      //			SD_piSetSRAMRWAddress((UINT32)((pageCounter * CustomPar[2]) + CustomPar[3] + loop));		      // try this ...
		      value=(loop + pageCounter) & 0x000000FF;
		      SD_piWriteSRAM(value);
		    }
		  }

		TI_piGetTimeInfo_ms(&Time_end);
		Time_end = Time_end - Time_begin;

		//Test what has been written
		  
		for(pageCounter=CustomPar[0]; pageCounter <= CustomPar[1]; pageCounter++)
		  {
		  
		    SD_piSetSRAMRWAddress((UINT32)((pageCounter * CustomPar[2]) + CustomPar[3]));
		  
		    //Read on the whole page
		    runAddr = RAMStartAddr;		  

		    for(loop=0; loop < CustomPar[2]; loop++)
		      {
			//			  SD_piSetSRAMRWAddress((UINT32)((pageCounter * CustomPar[2]) + CustomPar[3] + loop));                    // try this ...
			//			  *runAddr = SD_piReadSRAM();
			value = SD_piReadSRAM();
			//			  *runAddr = value;

			//			  if (*runAddr++ != ((loop + pageCounter) & 0xFF))
			if (value != ((loop + pageCounter) & 0xFF))
			  {
			    //			    sprintf(buf,"Error on page %02X location: %04X  read: %08X", pageCounter, loop, value);
			    //			      puts(buf);
			  }
		      }
		  }
 
		// Save to MM  ,  explicit saving 
		
		for (loop = 0; loop < CustomPar[4]; loop++)
		  {
		    for(pageCounter=CustomPar[0]; pageCounter <= CustomPar[1]; pageCounter++)
		      {
			// Put a save request for the SRAM page in the save queue

			  pageInfo = (UINT32)(pageCounter * CustomPar[2]) + CustomPar[2] + CustomPar[3] - 1;

			  // force storage to FS_FILE1

			  TI_piGetTimeInfo_ms(&Time_begin);
			  if(FT_piSavePage(pageCounter, pageInfo, FS_FILE1) != FT_SUCCESS)
			    {
			      /* The save request was refused */
			      //			      sprintf(buf,"Page number %02X store request refused ", pageCounter);
			      //			      puts(buf);
			    }
			  else 
			    {
			      /* The save request was accepted */
			      /* so lock the (((skatchboard))) page  */
			      //			      sprintf(buf,"Page number %02X store accepted  ", pageCounter);
			      //			      puts(buf);
			    }	    
	  		  TI_piGetTimeInfo_ms(&Time_end);
			  Time_end = Time_end - Time_begin;
			}
		    }

		  /* Disable storage on Event Trigger Interrupt */
		  OS_piInterDisable(&intLevel);
		  SD_piUnMaskInt(SD_WPB_EOT);
		  //SM_EnableStoreET = TRUE;
		  OS_piInterEnable(intLevel);

		}  

	      free(RAMStartAddr);
	      
	      break;
	    }
				

	    case 2: {         

	      // Write flexible to SRAM pages   w/o MM
	      //  CustomPar:
	      //  0 = start page (0,1,...)
	      //  1 = page offset
	      //  2 = nb.bytes to write 

	      UINT32         loop;
	      UINT32         * RAMStartAddr;
	      UINT32         * runAddr;

	      RAMStartAddr = (UINT32 *) malloc(CustomPar[2] * sizeof(UINT32));

	      if (RAMStartAddr == NULL)
		break; 

	      if (PM_pi_GetAcqMode() == SM_EXP64/*it was SM_EXPERIMENT*/)
		{
		  SD_piSetSRAMRWAddress((UINT32)((CustomPar[0] * 0x4000) + CustomPar[1]));		    
		  
		      for(loop=0; loop < CustomPar[2]; loop++)
			SD_piWriteSRAM((loop + CustomPar[0]) & 0x000000FF);

		      // Test what has been written

		      SD_piSetSRAMRWAddress((UINT32)((CustomPar[0] * 0x4000) + CustomPar[1]));		    
		      runAddr = RAMStartAddr;
		  
		      for(loop=0; loop < CustomPar[2]; loop++)
			{
			  *runAddr = SD_piReadSRAM();
			  if ((UINT32) *runAddr != ((loop + CustomPar[0]) & 0xFF))
			    {
			      //			      sprintf(buf,"Error on location: %04X  read: %08X", loop,(UINT32 *) runAddr );
			    }
			  runAddr++;
			}			      
		}

	      free(RAMStartAddr);	      
	      break;
	    }

	    case 3: 	      {         

	      // read back from critical SRAM area (last 0xff)
	      //    CustomPar  0=page.nb.; 1=write-offset, 2=nb.bytes, 3=additional read-offset 
	      
	      UINT32           loop;
	      UINT32         * RAMStartAddr, * RAMStartAddr_1;
	      UINT32         * runAddr, * runAddr_1;
	      UINT32           value;
	      
	      RAMStartAddr   = (UINT32 *) malloc(0xe0 * sizeof(UINT32));
	      RAMStartAddr_1 = (UINT32 *) malloc(0xe0 * sizeof(UINT32));
	      
	      if (RAMStartAddr == NULL)
		break; 
	      
	      // Fill test array
	      runAddr = RAMStartAddr;
	      //		for(loop = 0;  loop < 0xe0;  loop++)
	      for(loop = 0;  loop < CustomPar[2];  loop++)
		*runAddr++ = loop & 0xFF;
	      

	      //  write to SRAM
	      //		    SD_piSetSRAMRWAddress((UINT32)((CustomPar[0] * 0x4000) + 0x3f10));		    
	      SD_piSetSRAMRWAddress((UINT32)((CustomPar[0] * 0x4000) + CustomPar[1]));		    		  
	      runAddr = RAMStartAddr;
		  
	      for(loop = 0; loop < CustomPar[2]; loop++)
		SD_piWriteSRAM((unsigned char) (*runAddr++ & 0x000000FF));
	      
	      //Test what has been written : with read-offset
	      
	      SD_piSetSRAMRWAddress((UINT32)((CustomPar[0] * 0x4000) + CustomPar[1] + CustomPar[3]));		    		  
	      runAddr   = RAMStartAddr + CustomPar[3];
	      runAddr_1 = RAMStartAddr_1 + CustomPar[3];
	      
	      for(loop = 0; loop < (CustomPar[2]-CustomPar[3]); loop++)
		{
		  value = (UINT32) SD_piReadSRAM();
		  *(runAddr_1++) = value;
		  if ((UINT32) *(runAddr++) != value) {
		    // sprintf(buf,"Error on location: %04X  read: %08X", loop,(UINT32 *) runAddr );
		  }
		}			      
	      
	      free(RAMStartAddr);	      
	      free(RAMStartAddr_1);	      
	      break;
	    }


	    case 9: {         
	      
	      // use Store_Packet  (inspired by OrbitalData)   RW, 12/2002			

	      status_code       status;
	      status_code       statusTemp;
	      SM_ACQMODE        PrevAcqMode;
	      FS_FILE_DESCR     FileInfo;
	      //	      unsigned char     tst_pkt[0x4000];
	      unsigned char   * tst_pktPtr,
		              * runAddr;
	      int loop;

	      tst_pktPtr   = (unsigned char *) malloc(0x4000 * sizeof(char));
	      if (tst_pktPtr == NULL)
		break; 

	      //Write on the whole page

	      runAddr = tst_pktPtr;
	      for(loop = 0;  loop < 0x4000;  loop++)
		*runAddr++ = loop & 0xFF;

	      /* eventuali controlli sulla fattibilità dello switch in Experiment */
	      PrevAcqMode = PM_pi_GetAcqMode();

	      /* così acq al max 16k */
	      FT_piChangeAcqMode(SM_EXP64/*it was SM_EXPERIMENT*/);

	      //	      sprintf(buf,"Packet filled  nbyte=%08X ", loop);
	      //	      puts(buf);
	      //	      TS_piPrintMiniCom_INFN (buf);

	      if (FS_piGetFileInfo (FS_FILE1, &FileInfo) != FS_FILEISFULL)
		{
		  if ( (statusTemp = PM_pi_StorePacket (0x4000, tst_pktPtr, FS_FILE1)) != SUCCESSFUL)
		    {
		      status = statusTemp;
		      
		    }
		  else
		    status = FS_FILEISFULL;
		
		}

	      /* gli stati dei file possono essere ricavati dal RTF */
	      /* Il codice può salvare i dati nel file di HK (o di experimento) e ritornare FILE_FULL x' uno dei due è pieno */	    
		    
	      FT_piChangeAcqMode(PrevAcqMode);
	      
	      // HA_piLogHistoryEntry2 (PtrMcmd->Type,status);
	      //	      sprintf(buf,"Store Packet finished \n ");
	      //	      puts(buf);
	      //	      TS_piPrintMiniCom_INFN (buf);
	      
	      free(tst_pktPtr);		    
	    }
	      break;
	      
	    case 20:
	      {         
		int i;

		for (i = 0;  i < CustomPar[0];  i++)
		  {
		    // Set Page & End Address
		    SD_piSetCMDBUSReadPage (CustomPar[1]);
		    SD_piSetCMDBUSReadParams (CustomPar[1]*0x4000 + CustomPar[2]);
		    // Start DMA
		    SD_piStartTransferToCMD();
		    // Delay for next DMA
		    OS_piTaskSuspend (CustomPar[3]);
		  }

		break;
	      }

           case 40:
             {
               // use Store_Packet to fill 1M of MM   THOR, 05/06/2003

               status_code       statusTemp;
               unsigned char   * tst_pktPtr,
                               * runAddr;
               int               i;
               SM_ACQMODE        PrevAcqMode;
               FS_FILE_DESCR     FileInfo;

               tst_pktPtr   = (unsigned char *) malloc(0x4000 * sizeof(char)); 
               if (tst_pktPtr == NULL)
                 break;

               //Write on the whole page

               runAddr = tst_pktPtr;

               for(i = 0;  i < 0x4000;  i++)
                 *runAddr++ = i & 0xFF;


               // eventuali controlli sulla fattibilita dello switch in Experiment

               PrevAcqMode = PM_pi_GetAcqMode();

               FT_piChangeAcqMode(SM_EXP64/*it was SM_EXPERIMENT*/);

	       CustomPar[0]=200;

               for (i = 0;  i < CustomPar[0];  i++)
                 {
                   if (FS_piGetFileInfo (FS_FILE1, &FileInfo) != FS_FILEISFULL)
                     {
                       if ( (statusTemp = PM_pi_StorePacket (0x4000, tst_pktPtr, FS_HK)) != SUCCESSFUL)
                         {
			   status = FS_FILEISFULL;
                         }
                     }
		   
		   CustomPar[1] = 50;

                   OS_piTaskSuspend (CustomPar[1]);
                 }

             FT_piChangeAcqMode(PrevAcqMode);

             free(tst_pktPtr);
             break;
             }

	    case 41:
	      {
		// use SavePage to fill 1M of MM   THOR, 05/06/2003
		
		status_code       statusTemp;
		unsigned char   * runAddr,
		                * RAMStartAddr;
		int               i,
		                  loop,
		                  page_size;
		SM_ACQMODE        PrevAcqMode;
		FS_FILE_DESCR     FileInfo;
		TI_TIME           Time_begin,
		                  Time_end;
		unsigned int    * deltaT_array,
		                  min_val        = 0xFFFFFFFF,
		                  max_val        = 0,
		                  ave_val        = 0;

		deltaT_array = (unsigned int *)  malloc(CustomPar[2] * sizeof(int));

		if (deltaT_array == NULL)
		  break; 
	      
		RAMStartAddr = (unsigned char *) malloc(0x4000 * sizeof(char));

		if (RAMStartAddr == NULL)
		  break; 
			
		//fill the RAM buffer with zeroes
		
		runAddr = RAMStartAddr;
			
		for(loop = 0;  loop < 0x4000;  loop++)
		  *runAddr++ = 0;
		
		//fill the PIF PAGE with a counter or a unique value
		
		SD_piSetSRAMRWAddress  ((UINT32) (CustomPar[0] * 0x4000));		    		  
		
		for (i = 0;  i < 0x4000;  i++) {                             
		  if (CustomPar[1] == 0xffff)  SD_piWriteSRAM ((unsigned char) (0xff & i));
		  else SD_piWriteSRAM ((unsigned char) (CustomPar[1]));
		}

		// eventuali controlli sulla fattibilita dello switch in Experiment
		
		PrevAcqMode = PM_pi_GetAcqMode();

		FT_piChangeAcqMode(SM_EXP64/*it was SM_EXPERIMENT*/);

		for (i = 0;  i < CustomPar[2];  i++)                // 0x10000 ==> 64 k   -   Loop over pages
		  {
		    SD_piSetSRAMRWAddress  ((UINT32) (CustomPar[0] * 0x4000));		    		  

		    // writes boundary word (0xFFFF)

		    SD_piWriteSRAM ((unsigned char) (0xFF));
		    SD_piWriteSRAM ((unsigned char) (0xFF));

		    // writes counter into first and last word of the PIF PAGE

		    SD_piWriteSRAM ((unsigned char) ((i & 0xFF00) >> 8));    // MOST SIGNIFICANT BYTE of the 16 bit counter
		    SD_piWriteSRAM ((unsigned char) (i & 0xFF));             // LEAST SIGNIFICANT BYTE of the 16 bit counter

		    SD_piSetSRAMRWAddress  ((UINT32) ((CustomPar[0] + 1) * 0x4000 - 2));		    		  

		    SD_piWriteSRAM ((unsigned char) ((i & 0xFF00) >> 8));    // MOST SIGNIFICANT BYTE of the 16 bit counter
		    SD_piWriteSRAM ((unsigned char) (i & 0xFF));             // LEAST SIGNIFICANT BYTE of the 16 bit counter

		    if (CustomPar[3])
		      {
			// Test what has been written
			
			SD_piSetSRAMRWAddress  ((UINT32) (CustomPar[0] * 0x4000));		    		  
			
			runAddr = RAMStartAddr;
			
			for(loop = 0;  loop < 0x4000;  loop++)
			  *runAddr++ = SD_piReadSRAM();
		      }

		    //---------------------------------------------------------------------------------------------------------------------

		    if (CustomPar[5])
		      TI_piGetTimeInfo_ms(&Time_begin);

		    page_size=0x4000;
		    if (CustomPar[6] && (i==0)) page_size=0x2000;          // first page = 8kB in special mode

		    /*
		    if (FS_piGetFileInfo (FS_FILE1,   &FileInfo) != FS_FILEISFULL)
		      FT_piSavePage     (CustomPar[0],  (CustomPar[0] + 1) * 0x4000 - 1,  FS_FILE1);	      // force storage to FS_FILE1
		    else
		      if (FS_piGetFileInfo (FS_FILE2,   &FileInfo) != FS_FILEISFULL)
			FT_piSavePage   (CustomPar[0],  (CustomPar[0] + 1) * 0x4000 - 1,  FS_FILE2);          // force storage to FS_FILE2
		    */
		    if (FS_piGetFileInfo (FS_FILE1,   &FileInfo) != FS_FILEISFULL)
		      FT_piSavePage     (CustomPar[0], CustomPar[0]*0x4000 + page_size - 1,  FS_FILE1);	

		    if (CustomPar[5])
		      {
			while (FT_opSaveInProgress ())
			  OS_piTaskSuspend (1);

			TI_piGetTimeInfo_ms(&Time_end);

			Time_end -= Time_begin;      // delta time 

			deltaT_array [i] = Time_end;

			if (min_val > Time_end )
			  min_val =  Time_end;

			ave_val = ave_val + Time_end * 100;

			if (max_val < Time_end )
			  max_val =  Time_end;
		      }

		    //---------------------------------------------------------------------------------------------------------------------
		    
		    if (!CustomPar[5])
		      OS_piTaskSuspend (CustomPar[4]);
		  }

		if (CustomPar[5])
		  ave_val = ave_val / CustomPar[2];
		  
		FT_piChangeAcqMode(PrevAcqMode);

		free (RAMStartAddr);
		free (deltaT_array);
		break;
	      }

	    case 42:
	      {
		int      i;
		
		SD_piSetSRAMRWAddress  ((UINT32) (SM_CALEXP0 * 0x4000));		    		  

		for (i = 0;  i < CustomPar[0];  i++)		
		  SD_piWriteSRAM ((unsigned char) (CustomPar[i + 1]));

		SD_piSetCMDBUSReadPage    (SM_CALEXP0);
		SD_piSetCMDBUSReadParams  (SM_CALEXP0 * 0x4000 + CustomPar[0] - 1);

		SD_piStartTransferToCMD   ();
		break;
	      }

	    case 43:
	      {
		int      i;
		
		SD_piSetSRAMRWAddress  ((UINT32) (SM_CALPAGE * 0x4000));		    		  

		for (i = 0;  i < 0x4000;  i++)		
		  SD_piWriteSRAM ((unsigned char) 0);
		

		SD_piSetSRAMRWAddress  ((UINT32) (SM_CALEXP0 * 0x4000));		    		  

		for (i = 0;  i < CustomPar[0];  i++)		
		  SD_piWriteSRAM ((unsigned char) (CustomPar[i + 1]));

		SD_piSetCMDBUSReadPage    (SM_CALEXP0);
		SD_piSetCMDBUSReadParams  (SM_CALEXP0 * 0x4000 + CustomPar[0] - 1);

		//		SD_piStartTransferToCMD   ();

		SD_piSetDAQWritePage      (SM_CALPAGE);
		SD_piTrigCalibrationEvent ();
		SD_piStartTransferToCMD   ();
		
		break;
	      }
	    case 44:
	      {
		int      i;
	        // la prima volta:
		// devi fare print PM_pi_UseCalibrationPage(SM_CALEXP0) (la8)
		// poi source scrivoinramidaq  perpcaricare la pagina
		

		// devi fare print PM_pi_UseCalibrationPage(SM_CALEXP1) (la9)
		// poi source rileggiramidaqdirettamente (o in rileggiramidaq_reset_44) per pcaricare la pagina
		// poi mettere il SW nello stato DAQSETUP (B3)
		// poi source tkTest_msg44 per mandare l'opportuno messaggio a questo task		
	
		ERC32_Force_interrupt(ERC32_INTERRUPT_EXTERNAL_5);
		
		break;
	      }

	  case 45:
	      {
		int      i;
		
		SD_piSetSRAMRWAddress  ((UINT32) (SM_CALEXP0 * 0x4000));		    		  

		for (i = 0;  i < CustomPar[0];  i++)		
		  SD_piWriteSRAM ((unsigned char) (CustomPar[i + 1]));

		SD_piSetCMDBUSReadPage    (SM_CALEXP0);
		SD_piSetCMDBUSReadParams  (SM_CALEXP0 * 0x4000 + CustomPar[0] - 1);

		//		SD_piStartTransferToCMD   ();

		SD_piSetDAQWritePage      (SM_CALPAGE);
		SD_piStartTransferToCMD   ();
		SD_piTrigCalibrationEvent ();
		
		break;
	      }

	    case 46:
	      {
		// Test of the CMD/DAQ BUS : 16 k out / 16 k in; check of bytes recived both in DSP and CPU; check of CMD byte counter at the end of duplex transmission

		UINT32       intLevel;
		UINT32       i,
		             loop,
		             value_pir,
		             cnt,
		             pkt_size,
		             value,
		             cnt_err,
		             error_ovr,
		             cmd_counter_error,
		             timeOutCMD,
		             timeOutCMD_max,
		             timeOutCMD_cnt;
		UINT32     * runAddr,
		           * RAMStartAddr,
		             cmdCounterLeft;
	      
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//  set timeout: DTO & EOT
		//  set event timeout to maximum (4.26 s)

		*((unsigned char *) 0x980003b6) = 0xff;
		*((unsigned char *) 0x980003b8) = 0xff;
      
		// set data timeout (LSB bit is 508 ns)

		*((unsigned char *) 0x9800039a) = 0x01;
		*((unsigned char *) 0x9800039c) = 0x0f;

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//  header length = 0  

		*((unsigned char *) 0x9800039E) = 0x00;
		
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		// Disable ETO / DTO / PAGE OVR Interrupt 

		OS_piInterDisable(&intLevel);
		SD_piClearInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);
		SD_piMaskInt(SD_WPB_EOT | SD_DATA_TO | SD_EVT_TO);        // DTO & ETO
		OS_piInterEnable(intLevel);
		    
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		error_ovr         = 0x0;
		cnt_err           = 0;
		cmd_counter_error = 0;
		timeOutCMD_max    = 0;
		timeOutCMD_cnt    = 0;

		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//fills the CMD PAGE with a counter
		
		SD_piSetSRAMRWAddress  ((UINT32) (CustomPar[0] * 0x4000));		    		  
		
		for (i = 0;  i < (0x4000 / 2);  i++)
		  {
		    SD_piWriteSRAM ((unsigned char) (((i & 0xFF00) >> 8)));    // MOST SIGNIFICANT BYTE of the 16 bit counter
		    SD_piWriteSRAM ((unsigned char) (i & 0xFF));              // LEAST SIGNIFICANT BYTE of the 16 bit counter
		  }
		
		for (loop = 0;  loop < CustomPar[5];  loop++)
		  {
		    // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		    //fills the DAQ PAGE with a unique value
		    
		    SD_piSetSRAMRWAddress  ((UINT32) (CustomPar[2] * 0x4000));		    		  
		
		    for (i = 0;  i < 0x4000;  i++)
		      SD_piWriteSRAM ((unsigned char) (CustomPar[3]));

		    // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		    //  select pages
		
		    SD_piSetCMDBUSReadPage   (CustomPar[0]);                                 // CMD
		    SD_piSetCMDBUSReadParams (CustomPar[0] * 0x4000 + CustomPar[1] - 1);
		    
		    *((unsigned char *) 0x980003A2) = CustomPar[2];                          // DAQ

		    // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		    // Start DMA-DAQ  --  DAQ Mode
		
		    *((unsigned char *) 0x98000396) = 0xff;
	
		    // Start CMD-DMA

		    SD_piStartTransferToCMD();
	
		    // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		    // wait for DTO IR

		    value_pir = 0x0;
		    cnt       = 0;
		    
		    while (!(value_pir & 0x01) && (cnt < CustomPar[4]))
		      {
			value_pir = (unsigned int) (*(unsigned char *) 0x98000394);
			
			if (value_pir & 0x10)       // OVR
			  {
			    error_ovr++;
			    break;
			  }
			
			cnt++;
		      }
		
		    if (cnt >= CustomPar[4])
		      timeOutCMD = 0;  // use as dummy instruction to break at timeout 
   
		    // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		    if ((cnt < CustomPar[4]) && !error_ovr)           // NO TIMEOUT,  NO OVR
		      {
			// wait until the buffer on CMD I/F is empty
			
			timeOutCMD = 0;

			while (SD_piGetCMDCounterLeft() != 0)
			  timeOutCMD++;

			if (timeOutCMD > timeOutCMD_max)
			  {
			    timeOutCMD_cnt++;
			    timeOutCMD_max = timeOutCMD;
			  }
			
			// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
			pkt_size = 0;
			pkt_size = SD_piGetDAQWriteResult() + 1;
			
			SD_piSetSRAMRWAddress((UINT32) (CustomPar[2] * 0x4000));		    		  
			
			// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

			RAMStartAddr = (UINT32 *) malloc(0x4000 * sizeof(UINT32));

			if (RAMStartAddr == NULL)
			  break; 
			
			// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

			//fills the RAM buffer with zeroes
			
			runAddr = RAMStartAddr;
			
			for(i = 0;  i < 0x4000;  i++)
			  *runAddr++ = 0;
		    
			// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

			runAddr = RAMStartAddr;
			
			for (i = 0;  i < (pkt_size / 2);  i++)
			  {
			    value  = (SD_piReadSRAM() << 8) & 0xFF00;
			    value |=  SD_piReadSRAM() & 0xFF;
			    
			    *runAddr++ = value;
			    
			    if (value != i)    // error
			      {
				errors[0][cnt_err] = i;
				errors[1][cnt_err] = value;
				
				cnt_err++;
			      }
			  }

			// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
			
			cmdCounterLeft = 0;
			cmdCounterLeft = SD_opGetCMDCounterLeft ();

			if (cmdCounterLeft != 0)
			  cmd_counter_error++;
			  
			// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

			free (RAMStartAddr);
		      }
		  }
    
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		// Enable ETO / DTO / PAGE OVR Interrupt 

		OS_piInterDisable(&intLevel);
		SD_piClearInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);
		SD_piUnMaskInt(SD_WPB_EOT | SD_DATA_TO | SD_EVT_TO);        // DTO & ETO
		OS_piInterEnable(intLevel);
		    
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		break;
	      }

	    case 47:
	      {
		// Test of the CMD/DAQ BUS : 16 k out (different pages) / 64 k in; check of bytes recived both in DSP and CPU; check of CMD byte counter at the end of CMD transmission
		
		UINT32       intLevel;
		UINT32       page,
		             daq_page,
		             i,
		             timeOutCMD,
		             timeOutCMD_err,
		             value_pir,
		             cnt,
		             pkt_size,
		             value1,
		             value2,
		             value,
		             cnt_err;
		UINT32     * runAddr,
		           * RAMStartAddr;

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//  set timeout: DTO & EOT
		//  set event timeout to maximum (4.26 s)

		*((unsigned char *) 0x980003b6) = 0xff;
		*((unsigned char *) 0x980003b8) = 0xff;
      
		// set data timeout (LSB bit is 508 ns)

		*((unsigned char *) 0x9800039a) = 0x01;
		*((unsigned char *) 0x9800039c) = 0x0f;

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//  header length = 0  

		*((unsigned char *) 0x9800039E) = 0x00;
		*((unsigned char *) 0x980003A0) = 0x00;        // necessario per azzerare l'header offset nel caso di acquisizione a 64/128 K
		
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		// Disable ETO / DTO / PAGE OVR Interrupt 

		OS_piInterDisable(&intLevel);
		SD_piClearInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);
		SD_piMaskInt(SD_WPB_EOT | SD_DATA_TO | SD_EVT_TO);        // DTO & ETO
		OS_piInterEnable(intLevel);
		    
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		// selects SM_PAGE0..SM_PAGE3 or SM_PAGE4..SM_PAGE7 as DAQ PAGE

		if (CustomPar[1] == 1)
		  daq_page = SM_PAGE0;
		else
		  daq_page = SM_PAGE4;

		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//  programs DAQ DMA
		
		*((unsigned char *) 0x980003A2) = daq_page;
		
		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//fills the DAQ PAGE with a unique value
		    
		SD_piSetSRAMRWAddress  ((UINT32) (daq_page * 0x4000));		    		  
		
		for (i = 0;  i < 0x10000;  i++)                     // 64 k
		  SD_piWriteSRAM ((unsigned char) (CustomPar[2]));

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		// sends the 4 SM_CALEXP pages to the DSP

		for (page = SM_CALEXP0;  page <= SM_CALEXP3;  page++)
		  {
		    //fills the CMD PAGE with a counter
		
		    SD_piSetSRAMRWAddress  ((UINT32) (page * 0x4000));		    		  
		
		    for (i = 0;  i < (0x4000 / 2);  i++)
		      {
			SD_piWriteSRAM ((unsigned char) ((((i + (page - SM_CALEXP0) * 0x2000)) & 0xFF00) >> 8));    // MOST SIGNIFICANT BYTE of the 16 bit counter
			SD_piWriteSRAM ((unsigned char) ((i + (page - SM_CALEXP0) * 0x2000) & 0xFF));               // LEAST SIGNIFICANT BYTE of the 16 bit counter
		      }
		
		    // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    //  programs CMD DMA
		
		    SD_piSetCMDBUSReadPage   (page);
		    SD_piSetCMDBUSReadParams (page * 0x4000 + CustomPar[0] - 1);

		    // Start CMD-DMA

		    SD_piStartTransferToCMD();
	
		    // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    // wait until the buffer on CMD I/F is empty

		    timeOutCMD = 0;

		    while ((SD_piGetCMDCounterLeft() != 0) && (timeOutCMD < TIMEOUT_CMD_LOOP))
		      timeOutCMD++;

		    if (timeOutCMD >= TIMEOUT_CMD_LOOP)
		      timeOutCMD_err++;
		  }

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		// receives 64 k bytes from the DSP

		// Start DMA-DAQ  --  DAQ 64 k Mode (DTO/ETO/OVR received)
		
		*((unsigned char *) 0x980003E2) = 0xff;
	
		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		// wait for DTO IR

		value_pir = 0x0;
		cnt       = 0;
		    
		while (!(value_pir & 0x01) && (cnt < CustomPar[3]))
		  {
		    value_pir = (unsigned int) (*(unsigned char *) 0x98000394);
		    cnt++;
		  }
		
		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		if (cnt < CustomPar[3])   // NO TIMEOUT
		  {
		    RAMStartAddr = (UINT32 *) malloc(0x8000 * sizeof(UINT32));

		    if (RAMStartAddr == NULL)
		      break; 
			
		    // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    //fills the RAM buffer with zeroes
		
		    runAddr = RAMStartAddr;
			
		    for(i = 0;  i < 0x8000;  i++)
		      *runAddr++ = 0;
		    
		    // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    pkt_size = 0;

		    if (CustomPar[1] == 1)
		      pkt_size = SD_piGetDAQWriteResult() + 1;		      
		    else
		      pkt_size = SD_piGetDAQWriteResult() + 1 - 0x10000;
			
		    SD_piSetSRAMRWAddress((UINT32) (daq_page * 0x4000));		    		  
			
		    // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    runAddr = RAMStartAddr;
		    cnt_err = 0;

		    if (pkt_size > 0x10000)
		      pkt_size = 0x10000;

		    for (i = 0;  i < (pkt_size / 2);  i++)
		      {
			//			value  = (SD_piReadSRAM() << 24) & 0xFF000000;
			//			value |= (SD_piReadSRAM() << 16) & 0x00FF0000;
			value1  = SD_piReadSRAM();
			value2  = SD_piReadSRAM();

			value  = (value1 << 8)  & 0x0000FF00;
			value |=  value2 & 0xFF;
			    
			*runAddr++ = value;
			    
			if (value != i)    // error
			  {
			    errors[0][cnt_err] = i;
			    errors[1][cnt_err] = value;
				
			    cnt_err++;
			  }
		      }
  
		    // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    free (RAMStartAddr);
		  }

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		// Enable ETO / DTO / PAGE OVR Interrupt 

		OS_piInterDisable(&intLevel);
		SD_piClearInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);
		SD_piUnMaskInt(SD_WPB_EOT | SD_DATA_TO | SD_EVT_TO);        // DTO & ETO
		OS_piInterEnable(intLevel);
		    
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		break;
	      }

	    case 48:
	      {
		// Test of the CMD/DAQ BUS : 1 byte out / 128 k in; check of bytes recived in CPU; check of PAGE OVERRUN
		
		UINT32       intLevel;
		UINT32       i,
		             value_pir,

		             cnt,
		             pkt_size,
		             value,
		             cnt_err;
		char       * runAddr,
		           * RAMStartAddr;
		BOOL         ovr_detached;

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//  set timeout: DTO & EOT
		//  set event timeout to maximum (4.26 s)

		*((unsigned char *) 0x980003b6) = 0xff;
		*((unsigned char *) 0x980003b8) = 0xff;
      
		// set data timeout (LSB bit is 508 ns)

		*((unsigned char *) 0x9800039a) = 0x01;
		*((unsigned char *) 0x9800039c) = 0x0f;

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//  header length = 0  

		*((unsigned char *) 0x9800039E) = 0x00;
		*((unsigned char *) 0x980003A0) = 0x00;        // necessario per azzerare l'header offset nel caso di acquisizione a 64/128 K
		
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		// Disable ETO / DTO / PAGE OVR Interrupt 

		OS_piInterDisable(&intLevel);
		SD_piClearInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);
		SD_piMaskInt(SD_WPB_EOT | SD_DATA_TO | SD_EVT_TO);        // DTO & ETO
		OS_piInterEnable(intLevel);
		    
		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//  programs DAQ DMA
		
		*((unsigned char *) 0x980003A2) = 0;                 // partiamo da pagina 0
		
		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//fills the DAQ PAGE with a unique value
		    
		SD_piSetSRAMRWAddress  ((UINT32) (0));              // partiamo da pagina 0		    		  
		
		for (i = 0;  i < 0x20000;  i++)                     // 128 k
		  SD_piWriteSRAM ((unsigned char) (CustomPar[0]));

		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		//clears the CMD PAGE
		    
		SD_piSetSRAMRWAddress  ((UINT32) ((UINT32) (SM_CALEXP0 * 0x4000)));		    		  
		
		for (i = 0;  i < 0x4000;  i++)                     // 128 k
		  SD_piWriteSRAM ((unsigned char) (0));

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		// sends 1 byte to the DSP thru CMD BUS

		SD_piSetSRAMRWAddress    ((UINT32) (SM_CALEXP0 * 0x4000));		    		  
		SD_piWriteSRAM           ((unsigned char) (0));
		SD_piSetCMDBUSReadPage   (SM_CALEXP0);
		SD_piSetCMDBUSReadParams (SM_CALEXP0 * 0x4000 + 1 - 1);

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		// receives 128 k bytes from the DSP

		// Start DAQ-DMA  --  DAQ 128 k Mode (DTO/ETO/OVR received)
		
		*((unsigned char *) 0x98000398) = 0x00;
	
		// Start CMD-DMA

		SD_piStartTransferToCMD  ();

		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		// wait for DTO IR

		value_pir    = 0x0;
		cnt          = 0;
		ovr_detached = FALSE;
		    
		while (!(value_pir & 0x01) && (cnt < CustomPar[1]))
		  {
		    value_pir = (unsigned int) (*(unsigned char *) 0x98000394);

		    if (value_pir & 0x10)               // OVR
		      ovr_detached = TRUE;
		    
		    cnt++;
		  }
		
		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		if (cnt < CustomPar[1])            // NO TIMEOUT
		  {
		    RAMStartAddr = (char *) malloc (0x20000 * sizeof(char));

		    if (RAMStartAddr == NULL)
		      break; 
			
		    // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    //fills the RAM buffer with zeroes
		
		    runAddr = RAMStartAddr;
			
		    for(i = 0;  i < 0x20000;  i++)
		      *runAddr++ = 0;
		    
		    // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    pkt_size = 0;
		    pkt_size = SD_piGetDAQWriteResult() + 1;

		    if (pkt_size > 0x20000)
		      pkt_size = 0x20000;
			
		    // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    runAddr = RAMStartAddr;
		    cnt_err = 0;

		    SD_piSetSRAMRWAddress((UINT32) (0));                 // partiamo da pagina 0		    		  
			
		    for (i = 0;  i < pkt_size;  i++)
		      {
			value  = SD_piReadSRAM();
			    
			*runAddr++ = value;
			    
			if (value != (i & 0xFF))    // error
			  {
			    errors[0][cnt_err] = i;
			    errors[1][cnt_err] = value;
				
			    cnt_err++;
			  }
		      }
  
		    // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		    free (RAMStartAddr);
		  }
		
		// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		if (ovr_detached == TRUE)            // PAGE OVERRUN
		  {
		    // controlla che non sia stata sovrascritta la pagina successiva SM_PAGE7

		    //		    errors[0][cnt_err]   = 0xFF;
		    //		    errors[1][cnt_err++] = 0xFF;

		    SD_piSetSRAMRWAddress((UINT32) (SM_CALEXP0 * 0x4000));
			
		    for (i = 0;  i < 0x4000;  i++)
		      {
			value  = SD_piReadSRAM();
			    
			if (value != 0)    // error
			  {
			    errors[0][cnt_err] = i;
			    errors[1][cnt_err] = value;
				
			    cnt_err++;
			  }
		      }
		  }

		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		// Enable ETO / DTO / PAGE OVR Interrupt 

		OS_piInterDisable(&intLevel);
		SD_piClearInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);
		SD_piUnMaskInt(SD_WPB_EOT | SD_DATA_TO | SD_EVT_TO);        // DTO & ETO
		OS_piInterEnable(intLevel);
		    
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		break;
	      }
	    case 49:
	      b=1000;
	      TI_piGetTimeInfo_ms(&Time_begin);
	      for(a=0;a<b;a++) {
		TS_TM_All( TM_DEA_ANA_1      ,TM_DEA_ANA_16      ,&Time_diff[0]);
		TS_TM_All( TM_TH_ANA_1       ,TM_TH_ANA_16       ,&Time_diff[1]);
		TS_TM_All( TM_BIL_DIAG_ACQ_1 , TM_BIL_DIAG_ACQ_8 ,&Time_diff[2]);
		TS_TM_All( TM_CC_DIAG_ACQ_1  , TM_CC_DIAG_ACQ_32 ,&Time_diff[3]);
		TS_TM_All( TM_DBL_ACQ_3      , TM_DBL_ACQ_8      ,&Time_diff[4]);
		TS_TM_All( TM_DS_16_ACQ_1    , TM_DS_16_ACQ_2    ,&Time_diff[5]);		
	      }
	      TI_piGetTimeInfo_ms(&Time_end);
	      Time_diff[6]=Time_end - Time_begin;
	      break;

	    case 50:
	      {
                // test abbinato al DSP SW TAM_chk_match : riempio una pagina con una rampa crescente e la successiva con una rampa discendente

		FS_FILE_DESCR     FileInfo;
		int               i;
		SM_ACQMODE        PrevAcqMode;
		
		PrevAcqMode = PM_pi_GetAcqMode();

		FT_piChangeAcqMode(SM_EXP64/*it was SM_EXPERIMENT*/);

                SD_piSetSRAMRWAddress  ((UINT32) (SM_SKETCHBOARD * SM_SRAMPAGESIZE));               // prima pagina riempita con una rampa ascendente (contatore a 16 bit)

		for (i = 0;  i < (SM_SRAMPAGESIZE/2);  i++)
		  {
		    SD_piWriteSRAM ((unsigned char) ((i & 0xFF00) >> 8));    // MOST SIGNIFICANT BYTE of the 16 bit counter
		    SD_piWriteSRAM ((unsigned char) (i & 0xFF));             // LEAST SIGNIFICANT BYTE of the 16 bit counter
		  }

		SD_piSetSRAMRWAddress  ((UINT32) ((SM_SKETCHBOARD + 1) * SM_SRAMPAGESIZE));         // seconda pagina riempita con una rampa discendente (contatore a 16 bit)

		for ((i = (SM_SRAMPAGESIZE/2 - 1));  i >= 0;  i--)
		  {
		    SD_piWriteSRAM ((unsigned char) ((i & 0xFF00) >> 8));    // MOST SIGNIFICANT BYTE of the 16 bit counter
		    SD_piWriteSRAM ((unsigned char) (i & 0xFF));             // LEAST SIGNIFICANT BYTE of the 16 bit counter
		  }

		// riempiamo multipli di 4M byte della MM con queste 2 pagine

		for (i = 0;  i < (CustomPar[0] * 0x100);  i++)
		  {		  
		    if (FS_piGetFileInfo (FS_FILE1,   &FileInfo) != FS_FILEISFULL)
		      {
			if (!(i % 2))
			  FT_piSavePage     (SM_SKETCHBOARD,        (SM_SKETCHBOARD + 1) * SM_SRAMPAGESIZE - 1,  FS_FILE1);	      // force storage to FS_FILE1
			else
			  FT_piSavePage     ((SM_SKETCHBOARD + 1),  (SM_SKETCHBOARD + 2) * SM_SRAMPAGESIZE - 1,  FS_FILE1);
		      }

		  }

		FT_piChangeAcqMode(PrevAcqMode);
	      }
	      break;

	    case 51:
	      {
		// TEST RUSSI #1
		//                 1) PREPARO IL GB IN MM
		//                 2) DOWNLOAD DEL GB VERSO IL VRL
		//                    A) SWITCH ON DEL VRL   (HL_CMD_1)
		//                    B) WAIT 6 SEC
		//                    C) START DEL VRL       (HL_CMD_2)
		//                    D) DOWNLOAD GB
		//                    E) SWITCH OFF DEL VRL  (HL_CMD_3)
		rtems_event_set   unused;
		unsigned int code;
		unsigned char     pattern [128] = { 0x00, 0x00, 0x00, 0x00,
					  	    0x00, 0x00, 0x00, 0x00,
						    0x00, 0x00, 0x00, 0x00,
						    0x00, 0x00, 0x00, 0x00,
						    0xFF, 0xFF, 0xFF, 0xFF,
						    0xFF, 0xFF, 0xFF, 0xFF,
						    0xFF, 0xFF, 0xFF, 0xFF,
						    0xFF, 0xFF, 0xFF, 0xFF,
						    0xAA, 0x55, 0xAA, 0x55,
						    0xAA, 0x55, 0xAA, 0x55,
						    0xAA, 0x55, 0xAA, 0x55,
						    0xAA, 0x55, 0xAA, 0x55,
						    0x55, 0xAA, 0x55, 0xAA,
						    0x55, 0xAA, 0x55, 0xAA,
						    0x55, 0xAA, 0x55, 0xAA,
						    0x55, 0xAA, 0x55, 0xAA, 
						    0x55, 0xAA, 0x55, 0xAA,
						    0x55, 0xAA, 0x55, 0xAA,
						    0x55, 0xAA, 0x55, 0xAA,
						    0x55, 0xAA, 0x55, 0xAA, 
						    0xAA, 0x55, 0xAA, 0x55,
						    0xAA, 0x55, 0xAA, 0x55,
						    0xAA, 0x55, 0xAA, 0x55,
						    0xAA, 0x55, 0xAA, 0x55,
						    0xFF, 0xFF, 0xFF, 0xFF,
						    0xFF, 0xFF, 0xFF, 0xFF,
						    0xFF, 0xFF, 0xFF, 0xFF,
						    0xFF, 0xFF, 0xFF, 0xFF,
						    0x00, 0x00, 0x00, 0x00,
						    0x00, 0x00, 0x00, 0x00,
						    0x00, 0x00, 0x00, 0x00,
						    0x00, 0x00, 0x00, 0x00
		                                  };
		unsigned int     i,
		                 j;
		FS_FILE_DESCR    FileInfo;
		SM_ACQMODE       PrevAcqMode;
		unsigned short   nSects;
		unsigned short   mcmd [] =        { 0x0001,
						    0x0082,
						    0x000A,    
						    0x0000,
						    0x0000,
						    0x3E8A,
						    0x0000,
						    0x0000
		                                  };
		rtems_status_code    status;
		static  MsgTsk               sndMsg;
		static  MA_HEADER_MCMD       mcmdHeader;

		// -----------------------------------------------------------------------------------------------------------------------------------------------

		nSects = CustomPar[0];

		if (nSects < FT_MINDLSECTORS)
		  nSects = FT_MINDLSECTORS;

		// -----------------------------------------------------------------------------------------------------------------------------------------------
		
		FT_opChangeOpMode (MC_MAINTENANCE_STATE);
		FT_opChangeOpMode (MC_ACTIVE_STATE);

		PrevAcqMode = PM_pi_GetAcqMode();
			
		FT_piChangeAcqMode(SM_EXP64/*it was SM_EXPERIMENT*/);
		
		switch (CustomPar[1])       // scelta del pattern di riempimento della PIF SRAM
		  {
		    case   0 :
		      // -----------------------------------------------------------------------------------------------------------------------------------------------
		      // test preliminare con riempimento dei 256k della PIF SRAM con un contatore ad 8 bit 
		
		      SD_piSetSRAMRWAddress  ((UINT32) (SM_CALPAGE * SM_SRAMPAGESIZE));
		
		      for (j = 0;  j < 1024;  j++)                              // 256 k = 256 * 1024 (256 = lunghezza del pattern)
			for (i = 0;  i < 256;  i++)
			  SD_piWriteSRAM ((unsigned char) (i & 0xFF));
		      break;

		    case   1 :
		      // -----------------------------------------------------------------------------------------------------------------------------------------------
		      // test preliminare con riempimento dei 256k della PIF SRAM con un contatore a 16 bit 
		
		      SD_piSetSRAMRWAddress  ((UINT32) (SM_CALPAGE * SM_SRAMPAGESIZE));
		
		      for (j = 0;  j < 1024;  j++)                              // 256 k = 256 * 1024 (256 = lunghezza del pattern)
			for (i = 0;  i < 128;  i++)
			  {
			    SD_piWriteSRAM ((unsigned char) (((j * i) & 0xFF00) >> 8));    // MOST SIGNIFICANT BYTE of the 16 bit counter
			    SD_piWriteSRAM ((unsigned char) ((j * i) & 0xFF));             // LEAST SIGNIFICANT BYTE of the 16 bit counter
			  }
		      break;
		
		    case   2 :
		      // -----------------------------------------------------------------------------------------------------------------------------------------------
		      // riempimento di una pagina della PIF con un PATTERN DI TEST (riempiamo tutta la SRAM della PIF : 256 k)

		      SD_piSetSRAMRWAddress  ((UINT32) (SM_CALPAGE * SM_SRAMPAGESIZE));
		
		      //	for (j = 0;  j < 64;  j++)
		      for (j = 0;  j < 1024;  j++)                              // 256 k = 256 * 1024 (256 = lunghezza del pattern) 
			{
			  for (i = 0;  i < 64;  i++)
			    SD_piWriteSRAM (pattern [i]);
		    
			  for (i = 0;  i < 128;  i++)
			    SD_piWriteSRAM ((unsigned char) (i & 0xFF)); 
		    
			  for (i = 64;  i < 128;  i++)
			    SD_piWriteSRAM (pattern [i]);
			}
		      break;
		  }	
		
		// -----------------------------------------------------------------------------------------------------------------------------------------------
		// riempio 1 GB di MM con i pattern contenuti nella PIF SRAM

		//		for (i = 0;  i < (64 * nSects);  i++)
		for (i = 0;  i < (4 * nSects);  i++)                    // 1 M = 4 * 256 k
		  {
		    FT_piSavePage     (SM_CALPAGE,   256 * 1024 - 1,   FS_FILE1);	  // scrive 256 k nel file di HOUSEKEEPING

		    while (FT_opSaveInProgress ())
		      OS_piTaskSuspend (1);
		  }

		// -----------------------------------------------------------------------------------------------------------------------------------------------
		// SET START to 0 : START HLC 4
		
		HK_SendTC      (TM_HL_CMD_4, 0x1);
		OS_piTaskSuspend (110);

		// -----------------------------------------------------------------------------------------------------------------------------------------------
		// SWITCH ON VRL : START HLC 2 + WAIT FOR 6 sec
		
		HK_SendTC      (TM_HL_CMD_2, 0x1);
		OS_piTaskSuspend (6000);

		// -----------------------------------------------------------------------------------------------------------------------------------------------
		// SET START to 1     : START HLC 3
		
		HK_SendTC      (TM_HL_CMD_3, 0x1);

		// -----------------------------------------------------------------------------------------------------------------------------------------------
		// wait some msecs before sending MCMD

		if (CustomPar[3])
		  OS_piTaskSuspend   (CustomPar[3]);		  
		
		// -----------------------------------------------------------------------------------------------------------------------------------------------
		// send DOWNLINK MCMD

		mcmd [5] = (nSects << 4) | 0x000A;

		MC_piSetState (MC_ACTIVE_STATE);

		sndMsg.Code        = MD_MCMD_EXEC;

		mcmdHeader.Type    = DOWN_LINK;
		mcmdHeader.TimeTag = 0x0000;
		mcmdHeader.PtrMCMD = (void *) mcmd;
		mcmdHeader.Length  = 0x000A;

		memcpy((void *) sndMsg.Info, (void *) &mcmdHeader, 16); 
	
		sndMsg.LlInfo      = 16;

		OS_piEventClear          (OS_EVENT_END_OF_DOWNLINK);
		FT_opSetTask2Notify_EOD  (TS_INFN_TASK);
		//HK_SendTC              (TM_DBL_CMD, 0x0);

		//while (1)
		//  {
		status = MD_piSndMsgMCMDDispatcher (&sndMsg);

		// per effettuare il download di 4 settori da 1015x1024 byte, ci vogliono circa 4 secondi

		code = OS_piEventReceive (OS_EVENT_END_OF_DOWNLINK,WAIT, CustomPar[2], &unused);

		// -----------------------------------------------------------------------------------------------------------------------------------------------
		// SET START to 0       : START HLC 4

		HK_SendTC        (TM_HL_CMD_4, 0x1);
		OS_piTaskSuspend   (110);
 
		// -----------------------------------------------------------------------------------------------------------------------------------------------
		// SWITCH OFF VRL : START HLC 1

		HK_SendTC        (TM_HL_CMD_1, 0x1);
		//  }
		// -----------------------------------------------------------------------------------------------------------------------------------------------
		
		FT_piChangeAcqMode (PrevAcqMode);
		//free               (RAMStartAddr);
	      }
	      break;


	    case 60: 
	      {
		unsigned int value_pir    = 0x0;
		unsigned int cnt          = 0;
		unsigned int ovr_detached = FALSE;
		unsigned int eto = 0xfffff;
		unsigned short *us;
#define MAX_LEN_BUF 3000
		static int LEN_BUF[MAX_LEN_BUF];
		unsigned int N_LEN_BUF,gen_init;
		int com,success=0,unsuccess=0,very_success=0,nexit,susp,expected_len,mode;
		status_code  s;
		SM_STRSTAT stat;
		DAQ_CMD_BUF *sub;

		/* fill the body of the command data			*/
		a=1;
		b=idaqbuf.len;
		c=100000;
		d=7000;
		g=1;
		amode=SM_DIRECT;
		susp= 50;

		SD_piSetEventTimeout(eto);
		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);

		PM_opSetNotifyTask_PKT_READY(TS_INFN_TASK);
		com=13;
		nexit=100;
		expected_len=16732;
		N_LEN_BUF=0;
		gen_init=1;
		mode=1;
		while(nexit--) {
		  OS_piTaskSuspend(susp);
		  DAQ_Format_CMD_Empty(&idaqbuf);
		  switch(com) {
		  case 1:
		    /* scrivi ram, leggi ram */
		    s = DAQ_Format_CMD_Fill(&data,300,0xbb);
		    s = DAQ_Format_CMD_Fill(&data2,3,0xcc);
		    
		    s = DAQ_Format_Cmd2Ram_SetAddress(&idaqbuf,0);
		    s = DAQ_Format_Cmd2Ram_WriteData(&idaqbuf,&data2);
		    s = DAQ_Format_Cmd2Ram_EndBlock(&idaqbuf);
		    s = DAQ_Format_Ram2Daq(&idaqbuf,&ram_readdata);
		    break;
		  case 2:
		    s = DAQ_Format_CMD_Fill(&data,300,0xEE);
		    s = DAQ_Format_Cmd2Fe(&idaqbuf,&data,DAQ_FE_TRK_1);
		    s = DAQ_Format_CMD_Fill(&data,500,0x15);
		    s = DAQ_Format_Cmd2Fe(&idaqbuf,&data,DAQ_FE_CAL_1);
		    s = DAQ_Format_ReleaseBusy(&idaqbuf);
		    break;
		  case 3:
		    s = DAQ_Format_ReleaseBusy(&idaqbuf);
		    break;
		  case 4:
		    // CH_GetBuf(CH_SUBLIMINALE,&sub);
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		    break;
		  case 5:

		    switch(gen_init) {
		    case 1: 
		      // CH_GetBuf(CH_default_assembled_0,&sub);
		      break;
		    case 2:
		      // CH_GetBuf(CH_default_assembled_0bis,&sub);
		      break;
		    case 3:
		      // CH_GetBuf(CH_default_assembled_1,&sub);
		      break;
		    case 4:
		      // CH_GetBuf(CH_default_assembled_2,&sub);
		      break;
		    case 5:
		      // CH_GetBuf(CH_default_assembled_2_0,&sub);
		      break;
		    case 6:
		      // CH_GetBuf(CH_default_assembled_2bis,&sub);
		      break;
		    case 7:
		      // CH_GetBuf(CH_default_assembled_3,&sub);
		      break;
		    case 8:
		      // CH_GetBuf(CH_default_assembled_4,&sub);
		      break;
		    case 9:
		      // CH_GetBuf(CH_default_assembled_4_0,&sub);
		      break;
		    case 10:
		      // CH_GetBuf(CH_default_assembled_4_bis,&sub);
		      break;
		    case 11:
		      // CH_GetBuf(CH_default_assembled_5,&sub);
		      break;
		    case 12:
		      // CH_GetBuf(CH_default_assembled_5_0,&sub);
		      break;
		    case 13:
		      // CH_GetBuf(CH_default_assembled_5_bis,&sub);
		      break;
		    case 14:
		      // CH_GetBuf(CH_default_assembled_6,&sub);
		      break;
		    default:
		      s=0xFFF;
		      break;
		    }
		    
		    gen_init++; 
		    
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		    break;
		  case 6:
		    // CH_GetBuf(CH_TRACKER_DUMMY_WITH_TRIGGER,&sub);
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		    break;
		  case 7:
		    // CH_GetBuf(CH_elena_load_program_dsp0link1,&sub);
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		    break;
		  case 8:
		    // CH_GetBuf(CH_elena_start_acq_full,&sub);
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		  case 9:
		    // CH_GetBuf(CH_elena_read_buffer,&sub);
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		    break;
		  case 10:
		    // CH_GetBuf(CH_flash_non_funziona,&sub);
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		    break;
		  case 11:
		    // CH_GetBuf(CH_ram_funziona,&sub);
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		    break;
		  case 12:
		    CH_GetBuf(CH_assembled_subliminale_scrittura,&sub);
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		    break;
		  case 13:
		    CH_GetBuf(CH_assembled_subliminale_lettura,&sub);		    
		    s = DAQ_Format_AppendBuffer(&idaqbuf,sub);
		    break;

		  }
		  if(s != SUCCESSFUL) {
		    LU_INFN_LOG(LU_WARNING,0xffffffff,__FILEID__,__LINE__,s);
		    continue;
		  }
		  

		  oldmode=PM_pi_GetAcqMode();

		  if(mode=1) {

		    PM_pi_SetAcqMode(amode);
		    PM_pi_SetExpPktCpyFlag(a);
		    PM_pi_UseCalibrationPage(SM_CALEXP0);
		    stat=PM_pi_CopyToSRAM(SM_CALEXP0 , idaqbuf.buf , idaqbuf.len);
		    if(stat != SM_STR_OK)
		      continue;

		    switch(a) {
		    case 1:
		      PM_opPreparePage(TRUE);
		      break;
		    case 2:
		      ERC32_Force_interrupt(ERC32_INTERRUPT_EXTERNAL_5);
		      break;
		    }
		    e=OS_piEventReceive(OS_EVENT_PKT_READY,RTEMS_WAIT,d,&evout);
		    if(e == SUCCESSFUL) {
		      PM_pi_GetPacket(&dest.len,dest.buf);
		      success++;
		      LEN_BUF[N_LEN_BUF]=dest.len;
		      if(dest.len == expected_len && dest.buf[3] == 1 && dest.buf[5] == 2 && dest.buf[7]== 3)
			very_success++;
		    }else{
		      LEN_BUF[N_LEN_BUF]=-1;
		      unsuccess++;
		    }
		  }else {
		    s=DAQ_StoreCmdQueue2PIF(SM_CALEXP0,&idaqbuf);
		    s=DAQ_SendCmd2PIFWaitDAQReply(SM_CALEXP0,FALSE,&dest,TRUE);
		  }
		  PM_pi_SetAcqMode(oldmode);

		  if(N_LEN_BUF >= MAX_LEN_BUF)
		    N_LEN_BUF=0;
		  else
		    N_LEN_BUF++;
		}
		susp+=100;
	      }

	      break;
	    case 61:
	      {
		unsigned int value_pir    = 0x0;
		unsigned int cnt          = 0,com;
		unsigned int ovr_detached = FALSE;

		/* fill the body of the command data			*/


		s |=   DAQ_Format_CMD_Fill(&data,300,0xbb);
		s |=   DAQ_Format_CMD_Fill(&data2,3,0xcc);
		
		s |=   DAQ_Format_Cmd2Ram_SetAddress(&idaqbuf,0);
		s |=   DAQ_Format_Cmd2Ram_WriteData(&idaqbuf,&data2);
		s |=   DAQ_Format_Cmd2Ram_EndBlock(&idaqbuf);
		s |=   DAQ_Format_Ram2Daq(&idaqbuf,&ram_readdata);

		a=1;
		b=idaqbuf.len;
		c=100000;
		d=7000;
		
		
		OS_piInterDisable(&intLevel);
		SD_piClearInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);		
		SD_piMaskInt(SD_DATA_TO | SD_PAGE_OVR | SD_EVT_TO);		
		OS_piInterEnable(intLevel);
		while(1) {
		  oldmode=PM_pi_GetAcqMode();
		  PM_pi_SetAcqMode(SM_DAQSETUP);
		  PM_pi_SetExpPktCpyFlag(a);
		  PM_pi_UseCalibrationPage(SM_CALEXP0);
		  PM_pi_CopyToSRAM(SM_CALEXP0 , idaqbuf.buf , idaqbuf.len);
		  // ERC32_Force_interrupt(ERC32_INTERRUPT_EXTERNAL_5);
		  PM_opPreparePage(TRUE);
		  value_pir    = 0x0;
		  cnt          = 0;
		  ovr_detached = FALSE;
		  
		  while (!(value_pir & 0x01) && (cnt < c))
		    {
		      value_pir = (unsigned int) (*(unsigned char *) 0x98000394);
		      
		      if (value_pir & 0x10)               // OVR
			ovr_detached = TRUE;
		      
		      cnt++;
		    }
		  if(cnt < c) {
		    PM_opSetNotifyTask_PKT_READY(TS_INFN_TASK);
		    PM_opPageHasData();
		    e=OS_piEventReceive(1,RTEMS_WAIT,d,&evout);
		    PM_pi_GetPacket(&dest.len ,dest.buf);
		  }
		  PM_pi_SetAcqMode(oldmode);
		  

		}
	      }
	      break;
	      // TEST PAMELA SOFTWARE dal 62 al .....
	    case 62:
	      // Test HB function
	      {
		s = DAQ_Format_CMD_Fill(&data,1024,0xa5);
		//s = HB_Store(HB_LOG,1024,data.buf,0);
		HB_WriteToPIF();
	      }
	      break;
	    case 63:
	      // fill MM
	      {

		int i,nt,ns,to;
		int cicli=4000;
		int c=1;
		int s=0,t;
		unsigned int pattern=0xF1CAF0CA;
		SM_STRSTAT stat;
		rtems_event_set out;
		SM_ACQMODE m = SM_DAQSETUP;
		
		DAQ_BUFFER_INIT(databuffer);
		MC_piSetState(MC_ACTIVE_STATE);
		FT_piChangeAcqMode(m);
		PM_opSetNotifyTask_SKETCHBOARD_FREE(TS_INFN_TASK);
		t=2;
		switch(t) {
		case 0:
		  for(i=0;i<TEST_DATALEN;i++)
		    databuffer.buf[i]= TEST_DATALEN-i;
		  databuffer.len=1024*20;
		  break;
		case 1:
		  for(i=0;i<TEST_DATALEN/4;i++)
		    ((unsigned int*)databuffer.buf) [i]= pattern;
		  databuffer.len=1024*20;
		  break;
		case 2:
		  for(i=0;i<TEST_DATALEN;i++)
		    databuffer.buf[i]= i;
		  databuffer.len=1024*20;
		  break;
		}
		if(c) {
		  ns=0;
		  nt=0;
		  to=2000;
		  for(i=0;i<cicli;i++) {
			OS_piTaskSuspend(s);
		        s=OS_piEventReceive(OS_EVENT_SKETCHBOARD_FREE,RTEMS_WAIT,to,&out);

			if(s!=SUCCESSFUL)
			  ns++;
			
			stat = PM_pi_StorePacket(databuffer.len,i<2 ? databuffer.buf : NULL,FS_HK);
			if(stat != SM_STR_OK)
			  nt++;
		  }

		}else {
		  for(i=0;i<cicli;i++) 
		    status = DAQ_SaveBuffer2MM(&databuffer,FS_HK,1000);
		  

		}
		
	      }
	      break;
	    case 64:
	      {
		int i=0;
		int w=30000;
		SM_ACQMODE m = SM_DAQSETUP;
		MC_piSetState(MC_ACTIVE_STATE);
		FT_piChangeAcqMode(m);
		PM_opSetNotifyTask_SKETCHBOARD_FREE(TS_INFN_TASK);
		while(i<1000) {
		  OS_piTaskSuspend(w);
		  HB_WriteToPIF();
		  i++;
		}
	      }
	      break;
	  case 65:
	      /* invia un macrocomando simulato di test_debug */
	      {
#ifdef SIMULATOR
		unsigned short code = 0;
		PM_SIM_send_testdebug(code);
#endif
	      }
	      break;
	  case 99:
	    TS_FULL_CPU_TESTS();
	    break;
	      //TEST FUNZIONALI
	  case 100:
	      // fill MM pattern crescente utilizzando DAQ_SaveBuffer2MM
	      {
		DAQ_BUFFER_INIT(databuffer);
	      }
	      break;
	    case 101:
	      // fill MM pattern crescente utilizzando direttamente StorePacket
	      {
		DAQ_BUFFER_INIT(databuffer);
	      }
	      break;
	    case 102:
	      // flush di HB buffer su MM
	      {
		
	      }
	      break;

	    case 103:
	      // IDAQ Scrittura-Lettura (subliminale)
	      {
		static unsigned int eto = 0xfffff;
		DAQ_CMD_BUF *sub;
		SM_STRSTAT stat;
		static unsigned int timeout=5000;
	
		static SM_ACQMODE acqmode =SM_DAQSETUP;
		
		// KHB_TestBoard(3); // Reset all FE
		
		SD_piSetEventTimeout(eto);
		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);

		PM_opSetNotifyTask_PKT_READY(TS_INFN_TASK);
		switch(bufsel) {
		case 1:
		  CH_GetBuf(CH_assembled_RAM_RW,&sub);
		  break;
		case 2:
		  //CH_GetBuf(CH_assembled_RAM_solo_scrittura,&sub);		  
		  break;
		case 3:
		  CH_GetBuf(CH_assembled_subliminale_lettura,&sub);		  
		  break;
		case 4:
		  CH_GetBuf(CH_assembled_SOLO_RAM,&sub);		  
		  break;
		case 11:
		  //		  CH_GetBuf(CH_calo_techno_all_as,&sub);
		  break;
		case 12:
		  CH_GetBuf(CH_calo_techno_fer_as,&sub);
		  break;
		case 13:
		  CH_GetBuf(CH_calo_techno_dsp_as,&sub);
		  break;
		case 14:
		  CH_GetBuf(CH_calo_techno_on_as,&sub);
		  break;
		case 15:
		  CH_GetBuf(CH_calo_techno_all_only_10_as,&sub);
		  break;

		case 16:
		  //		  CH_GetBuf(CH_int_vec_crc_as,&sub);
		  break;
		case 17:
		  CH_GetBuf(CH_rampa_crc_as,&sub);
		  break;
		case 18:
		  CH_GetBuf(CH_res_vec_crc_as,&sub);
		  break;
		case 19:
		  CH_GetBuf(CH_rileggi_crc_as,&sub);
		  break;
		  
		  /*
		    case X:
		    // il primo argomento e' CH_ + "il nome del file punto dat senza estensione nella dir INFN/commands
		    CH_GetBuf(CH_nomefiledat,&sub);
		    break;
		  */
		default:
		  CH_GetBuf(CH_assembled_SOLO_RAM,&sub);
		  break;
		}
		//acqmode = SM_DIRECT;

		PM_pi_SetAcqMode(acqmode);
		
		OS_piEventReceive(OS_EVENT_PKT_READY,RTEMS_NO_WAIT,0,&evout);
		OS_piEventReceive(OS_EVENT_ETO      ,RTEMS_NO_WAIT,0,&evout);

		PM_pi_SetExpPktCpyFlag(1); // copy in ram ogni volta
		PM_pi_UseCalibrationPage(SM_CALEXP0);
		stat=PM_pi_CopyToSRAM(SM_CALEXP0 , sub->buf , sub->len);
		if(stat != SM_STR_OK)
		  {
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,stat);
		  }
		
		OS_piInterDisable(&intLevel);
		PM_opPreparePage(TRUE);
		OS_piInterEnable(intLevel);
		
		e=OS_piEventReceive(OS_EVENT_PKT_READY | OS_EVENT_ETO ,RTEMS_WAIT|RTEMS_EVENT_ANY,timeout,&evout);
		if(e == SUCCESSFUL) {
		  if(evout & OS_EVENT_PKT_READY)
		    PM_pi_GetPacket(&dest.len,dest.buf);
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,dest.len);
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,evout);
		}else{
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,e);
		}
	      }
	      break;
	      
	    case 104:
	      // check IDAQ BUS: write and read a buffer on IDAQ MEMORY
	      {
		static unsigned int eto = 0xfffff;
		static unsigned int reset_flag=0;
		static unsigned int ramcopyfreq = 1000;
		DAQ_CMD_BUF *sub;
		SM_STRSTAT stat;
		BOOL answer = TRUE;
		BOOL error;
		UINT32 i,j,k,prec,last_error;
		static unsigned int timeout=5000;
		static BYTE pattern[4] = {0xAA,0x55,0xAA,0x55};
		BYTE byte;
		BYTE *pbyte;
		static SM_ACQMODE acqmode =SM_DAQSETUP;
		static UINT32 counter=0;
		DAQ_BUFFER_INIT(idaqcmd);

		/*
		if(reset_flag)
		  KHB_TestBoard(3); // Reset all FE
		*/
		MC_piSetState(MC_ACTIVE_STATE);
		SD_piSetEventTimeout(eto);
		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);
		PM_pi_SetPktType(HB_PKTTYPE_FORCED_FECMD);
		PM_pi_SetNotifyTask_PKT_READY(TS_INFN_TASK);

		if(PRH_VAR_TS_104pifwrite>0) {
		  SD_piSetSRAMRWAddress(0);
		  for(i=0;i<PRH_VAR_TS_104pifwrite;i++)
		    SD_piWriteSRAM(0x00);
		}
		
		switch(bufsel) {
		case 1:
		  CH_GetBuf(CH_assembled_RAM_RW,&sub);
		  break;
		case 2:
		  //CH_GetBuf(CH_assembled_RAM_solo_scrittura,&sub);		  
		  answer=FALSE;
		  break;
		case 3:
		  CH_GetBuf(CH_assembled_subliminale_lettura,&sub);		  
		  break;
		case 4:
		  CH_GetBuf(CH_assembled_SOLO_RAM,&sub);		  
		  break;
		case 5:
		  CH_GetBuf(CH_buf_make_acq_full,&sub); // scriveva subliminale
		  break;  
		case 6:
		  CH_GetBuf(CH_buf_make_acq,&sub);      //legge
		  break;
		case 7:
		  CH_GetBuf(CH_buf_init_run,&sub);      //scrive?
		  break;
		case 11:
		  //		  CH_GetBuf(CH_calo_techno_all_as,&sub);
		  break;
		case 12:
		  CH_GetBuf(CH_calo_techno_fer_as,&sub);
		  break;
		case 13:
		  CH_GetBuf(CH_calo_techno_dsp_as,&sub);
		  break;
		case 14:
		  CH_GetBuf(CH_calo_techno_on_as,&sub);
		  break;
		case 15:
		  CH_GetBuf(CH_calo_techno_all_only_10_as,&sub);
		  break;
		case 16:
		  //		  CH_GetBuf(CH_int_vec_crc_as,&sub);
		  break;
		case 17:
		  CH_GetBuf(CH_rampa_crc_as,&sub);
		  break;
		case 18:
		  CH_GetBuf(CH_res_vec_crc_as,&sub);
		  break;
		case 19:
		  CH_GetBuf(CH_rileggi_crc_as,&sub);
		  break;
		case 20:
		  sub=&idaqcmd;
		  TS_GetCustomWriteRam(sub,PRH_VAR_TS_writeaddr_104,
				       PRH_VAR_TS_kilo_104*1024/4,
				       pattern[0],pattern[1],pattern[2],pattern[3]);
		  answer=FALSE;
		  break;
		case 21:
		  sub=&idaqcmd;
		  TS_GetCustomReadRam(sub,PRH_VAR_TS_readaddr_104);
		  break;
		case 22:
		  sub=&idaqcmd;
		  s=0;
		  s|=DAQ_Format_CMD_Empty(sub);
		  s|=DAQ_Format_Cmd2Ram_SetAddress(sub,PRH_VAR_TS_writeaddr_104);
		  s|=TS_GetCustomReadWriteRamBig(sub,PRH_VAR_TS_writeaddr_104,
						 PRH_VAR_TS_kilo_104*1024,&counter);
		  PRH_VAR_TS_writeaddr_104+=PRH_VAR_TS_kilo_104*1024;
		  answer=FALSE;
		  break;
		case 23:
		  /* End Block */
		  sub=&idaqcmd;
		  s=0;
		  s|=DAQ_Format_CMD_Empty(sub);
		  s|=DAQ_Format_Cmd2Ram_EndBlock(sub);
		  answer=FALSE;
		  break;
		case 24:
		  /* SetAddress(0) + Ram2Daq/ReadData * TS_len */
		  sub=&idaqcmd;
		  s=0;
		  s|=DAQ_Format_CMD_Empty(sub);
		  s|=DAQ_Format_Cmd2Ram_SetAddress(sub,0);
		  for(i=0;i<PRH_VAR_TS_104rate_n && s==0 ;i++) {
		    s|=DAQ_Format_Ram2Daq_ReadData(sub);
		  }
		  if(s)
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
		  break;
		case 25:
		  /* SetAddress(0) + (WriteData(count) + EndBlock) * TS_len */
		  sub=&idaqcmd;
		  s=0;
		  s|=DAQ_Format_CMD_Empty(sub);
		  s|=DAQ_Format_Cmd2Ram_SetAddress(sub,0); 
		  for(i=0;i<PRH_VAR_TS_104rate_n && s==0;i++) {
		    s|=DAQ_Format_OneByteCmd(&data,(BYTE)i);
		    s|=DAQ_Format_Cmd2Ram_WriteData(sub,&data);
		    s|=DAQ_Format_Cmd2Ram_EndBlock(sub);
		  }
		  if(s)
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
		  answer=FALSE;
		  break;
		case 26:
		  /* Read Data */
		  sub=&idaqcmd;
		  s=0;
		  s|=DAQ_Format_CMD_Empty(sub);
		  s|=DAQ_Format_Ram2Daq_ReadData(sub);

		  if(s)
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
		  break;
		case 27:
		  /* Set Address 0 */
		  sub=&idaqcmd;
		  s=0;
		  s|=DAQ_Format_CMD_Empty(sub);
		  s|=DAQ_Format_Cmd2Ram_SetAddress(sub,0);
		  if(s)
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
		  answer=FALSE;
		  break;
		case 28:
		  /* SetAddress(0) + (WriteData(count) + EndBlock) * TS_len */
		  sub=&idaqcmd;
		  s=0;
		  s|=DAQ_Format_CMD_Empty(sub);
		  s|=DAQ_Format_Cmd2Ram_SetAddress(sub,0); 
		  j=0;
		  data.len=2;
		  for(i=0;i<PRH_VAR_TS_104rate_n && s==0;i++) {
		    data.buf[0]=(BYTE)j;
		    j++;
		    data.buf[1]=(BYTE)j;
		    j++;
		    s|=DAQ_Format_Cmd2Ram_WriteData(sub,&data);
		    s|=DAQ_Format_Cmd2Ram_EndBlock(sub);
		  }
		  if(s)
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,s);
		  answer=FALSE;
		  break;
		case 100:
		  CH_GetBuf(CH_idaq_lettura_ram_0,&sub);
		  break;
		case 101:
		  CH_GetBuf(CH_idaq_scrittura_a5a5,&sub);
		  answer=FALSE;
		  break;
		case 102:
		  //CH_GetBuf(CH_idaq_scrittura_rampa_10K,&sub);
		  answer=FALSE;
		  break;
		case 103:
		  CH_GetBuf(CH_idaq_scrittura_text_lettura_0,&sub);
		  break;
		case 104:
		  //CH_GetBuf(CH_long_ramp_write_read,&sub);
		  break;
		default:
		  CH_GetBuf(CH_assembled_SOLO_RAM,&sub);
		  break;
		}

		// acqmode = SM_DIRECT;
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,bufsel);
		
		PM_pi_SetAcqMode(acqmode);

		OS_piEventReceive(OS_EVENT_PKT_READY,RTEMS_NO_WAIT,0,&evout);
		OS_piEventReceive(OS_EVENT_ETO      ,RTEMS_NO_WAIT,0,&evout);

		PM_pi_SetExpPktCpyFlag(PRH_VAR_TS_104ramcopyfreq); // copy in ram ogni volta
		PM_pi_UseCalibrationPage(SM_CALEXP0);
		stat=PM_pi_CopyToSRAM(SM_CALEXP0 , sub->buf , sub->len);
		if(stat != SM_STR_OK)
		  {
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,stat);
		  }
		
		if(answer) {
		  OS_piInterDisable(&intLevel);
		  PM_opPreparePage(TRUE);
		  OS_piInterEnable(intLevel);

		  e=OS_piEventReceive(OS_EVENT_PKT_READY | OS_EVENT_ETO ,RTEMS_WAIT|RTEMS_EVENT_ANY,timeout,&evout);
		}else{
		  e=DAQ_SendCmdQueue2CMDIF(SM_CALEXP0);
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,e);
		}

		if(e == SUCCESSFUL && answer) {
		  if(evout & OS_EVENT_PKT_READY)
		    { 
		      PM_pi_GetPacket(&dest.len,dest.buf);
		      switch(checkdata) {
		      case 1:
			if(dest.len != aspettata_len)
			  {
			    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,dest.len);
			    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,sub->len);			  
			  }
			else
			  { //else same len check data
			    int cic;
			    for(cic=0;cic<aspettata_len;cic++){
			      if(cic%2)
				if(aspettatopari!=dest.buf[cic])
				  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,cic);
				else
				  if(aspettatodisp!=dest.buf[cic])
				    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,cic);
			    }
			  }
			break;
		      case 2:
			if(dest.len != aspettata_len)
			  {
			    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,dest.len);
			    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,sub->len);			  
			  }
			else
			  { //else same len check data

			  }
		      case 3:
			pkt_counter++;
			if(acqmode == SM_DIRECT)
			  prec=0;
			else
			  prec=SM_PKTHEADER_LEN;

			last_error=0;
			for(a=prec+1;a<dest.len;a++,prec++) {
			  if(dest.buf[prec] == dest.buf[a]) {
			    pkt_delta_wrong[a-last_error]++;
			    last_error=a;
			  }
			}
			if(last_error!=0)
			  pkt_wrong_counter++;
			break;
		      default:
			break;
		      }
		    }
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,dest.len>>16);
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,dest.len);
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,evout);
		}else{
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,e);
		}
	      }
	      break;

	    case 105:
	      {
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,pkt_counter>>16);
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,pkt_counter);
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,pkt_wrong_counter>>16);
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,pkt_wrong_counter);
		for(a=0;a<K;a++)
		  if(pkt_delta_wrong[a] != 0) {
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,a);
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,pkt_delta_wrong[a]>>16);
		    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,pkt_delta_wrong[a]);
		  }
	      }
	      break;
	    case 106:
	      {
		int i=0;
		int w=30000;
		SM_ACQMODE m = SM_DAQSETUP;
		MC_piSetState(MC_ACTIVE_STATE);
		FT_piChangeAcqMode(m);
		PM_opSetNotifyTask_SKETCHBOARD_FREE(TS_INFN_TASK);
		OS_piTaskSuspend(w);
		HB_WriteToPIF();
		

	      }
	    case 107:
	      { 
		while(1)
		  TS_CRC();
	      }
	      
	      break;


	    case 110:
	      {
		static int test = 1;

		status_code status;
		
		switch (test)
		  {
		  case 1: 
		    {
		      /*
		      status = GS_Request();
		      if (!status) 
			status = GS_FillBuffer(1);
		      if (!status) 
			status = GS_Request();
		      if (!status) 
			status = GS_Purge(1);
		      */
		    }
		    break;
		  case 2 :
		    {
		      int i;

		      for (i=1; i < 4; i++)
			{
			  
			  /* status = GS_Request();
			  if (!status) 
			    status = GS_FillBuffer(i);
			  if (!status) 
			    status = GS_Request();
			    if (!status) 
			    status = GS_Purge(i); */
			}
		    }
		    break;
		  case 3:
		    {
		      status_code status;

		      //status = GS_StandBy(GS_STDBY_ON);

		      //if (!status)
		      //		status = GS_StandBy(GS_STDBY_OFF);
		    }
		  }
	      }
	      break;
	    case 111:
	      while(1)
		TS_BF();
	      break;

	  case 112:
	    {
	      static UINT16 outbuf_T[13];
	      static UINT16 outbuf_B[13];
	      status_code status;
	    
	      status = SNS_ReadTemperature(SNS_ONE,outbuf_T);
	      status = SNS_ReadB(SNS_ONE,outbuf_B);
	    }
	    
	    break;
	  case 113:
	    { /* idaq command status via KHB */
	      static UINT16 combuf[16],outbuf[16];
	      static int timeout=10000;
	      static int volte=1000;
	      status_code status;
	      combuf[0] = (UINT16)PRH_VAR_TS_khb_idaq_cmd;
	      volte=1000;
	      while(volte--){
		status = HK_KHB_Cmd2FE(KHB_IDAQ,1,1,combuf,outbuf,10);
		if(status)
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
		else
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,outbuf[0]);				
	      }	      
	    }
	    break;
	  case 114:
	    HK_KHB_HardReset();
	    break;
#ifdef SIMULATOR
	  case 115:
	    {
	      /*
	      TS_SendSimulatedMCMD(CH_MCMD_rampa1);
	      TS_SendSimulatedMCMD(CH_MCMD_rampa2);
	      TS_SendSimulatedMCMD(CH_MCMD_rampa3);
	      TS_SendSimulatedMCMD(CH_MCMD_rampa4);
	      TS_SendSimulatedMCMD(CH_MCMD_rampa5);
	      TS_SendSimulatedMCMD(CH_MCMD_rampa6);
	      TS_SendSimulatedMCMD(CH_MCMD_rampa7);
	      TS_SendSimulatedMCMD(CH_MCMD_rampa8);
	      TS_SendSimulatedMCMD(CH_MCMD_rampa9);
	      TS_SendSimulatedMCMD(CH_MCMD_rampa10);
	      */
	    }
	    break;
	  case 116:
	    {
	      // TS_SendSimulatedMCMD(CH_MCMD_rampa11);
	    }
	    break;
	  case 117:
	    {
	      // TS_SendSimulatedMCMD(CH_MCMD_rampa12);
	    }
	    break;
#endif

	  case 118:
	    { /* SENSOR command status via KHB */
	      static UINT16 sensor_combuf[16]={0x0000,};
	      static UINT16 outbuf[16];
	      static int timeout=100;
	      static BYTE expected=13;
	      static int volte=1000;
	      volte=1000;
	      while(volte--){
		status = HK_KHB_Cmd2FE(KHB_TRACKER_SENSORS_2,1,expected,sensor_combuf,outbuf,timeout);	      
		if(status)
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
		else
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,outbuf[0]);				
	      }
	    }
	    break;
	  case 119:
	    { /* idaq command status via KHB */
	      static UINT16 sensor_combuf[16]={0x0380,};
	      static BYTE expected=7;		      
	      static UINT16 outbuf[16];
	      static int timeout=100;
	      static int volte=1000;
	      volte=1000;
	      while(volte--){
		status=HK_KHB_Cmd2FE(KHB_TRACKER_SENSORS_2,1,expected,sensor_combuf,outbuf,timeout);
		if(status)
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
		else
		  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,outbuf[0]);				
	      }
	    }
	    break;
	    
	  case 120:
	    { /* idaq command status via KHB */
	      static UINT16 combuf[16],outbuf[16];
	      static int timeout=10000;
	      status_code status;
	      combuf[0] = (UINT16)PRH_VAR_TS_khb_idaq_cmd;
	      status = HK_KHB_Cmd2FE(KHB_IDAQ,1,1,combuf,outbuf,10);
	      if(status)
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
	      else
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,outbuf[0]);				
	    }
	    break;
	    
	  case 121:
	    { /* SENSOR command status via KHB */
	      static UINT16 sensor_combuf[16]={0x0000,};
	      static UINT16 outbuf[16];
	      static int timeout=100;
	      static BYTE expected=13;
	      status = HK_KHB_Cmd2FE(KHB_TRACKER_SENSORS_2,1,expected,sensor_combuf,outbuf,timeout);	      
	      if(status)
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
	      else
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,outbuf[0]);				
	    }
	    break;
	  case 122:
	    { /* idaq command status via KHB */
	      static UINT16 sensor_combuf[16]={0x0380,};
	      static BYTE expected=7;		      
	      static UINT16 outbuf[16];
	      static int timeout=100;
	      status=HK_KHB_Cmd2FE(KHB_TRACKER_SENSORS_2,1,expected,sensor_combuf,outbuf,timeout);
	      if(status)
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
	      else
		LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,outbuf[0]);				
	    }
	    break;
	  case 123: {
	    static int value=0;
	    static int blen=64*1024;
	    static UINT32 pattern=0xAA;
	    PM_pi_SetNotifyTask_SKETCHBOARD_FREE(TS_INFN_TASK);
	    // s=OS_piEventClear(OS_EVENT_SKETCHBOARD_FREE);
	    DAQ_BUFFER_INIT(hbuf);
	    switch(value) {
	    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;
	    }
	    status = DAQ_SaveBuffer2MM(&hbuf,FS_HK,1000);
	    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
	  }
	    break;
	    
	  case 124:
	    QS_piCounterCalibration(100000);
	    break;
	  case 125:
	    QS_piUsageStart();
	    break;
	  case 126:
	    {
	      UINT16 usage;
	      QS_piUsageStop(&usage);
	      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,usage);
	    }
	    break;
	  case 127:
	    {
	      UINT16 usage,i,j;
	      static volatile UINT32 susp=2,n=1000,crc=100,calib=100000;
	      QS_piCounterCalibration(calib);
	      QS_piUsageStart();
	      for(i=0;i<n;i++) {
		OS_piTaskSuspend(susp);
		for(j=0;j<crc;j++)
		  TS_CRC();
	      }
	      QS_piUsageStop(&usage);
	      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,usage);
	    }
	    break;
	  default:
	    break;
	  }
      
      }
    }
#endif // DURTY_MODE
}


void TS_RM_Test(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;

  switch(c1) {
  case 1:
    PM_pi_SetNotifyTask_SKETCHBOARD_FREE(RM_INFN_TASK);
    //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;
    }
    status = DAQ_SaveBuffer2MM(&hbuf,FS_HK,1000);
    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();
    break;
  case 4:
    {
      UINT32 value;
      HK_ReadKHBAlarmRegister(&value);
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,value);
    }
    break;
  case 5:
    {
      UINT16 value;
      HK_ReadKHBStatusRegister(&value);
      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();
    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();
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    break;
  case 12:
    status = PRH_ReadDefaultParam();
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    break;
  case 13:
    status = PRH_WriteCurrentParam();
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    break;
  case 15:
    status=DAQ_ReadStatusWord(&sw);
    if(status)
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    else
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,sw);
    break;
  default:
    break;
  }
  
}



/* this function is executed by PamManager */
void TS_PamManager(unsigned short code,
		   unsigned short value1,
		   unsigned short value2,
		   unsigned short value3,
		   unsigned short value4) {
  UINT32 i;
  static UINT32 blen = 24*1024;
  UINT32 fid,v;
  static UINT32 pattern = 0xCAFECAFE;
  status_code status,s;
  PWR_IPM6 ipm;
  CM_ON_OFF oo;
  GS_REPLY_STRUCT gas_status;
  UINT16 *gas_word=(UINT16*)&gas_status,sw;
  int n;
  int sleep;
  /*@LOG ciao bello */
  // LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,code); /* cicciopasticcio */
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,code); /* frocione */
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,code);
  /*@LOG capperi */
  LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,code);
  switch(code) {
  case 0:
    MH_SetGOM(MH_GOM_FLUSH_HB);
    break;
  case 1:
    MH_SetGOM(MH_GOM_ACQUISITION);
    break;
  case 2:
    MH_SetGOM(MH_GOM_MAINTENANCE);
    break;
#ifdef DURTY_MODE
  case 3:
    TS_SndTestCode_INFN(value1);
    break;
#endif // DURTY_MODE
  case 4:
    PM_pi_EnableStore_In_DataTimeOut();
    break;
  case 5:
    PM_pi_DisableStore_In_DataTimeOut();
    break;
  case 6:
    bufsel=value1;
    break;
  case 7:
    RM_LogStatus();
    break;
  case 8:
    //LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,HB_SpaceLeft());
    break;
  case 9:
    PM_pi_SetNotifyTask_SKETCHBOARD_FREE(TS_INFN_TASK);
    PM_opPageWasSaved(FS_HK);
    break;
  case 10:
    RM_SendHBStoreRequest();
   break;
  case 11:
    PM_EnableStoreTMTC();
    break;
  case 12:
    PM_DisableStoreTMTC();
    break;
  case 13:
    PM_EnableTMTC();
    break;
  case 14:
    PM_DisableTMTC();
    break;
  case 15:
    SD_piPIFReset();
    break;
  case 16:
    KHB_InitBoard();
    break;
  case 17:
    FS_piLogInfo();
    break;
  case 18:
    //KHB_TestBoard(value);
    break;
  case 19:
    {
      unsigned int DataValue;
      int i;
      static int min=0,max=4;
      for(i = min ; i < max; i++){
	HK_GetTMValue (TM_DEA_ANA_1+min, &DataValue); 
	LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,DataValue>>16);
	LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,DataValue);
      }
    }
    break;
  case 20:
    KHB_Log();
    break;
  case 21:
    for(fid=0;fid<LU_FILEID_N;fid++)
      LU_MASK(fid) |= LU_DEBUG_TRACE;
    break;
  case 22:
    for(fid=0;fid<LU_FILEID_N;fid++)
      if(LU_MASK(fid) & LU_DEBUG_TRACE)
	LU_MASK(fid) &= ~LU_DEBUG_TRACE;
    break;
  case 23:
    GS_SendCodeGasManager(GS_TEST,NULL); 
    break;
  case 24:
    GS_SendCodeGasManager(GS_START_UP,NULL); 
    break;
  case 25:
    GS_SendCodeGasManager(GS_FILLINPUT_BUFFER,NULL); 
    break;
  case 29:
    GS_SendCodeGasManager(GS_CONTAINER_PURGE,NULL); 
    break;
  case 30:
    GS_SendCodeGasManager(GS_TRD_PURGE,NULL); 
    break;
  case 31:
    GS_SendCodeGasManager(GS_TECH_PURGE,NULL); 
    break;
  case 32:
    GS_SendCodeGasManager(GS_ABORT_OP,NULL); 
    break;
  case 33:
    GS_GasResume();
    break;
  case 34:
    GS_InitGasBoard();
    break;
  case 41:
    PWR_SwitchOn_IPM(TM_KRB_IPM1);
    break;
  case 42:
    PWR_SwitchOn_IPM(TM_KRB_IPM2);
    break;
  case 43:
    PWR_SwitchOn_IPM(TM_KRB_IPM3);
    break;
  case 44:
    PWR_SwitchOn_IPM(TM_KRB_IPM4);
    break;
  case 45:
    PWR_SwitchOn_IPM(TM_KRB_IPM5);
    break;
  case 46:
    PWR_SwitchOn_IPM(TM_KRB_IPM6);
    break;
  case 47:
    PWR_SwitchOff_IPM(TM_IPM12_OFF);
    break;
  case 48:
    PWR_SwitchOff_IPM(TM_IPM34_OFF);
    break;
  case 49:
    PWR_SwitchOff_IPM(TM_IPM56_OFF);
    break;
  case 60:
    for(ipm=PWR_IPM_1;ipm<=PWR_IPM_6;ipm++) {
      PWR_KRB_IPM(ipm,&oo);
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,oo);
    }
  case 61:
    GS_COMRequest(&gas_status);
    gas_word=(UINT16*)&gas_status;
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,*(gas_word++));
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,*(gas_word++));
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,*(gas_word++));
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,*(gas_word++));
    break;
  case 62:
    GS_HLStandBy(GS_STDBY_ON);
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0);
    break;
  case 63:
    GS_HLStandBy(GS_STDBY_OFF);
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,0);
    break;
  case 64:
    HK_SendTC(TM_GAS_HOT_36V_OFF,1);
    break;
  case 65:
    HK_SendTC(TM_GAS_COLD_36V_OFF,1);
    break;
  case 66:
    HK_SendTC(TM_KHB_PWR_33_HOT_ON,1);
    break;
  case 67:
    HK_SendTC(TM_KHB_PWR_33_COLD_ON,1);
    break;
  case 68:
    HK_SendTC(TM_KHB_PWR_33_OFF,1);
    break;
  case 69:

#define LOG_TM(id,line) do { \
    HK_GetTMValue(id,&v); \
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,line,v); \
} while(0)

    LOG_TM(TM_GAS_HOT_ALARM,__LINE__);
    LOG_TM(TM_GAS_COLD_ALARM,__LINE__);
    LOG_TM(TM_GAS_ENABLED,__LINE__);
    LOG_TM(TM_GAS_LPS1,__LINE__);
    LOG_TM(TM_GAS_LPS2,__LINE__);
    LOG_TM(TM_GAS_LPS3,__LINE__);
    LOG_TM(TM_GAS_LPS4,__LINE__);
    LOG_TM(TM_GAS_LPS5,__LINE__);
    LOG_TM(TM_GAS_LPS6,__LINE__);
    LOG_TM(TM_GAS_HPS1,__LINE__);
    LOG_TM(TM_GAS_HPS2,__LINE__);
    LOG_TM(TM_GAS_TS_OUT_TEMP,__LINE__);
    LOG_TM(TM_GAS_TH,__LINE__);

    break;
  case 80:
    s=PRH_var_write2eeprom(PRH_EEPROM_CURRENT,value1);
    break;
  case 81:
    s=PRH_var_write2eeprom(PRH_EEPROM_CURRENT,value1);
    break;
  case 82:
    s=PRH_var_read_eeprom(PRH_EEPROM_CURRENT,value1);
    break;
  case 83:
    s=PRH_arr_write2eeprom(PRH_EEPROM_CURRENT,value1);
    break;
  case 84:
    s=PRH_arr_read_eeprom(PRH_EEPROM_CURRENT,value1);
    break;
  case 85:
    s=PRH_tab_write2eeprom(PRH_EEPROM_CURRENT,value1);
    break;
  case 86:
    s=PRH_tab_read_eeprom(PRH_EEPROM_CURRENT,value1);
    break;
  case 87:
    HK_KHB_HardReset();
    break;
  case 89:
    MH_SetTestParam(value1,value2,value3);
    MH_SetGOM(MH_GOM_TEST);
    break;
  case 90:
    HK_KHB_HardReset();
    break;
  case 91:
    MH_SetGOM(MH_GOM_INITIALIZATION);
    break;
  case 92:
    MH_SetGOM(MH_GOM_CALIBRATION);
    break;
  case 93:
    MH_SetGOM(MH_GOM_ACQUISITION);
    break;
  case 94:
    FT_piInitFileSystem();
    break;
  case 95:
    status=DAQ_ReadStatusWord(&sw);
    if(status)
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
    else
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,sw);
    break;
  case 96:
    QS_piCounterCalibration(value1);
    break;
  case 97:
    QS_piUsageStart();
    break;
  case 98:
    {
      UINT16 usage;
      QS_piUsageStop(&usage);
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,usage);
    }
    break;
  case 99:
    {
      static UINT16 usage;
      static UINT32 i,j;
      static UINT32 susp=2,n=1000,crc=100;
      n=value1;
      crc=value2;
      QS_piUsageStart();
      for(i=0;i<n;i++) {
	OS_piTaskSuspend(susp);
	for(j=0;j<crc;j++)
	  TS_CRC();
      }
      QS_piUsageStop(&usage);
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,usage);
    }
    break;
  }
}

#ifdef SIMULATOR
  
static status_code TS_SwapSimulatedMCMD(CH_COMMANDS bufid) {
  int i;
  char tmp;
  DAQ_CMD_BUF *b;
  CH_GetBuf(bufid,&b);

}

status_code  TS_SendSimulatedMCMD(CH_COMMANDS bufid) {
  /*
    BI_if1553BLoadMCMD( unsigned int subaddId,
		      unsigned short int* BI_1553MCMDBuffer,
		      unsigned short int* BI_1553MCMDACKWord )
  */
  MA_HEADER_MCMD mcmdHeader;
  UINT16 *BI_1553MCMDBuffer,*w;
  UINT32 nwords16;
  status_code status;
  unsigned int   checksum, i;
  int            mcmdttag_direct;
  MsgTsk         sndMsg;
  BYTE tmp;
  unsigned int   mcmdType,mcmdId; 
  unsigned char* pbyte;

  DAQ_CMD_BUF *b;
  CH_GetBuf(bufid,&b);

  /* use the 'crc16' field as flag to see if the swap has already done.
     swapping is necessary because Little Endian to Big Endian conversion */
  
  if(b->crc16 != 0x1234) 
    for(b->crc16=0x1234,i=0;i<(b->len/2);i++) {
      tmp=b->buf[2*i];
      b->buf[2*i]=b->buf[2*i+1];
      b->buf[2*i+1]=tmp;
    }
  
  BI_1553MCMDBuffer=(UINT16*)b->buf;
  if(b->len & 1) {
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,mcmdType);
    return CM_RC_UNDEFINED;
  }
  nwords16=b->len/2;

  mcmdId = BI_1553MCMDBuffer[1] & 0xFF;
  MA_piGetMCMDType(mcmdId, &mcmdType);
  if( mcmdType == NULL_MCMD ) {
    LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,mcmdType);
    return CM_RC_UNDEFINED;
  }
  
  mcmdHeader.Type = mcmdType;

  // verifies the checksum
  checksum = 0;
  for (i=0, pbyte = (unsigned char*)BI_1553MCMDBuffer; i<2*(nwords16-1); pbyte++, i++) {
    checksum += *pbyte;
  }
  
  if( (checksum & 0xFF) != (BI_1553MCMDBuffer[nwords16-1] & 0xFF) )
    {
      LU_INFN_LOG(LU_DEBUG_TRACE,LU_MASK(__FILEID__),__FILEID__,__LINE__,mcmdType);
      return CM_RC_UNDEFINED;
    }

  if( BI_1553MCMDBuffer[1] & BI_MCMD_TT_MASK )
    {
       mcmdHeader.TimeTag = BI_1553MCMDBuffer[3]<<16 | BI_1553MCMDBuffer[4];
       mcmdttag_direct = TIMETAG_MCMD;
       sndMsg.Code = MT_STORE_TIMETAG_MCMD;
    }
  else
    {
      mcmdHeader.TimeTag = 0;
      mcmdttag_direct = IMMEDIATE_MCMD;
      sndMsg.Code = MD_MCMD_EXEC;
    }
  
  mcmdHeader.Length = BI_1553MCMDBuffer[2] & 0x0FFF;
         
  if( MA_piGetBufferMCMD(&mcmdHeader.PtrMCMD, mcmdttag_direct)
      != SUCCESSFUL )
    {
      /* internal error: reject the MCMD */
      return CM_RC_UNSATISFIED;
    }
  else
    {
      memcpy((unsigned short int*)mcmdHeader.PtrMCMD, 
	     BI_1553MCMDBuffer, 
	     2*mcmdHeader.Length);
      *(MA_HEADER_MCMD*)sndMsg.Info = mcmdHeader;
      sndMsg.LlInfo = sizeof(MA_HEADER_MCMD);
      if( mcmdttag_direct == TIMETAG_MCMD )
	{
	  status = MT_piSndMsgTTManager(&sndMsg);
	  
	  if( status == HA_E1_TIMETAG_NOT_ALLOWED)
            {
	      // BI_1553MCMDACKWord[0] |= BI_MCMD_NOT_OK | BI_MCMD_WRONG_TIMETAG;
	      *(unsigned short int*)&sndMsg.Info[6] = status;
	      /* Extract parameters and delete MCMD from partition  */
	      //INFN_PATCH MA_piDelBufferMCMD(mcmdHeader.PtrMCMD,TIMETAG_MCMD,WAIT,NO_TIMEOUT);
	      MA_piDelBufferMCMD(mcmdHeader.PtrMCMD,TIMETAG_MCMD);
	    }
          else if(status == HA_E1_MCMD_QUEUE_FULL )
            {
              //BI_1553MCMDACKWord[0] |= BI_MCMD_NOT_OK | BI_MCMD_TTQUEUE_FULL;
	      *(unsigned short int*)&sndMsg.Info[6] = status;
	      /* Extract parameters and delete MCMD from partition  */
	      //INFN_PATCH MA_piDelBufferMCMD(mcmdHeader.PtrMCMD,TIMETAG_MCMD,WAIT,NO_TIMEOUT);
	      MA_piDelBufferMCMD(mcmdHeader.PtrMCMD,TIMETAG_MCMD);
	    }
	}
      else
	{
	  status = MD_piSndMsgMCMDDispatcher(&sndMsg);
        }
    }
}

#endif // ifdef SIMULATOR

/*****************************************************************************/
/*  TS_piSndMsgTest_INFN
 *
 *
 *  Input parameters:  NONE
 *
 *  Output parameters:  NONE
 *
 */
/*****************************************************************************/

status_code TS_SndMsgTest_INFN (MsgTsk* SndMsg)
{
  status_code status;

  status =OS_piMsgQueueSend_INFN(TS_INFN_MAILBOX,(void*)SndMsg,sizeof(MsgTsk));
  return (status);
}



