/***************************************************************
 ***    This is the first version of the "CLCDAQ" program    ***
 ***                                                         ***
 ***                  <<< S E N D E R >>>                    ***
 ***                                                         ***
 ***  Code in "send.c" will send DATA to the receiver using  ***
 ***  SmartSockets package. Theese DATA should  be red from  ***
 ***  the Scaler and  DPM (DualPortMemory) in  6U VME crate  ***
 ***  for luminosity calculations - total (Scaler DATA) and  ***
 ***  per  bunch (DPM DATA). After  calculations lumitosity  ***
 ***  should be  transmitted to  the Tevatron  (using ACNET  ***
 ***  structure) and  to the DPM  in  9U VME crate (for CDF  ***
 ***  DAQ).                                                  ***
 ***                                                         ***
 ***  Updates:                                               ***
 ***    ver_0_02:                                            ***
 ***      -> time structures added                           ***
 ***      -> luminosity calculations become realistic        ***
 ***      -> compact float-transmittion added                ***
 ***      -> time correction added                           ***
 ***      -> error handling added                            ***
 ***                                                         ***
 ***    ver_0_03:                                            ***
 ***      -> luminosity per bunch calculations (using DPM)   ***
 ***                             (instanteneous and total)   ***
 ***      -> DATA logging into the files                     ***
 ***                                                         ***
 ***    ver_0_04:                                            ***
 ***      -> dynamic memory allocation                       ***
 ***      -> Losses per bunch calculation                    ***
 ***      -> Automatic backup for LOG-files                  ***
 ***                                                         ***
 ***                                                         ***
 ***  Created:      May-10-2000       Sergey Makarychev.     ***
 ***                                  ( semak@fnal.gov )     ***
 ***  Last Updated: November-4-2000                          ***
 ***                                                         ***
 ***  Update        May 2001          (Ming)                 ***
 ***       -> include "clcTransformFloat32" for 32-bit       ***
 ***          representation of the real numbers for CLC     ***
 ***          lumi measurement                               ***
 ***                                                         ***
 ***  Update        June 5th 2001     (Ming)                 ***
 ***       -> CLC Inst. Lumi per bunch :                     ***
 ***          Using approx 8.8 hits per side (2 layers)      ***
 ***          Value obtained from the 36x36 0-bias data      ***
 ***          collected in April 2001                        ***
 ***                                                         ***
 ***       -> Include Version Id that will be printed out in ***
 ***          the clcdata.txt file.                          ***
 ***                                                         ***
 ***  Update        June 8th 2001     (Ming)                 ***
 ***       -> Convert instantaneous lumi to units of 1e30    ***
 ***       -> Comment out the subtraction of 25 in           ***
 ***          the power (in clcTransformFloat32)             ***
 ***                                                         ***
 ***  Update        June 13th 2001    (Valentin)             ***
 ***       -> BSC_NColl_West --> clcGetWestCollisionsNo      ***
 ***          BSC_NColl_East --> clcGetEastCollisionsNo      ***
 ***                                                         ***
 ***  Update	    July 13th 2001    (Valentin)             ***
 ***	   -> Close clcdata.txt at end of store              ***
 ***	      Add Luminosity to clcdata.txt                  ***
 ***                                                         ***
 ***  Update        July 27th 2001    (Ming)                 ***
 ***       -> Modify CLC Inst. Lumi per bunch :              ***
 ***          o Using approx 8.8 hits per side (2 layers)    ***
 ***            obtained from the 36x36 0-bias data          ***
 ***            collected in April 2001.                     ***
 ***          o Using Simga_effective = 38.9 mb              ***
 ***            Obtained from simulation using MBR           ***
 ***            (EL+SD+DD+HC) with 3X0 material infront      ***
 ***            from CLC to reproduce roughly                ***
 ***            the same hit multiplicity as in the data.    ***
 ***       -> Change the coincidence requirement from        ***
 ***               (N_East > 1) && (N_West > 1)              ***
 ***                           to                            ***
 ***               (N_East > 0) && (N_West > 0)              ***
 ***                                                         ***
 ***  Update        July 31th 2001    (Ming)                 ***
 ***   -> Readjust the Effective cross-section, and average  ***
 ***        number of hits due to drop in PMT gains          ***
 *** Ave Num of Hits = 13.8 hits for E+W L2+L3               ***
 ***        (at 500 ADC). This value obtained from the 36x36 ***
 ***        0-bias/LMB data collected on July 28-29 2001     ***
 *** Simga_effective = 36.5 mb                               ***
 ***   Obtained from simulation using MBR(EL+Stelnet D+DD+HC)***
 ***   with 3X0 material infront from CLC. Normalized MC to  ***
 ***   data based on the fitted SPP measured in data         ***
 ***   (July 28-29)                                          ***
 ***                                                         ***
 ***  Update	   August 30th 2001  (Valentin)              ***
 ***   -> Sigma_effective = 37.78mb                          ***
 ***      Ave Num of Hits = 16                               ***
 ***                                                         ***
 ***  Update	   September 19th 2001 (Valentin)            ***
 ***   -> Empty crossing method, lots of new variables.      ***
 ***                                                         ***
 ***  Update	   November 29th 2001 (Valentin)             ***
 ***   -> new variables (empty x) sent to ACNET              ***
 ***                                                         ***
 ***  Update	   January 18th 2002 (Valentin)              ***
 ***	-> Sigma_effective = 38.37mb                         ***
 ***      Ave Num of Hits = 15.86                            *** 
 ***                                                         ***
 ***  Update	   February 6th 2002 (Valentin)              ***
 ***	-> Sigma_effective = 36.61mb                         ***
 ***      Ave Num of Hits = 13.97                            *** 
 ***  Update	   March 7th 2002 (Valentin)                 ***
 ***	-> Sigma_effective = 37.50mb (march 7th effective)   ***
 ***      Ave Num of Hits = 14.5                             *** 
 ***                                                         ***
 ***  Update	   April 4th 2002 (Ming)                     ***
 ***	-> Sigma_effective = 36.60 mb (april 4th effective)  ***
 ***      Ave Num of Hits = 14.09                            *** 
 ***                                                         ***
 ***  Update	   May 16th 2002 (Ming)                      ***
 ***	-> Sigma_effective = 35.8 mb (may 17th effective)    ***
 ***      Ave Num of Hits = 13.6                             *** 
 ***                                                         ***
 *** Update        June 10th 2002 (Ming)                     ***
 ***    -> Add debugging lines to check if the B0's for      ***
 ***       all the 4 DPM are in the same memory location     ***
 ***                                                         ***
 *** Update        June 13th 2002 (Ming)                     ***
 ***    -> Search for the right memory location of B0 in     ***
 ***       each DPM                                          ***
 ***                                                         ***
 *** Update        June 19th 2002 (Ming)                     ***
 ***    -> Found a bug in the fix that I had put in on       ***
 ***       June 13th 2002. Remove bug !!!                    ***
 ***                                                         ***
 ***  Update	   Aug 09th 2002 (Ming)                      ***
 ***	-> Sigma_effective = 36.2 mb (9th Aug 2002 effective)***
 ***      Ave Num of Hits = 14.3                             *** 
 ***                                                         ***
 ***  Update	   Aug 28th 2002 (Ming)                      ***
 ***   -> Sigma_effective = 34.98 mb(28th Aug 2002 effective)***
 ***      Ave Num of Hits = 12.87                            *** 
 ***                                                         ***
 ***  Update       Sep 25th 2002 (Valentin)                  ***
 ***   -> Sigma_effective = 34.31 mb (Sep 26th effective?)   ***
 ***      Ave Num of Hits = 12. 48                           ***
 ***      alpha=0.14 beta_e=0.18 beta_w=0.12                 ***
 ***                                                         ***
 ***  Update       Nov 18th 2002 (Valentin)                  ***
 ***   -> Sigma_effective = 33.08 mb (Nov 19th effective)    ***
 ***      Ave Num of Hits = 11.88                            ***
 ***      alpha=.148 beta_e=.196 beta_w=.120                 ***
 ***                                                         ***
 ***  Update       Feb 11th 2003 (Ming)                      ***
 ***  New PMT on West Side => rough est. of SPP              ***
 ***   -> Sigma_effective = 37.1187 mb (Feb 11th effective)  ***
 ***      Ave Num of Hits = 14.8823                          ***
 ***      alpha=.1138 beta_e=.1224 beta_w=.1622              ***
 ***                                                         ***
 ***  Update       Feb 12th 2003 (Ming)                      ***
 ***  New PMT on West Side => SPP from MB data               ***
 ***   -> Sigma_effective = 35.1443 mb (Feb 12th effective)  ***
 ***      Ave Num of Hits = 12.5765                          ***
 ***      alpha=.1322 beta_e=.1576 beta_w=.1406              ***
 ***                                                         ***
 ***  Update       Feb 19th 2003 (Ming)                      ***
 ***  New HV for West Side => SPP from LED+spp               ***
 ***   -> Sigma_effective = 35.7366 mb (Feb 19th effective)  ***
 ***      Ave Num of Hits = 13.1167                          ***
 ***      alpha=.1268 beta_e=.1512 beta_w=.1428              ***
 ***                                                         ***
 ***  Update       Feb 21st 2003 (Ming)                      ***
 ***  New HV for West Side => SPP from LED+spp               ***
 ***   -> Sigma_effective = 32.6887 mb (Feb 21st effective)  ***
 ***      Ave Num of Hits = 11.2288                          ***
 ***      alpha=.1572 beta_e=.1736 beta_w=.1394              ***
 ***                                                         ***
 ***  Update       Feb 27th 2003 (Ming)                      ***
 ***  New HV for West Side => SPP from LED+spp               ***
 ***   -> Sigma_effective = 28.5177 mb (not used in online)  ***
 ***      Ave Num of Hits = 10.521                           ***
 ***      alpha=.1852 beta_e=.2412 beta_w=.1114              ***
 ***                                                         ***
 ***                                                         ***
 ***  Update       Mar 10th 2003 (Ming)                      ***
 ***  New 18 PMTs on the west side                           ***
 ***   -> Sigma_effective = 32.9478 mb (Mar 11th effective)  ***
 ***      Ave Num of Hits = 11.5378                          ***
 ***      alpha=0.152  beta_e=0.166 beta_w=0.148             ***
 ***                                                         ***
 ***  Update       Mar 12th 2003 (Ming)                      ***
 ***  New 18 PMTs on the west side (new SPP values)          ***
 ***   -> Sigma_effective = 34.4163 mb (Mar 12th effective ?)  ***
 ***      Ave Num of Hits = 12.5038                          ***
 ***      alpha=0.1388 beta_e=0.1498 beta_w=0.1536           ***
 ***                                                         ***
 ***  Update       Apr 04th 2003 (Ming)                      ***
 ***  Using SPP values from Store 2357 (mb2)                 ***
 ***   -> Sigma_effective = 33.1946 mb (Apr 04th effective)  ***
 ***      Ave Num of Hits = 11.4554                          ***
 ***      alpha=0.1484 beta_e=0.1612 beta_w=0.1524           ***
 ***                                                         ***
 ***  Update       May 31st 2003 (Ming)                      ***
 ***  Using SPP values from latest store+LED                 ***
 ***  Replace CLC WEST inner and middle layers' 30 PMTs      ***
 ***  Replacement done on May 27th 2003                      ***
 ***   -> Sigma_effective = 35.2554 mb (May 31st effective)  ***
 ***      Ave Num of Hits = 14.7504                          ***
 ***      alpha=0.1216 beta_e=0.1026 beta_w=0.2044           ***
 ***                                                         ***
 ***  Update       Aug 08th 2003 (Ming)                      ***
 ***  Using SPP values from latest store (2857)              ***
 ***   -> Sigma_effective = 34.7988 mb (May 31st effective)  ***
 ***      Ave Num of Hits = 14.1894                          ***
 ***      alpha=0.1254 beta_e=0.1016 beta_w=0.2090           ***
 ***                                                         ***
 ***  Update       Nov 21st 2003 (Ming)                      ***
 ***  Using SPP values estimate from SPP(sep16)              ***
 ***  SPP_est = SPP(Sep16)*LED(Nov10)/LED(Sep16)             ***
 ***   -> Sigma_effective = 38.5872 mb (11/21/03 effective)  ***
 ***      Ave Num of Hits = 16.5376                          ***
 ***      alpha=0.0998 beta_e=0.1264 beta_w=0.1484           ***
 ***                                                         ***
 ***  Update       Nov 25th 2003 (Ming)                      ***
 ***  Using SPP values from latest store (3043)              ***
 ***   -> Sigma_effective = 38.8463 mb (11/25/03 effective)  ***
 ***      Ave Num of Hits = 16.8059                          ***
 ***      alpha=0.0976 beta_e=0.1296 beta_w=0.1432           ***
 ***                                                         ***
 ***  Update       May 09th 2004 (Ming)                      ***
 ***  Using SPP values from latest store (3464)              ***
 ***   -> Sigma_effective = 37.6000 mb (05/10/04 effective)  ***
 ***      Ave Num of Hits = 14.9541                          ***
 ***      alpha=0.1080 beta_e=0.1350 beta_w=0.1476           ***
 ***                                                         ***
 ***  Update       Dec 16th 2004 (Ming)                      ***
 ***  Using SPP values from latest store (3845)              ***
 ***   -> Sigma_effective = 37.6864 mb (12/16/04 effective)  ***
 ***      Ave Num of Hits = 15.238                           ***
 ***      alpha=0.1076 beta_e=0.1432 beta_w=0.1384           ***
 ***                                                         ***
 *** Update 	 Mar 02 2005 (Valentin, Lester)	             ***
 *** Using SPP values from latest store (4004)               ***
 ***   -> Sigma_effective = 36.1068 mb (12/16/04 effective)  ***
 ***      Ave Num of Hits = 13.811                           ***
 ***      alpha=0.1204 beta_e=0.1574 beta_w=0.1370	     ***
 ***	                                                     ***
 *** Update	Jul 11 2005 (Valentin, Lester)		     ***
 *** Using SPP values from store 4132                        ***
 ***  -> Sigma_effective = 34.82 mb (07/11/04 effective)     ***
 ***     Ave Num of Hits = 12.49                             ***
 ***     alpha=0.1326 beta_e=0.1664 beta_w=0.1366            *** 
 ***	                                                     ***
 *** Update	Jul 18 2005 (Lester)		             ***
 *** Using SPP values from store 4250                        ***
 ***  -> Sigma_effective = 33.95 mb (07/18/04 effective)     ***
 ***     Ave Num of Hits = 11.89                             ***
 ***     alpha=0.1418 beta_e=0.1740 beta_w=0.1340            *** 
 ***	                                                     ***
 *** Update	Oct 1 2005 (Lester)		             ***
 *** Using SPP values from store 4349                        ***
 ***  -> Sigma_effective = 33.02 mb (10/01/04 effective)     ***
 ***     Ave Num of Hits = 11.22                             ***
 ***     alpha=0.152 beta_e=0.1766 beta_w=0.1362            *** 
 ***************************************************************/
 
#include <vxWorks.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sigLib.h>
#include <streams/led.h>
#include <usrLib.h>
#include <rtworks/common.h>
#include <rtworks/util.h>
#include <rtworks/ipc.h>
#include <VISION.h>
#include <clcdaq.h>

/* Ming++ */
/* #define VERSION_ID 5 */      /* version id (June 5th 2001) */
/* #define VERSION_ID 6 */      /* version id (June 9th 2001) */
/* #define VERSION_ID 6.01 */   /*version id (june 13th 2001) */ 
/* #define VERSION_ID 6.10 */   /*version id (july 27th 2001) */
/* Ming-- */
/* Valentin */
/* #define VERSION_ID 6.11  (july 31st 2001) */
/* #define VERSION_ID 6.12  (august 30th 2001) */
/* #define VERSION_ID 6.2   (september 19th 2001) */
/* #define VERSION_ID 6.3   (november 29th 2001) */
/* #define VERSION_ID 6.41  ( march  7th 2002) */
/* #define VERSION_ID 6.42  (april 4th 2002) */
/* #define VERSION_ID 6.50  (Aug 9th 2002) */
/* #define VERSION_ID 6.51  Aug 28th 2002 */
/* #define VERSION_ID 6.6  Sep 11th 2002 */
/* #define VERSION_ID 6.7  Sep 23rd 2002 */
#define VERSION_ID 6.71  /* Nov 18th 2002 */

#define NHITS 11.22
#define CRSEC 33.02

#define EPS_E 0.1766
#define EPS_W 0.1362
#define EPS_0 0.1520
#define SIG_INEL 61.7

#define EMPTY 0
#define HIT 1
#define EMPTY2 2 /* correct formula */

#define INST 0
#define INTG 1
#define DELIV 0
#define GLIVE 1

#define METHOD 2  /* METHOD : the oficial luminosity method */
#define METHOD2 1 /* METHOD2 : second method for our logfiles */
#define METHODS 3

#define BufferSize 32*1024    /* size of DATA arrays - 32 KWord */

#define CLC_OFFSET 10         /* offset "B0"   <--> "DATA"      */
#define CLC_OFFSET_GLIVE 28   /* offset "DATA" <--> "GLIVE"     */
#define BSC_OFFSET 3          /* offset "B0"   <--> "BSC DATA"  */

#define PAGES_No 10
#define BSC_PAGES_No 20

#define MAX_BUNCHES_NO 159    /* maximum amount of bunches (from B0 to next B0) */

#define PAUSE 1               /* pause for Scaler in seconds */

/* External structures for ACNET !!! */

struct LUMINOSITY{
  float total;
  float bunch[NUM_BUNCHES];
};

struct acnet{
  float clc_scalers[16]; 
  float clc_Z_position;
  struct  LUMINOSITY luminosity;
  struct  LUMINOSITY plos;
  struct  LUMINOSITY alos;
  struct  LUMINOSITY total_luminosity;
  struct  LUMINOSITY live_luminosity;
  struct  LUMINOSITY total_live_luminosity;
  struct  LUMINOSITY luminosity_e;
  struct  LUMINOSITY total_luminosity_e;
  struct  LUMINOSITY live_luminosity_e;
  struct  LUMINOSITY total_live_luminosity_e;
  
  float bsc_cntr_losses[8];
  float bsc_beam_position[8];
  float losses_ag[6];
  float losses_in[6];
}acnet_lum;

extern int sysClkRateGet();      /*for sleep() function */
/* --------------------------------------*/

/* FUNCTION'S PROTOTYPES     */
void      clcVMESlaveA24D16SetUp (VISION_SLAVE *); /* for DPMs and FAN */
void      clcVMESlaveA32D32SetUp (VISION_SLAVE *); /* for Scaler*/
void      clcPrintIntDATA (unsigned int *, short); /* TEST */
short int clcGetSignalsNumber (unsigned int);
short int clcGetLast4BitsNo (unsigned int event);
short int clcGetWestLossesNo (unsigned int event);
short int clcGetEastLossesNo (unsigned int event);
short int clcGetWestCollisionsNo (unsigned int event);
short int clcGetEastCollisionsNo (unsigned int event);
/* DT.begin */
int sendReset ();
int sendActivate(int);
int sendEnd(int);

void clcResetLumi (float*,float*,int);
/* DT.end */
float     clcGetInstLumi  (float);
float     clcGetTotalLumi (float, unsigned long int, float, unsigned long int);
float     clcGetscaler_InstLumi  (float);
float     clcGetBSC_TotalLumi (float, unsigned long int, float, unsigned long int);
float     clcGetSum (float *, int);
T_BOOL    clcDATAfloat_not_zero (float *, int, int);
char *    clcGetFileName(char *, char *, struct tm);

void clcInitSS(T_STR);
void clcInitSS_old(T_STR);
void clcMessageSetUp (T_IPC_MSG *);

unsigned short int clcTransformFloat (double);
/* ++ Ming ++ */
unsigned int clcTransformFloat32 (double);
/* -- Ming -- */
struct tm          clcGetLocalTime (void);

int clcsend();  /*the MAIN function. */

/* --------------------------------------------------------------------------- */
unsigned int clcControlByte; /*   GLOBAL VARIABLE for program controlling      */
unsigned int clcReset;   /*DT   GLOBAL VARIABLE to reset total Luminosity      */
unsigned int clcRunActive;

float         Run_LUMI, old_LUMI;
float         Run_LUMI_GLIVE, old_LUMI_GLIVE;

float lumi[METHODS][2][2]; /* empty:hit(0:1), inst:tot(0:1), deliv:glive(0:1) */

#include "func.ic"
#include "ComputeMu.ic"

/* ---------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------- */
/*                              MAIN                                            */
/* ---------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------- */
int clcsend (){
                                                                                /*
     !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     !!!                                    !!!
     !!! NOTE: SizeOf (int)   = 32 bits     !!!
     !!!       SizeOf (long)  = 32 bits     !!!
     !!!       SizeOf (short) = 16 bits     !!!
     !!!                                    !!!
     !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                                */

	T_IPC_MT mt;             /* SmartSockets message type                        */
	T_IPC_MSG msg;           /* SmartSockets message                             */
	T_IPC_MSG ACK_msg;       /* Acknowledge message                              */

	VISION_SLAVE DPM_7c;     /* Dual Port Memory 1 (base addr. 0x7c0000)         */
	VISION_SLAVE DPM_bc;     /* Dual Port Memory 2 (base addr. 0xbc0000)         */
	VISION_SLAVE DPM_dc;     /* Dual Port Memory 3 (base addr. 0xdc0000)         */
	VISION_SLAVE DPM_ec;     /* Dual Port Memory 4 (base addr. 0xec0000)         */
	VISION_SLAVE DPM_f4;     /* Dual Port Memory 5 (base addr. 0xf40000)         */
	VISION_SLAVE FAN;        /* Signal Distributor (base addr. 0x600000)         */
	VISION_SLAVE SCALER;     /* Scaler             (base addr. 0x38001800)       */
	VISION_SLAVE ACNDPM;     /* Dual Port Memory for Acnet (base addr. 0x3c0000) */ 

	char VME_InitStr[99]=""; /* Paramerets String for VISIONopen()               */
	int  VMEstatus;
	unsigned int VMErealbytes;
	unsigned short int data16;
	unsigned int data32;
 
	unsigned int *buffer_7c; /* buffer for reading from DPM_7c */
	unsigned int *buffer_bc; /* buffer for reading from DPM_bc */
	unsigned int *buffer_dc; /* buffer for reading from DPM_dc */
	unsigned int *buffer_ec; /* buffer for reading from DPM_ec */
	unsigned int *buffer_f4; /* buffer for reading from DPM_f4 */
  

	unsigned int   event, bucket_No, bunch_No;
	unsigned short N_West, N_East;
	float          N_hits_Average, noHits_prob[NUM_BUNCHES];
	float          N_hits_Average_GLIVE;
	T_BOOL         AG, BC, NextCycle, B0_found;
	unsigned short offset;
  
	unsigned int N_hits_Sum[NUM_BUNCHES], N_noHits_Sum[NUM_BUNCHES];
	unsigned int N_hits_Sum_GLIVE[NUM_BUNCHES];
	unsigned int N_total[NUM_BUNCHES], N_total_GLIVE[NUM_BUNCHES],gLive;
	unsigned int N_coinc[NUM_BUNCHES];

	unsigned int N_hits_Sum_159[MAX_BUNCHES_NO];   /* DT.begin */ 
	unsigned int N_total_159[MAX_BUNCHES_NO];      
	float        lumi_159[MAX_BUNCHES_NO];         /* DT.end: Instanteneous luminosity per bucket */

	float	lumi36[METHODS][2][2][NUM_BUNCHES]; /*  lumi per bucket */
	float  lumiInstOld36[METHODS][2][NUM_BUNCHES]; /* only instantaneous (one index less) */
	float  lumi2Sum[METHODS][2], lumi2Bucket[METHODS][2];  /* lumi integrated between two consec times */
  
	float        clc_lumi_scaler;                 /* Inst. luminosity from scaler and SCALER*/
	float        clc_lumi_scaler_old;
	float        CLC_LUMI_scaler;                  /* Integrated lumi from clc */

	unsigned int PagesCount;

	unsigned int BSC_N_East [5][NUM_BUNCHES]; /* Numbers of hits for LOSSES */
	unsigned int BSC_N_West [5][NUM_BUNCHES]; /* (0..3) -> BSC_No, 4->total */
	float        East_Losses[5][NUM_BUNCHES]; /* Losses from East and West  */
	float        West_Losses[5][NUM_BUNCHES]; /*      (ration in Hz)        */
	float        East_LOSSES;                 /* Total sum of ALL the East Losses */
	float        West_LOSSES;                 /* The same for West (sum of ALL bunches) */
	/* unsigned int BSC_N_coinc[NUM_BUNCHES]; */    /* Number of co-incedences from LOSSES */

	unsigned int BSC_N_East_AG[3];
	unsigned int BSC_N_West_AG[3];
	unsigned int BSC_N_East_IN[3];
	unsigned int BSC_N_West_IN[3];

	float        East_scaler_Losses;
	float        West_scaler_Losses;

	float        east_losses_old, west_losses_old;
	float        east_losses[NUM_BUNCHES], west_losses[NUM_BUNCHES];
	float        EAST_TOT_LOSSES, WEST_TOT_LOSSES;
	float        AV_INS_EAST_LOSS, AV_INS_WEST_LOSS;            	
	float        AV_TOT_EAST_LOSS, AV_TOT_WEST_LOSS;            
	float        coinc_coll_old, coinc_coll[NUM_BUNCHES];
	float	       COINC_TOT_COLL;
	float        AV_INS_COINC_COLL, AV_TOT_COINC_COLL;	   

	unsigned int BSC_NColl_East[5][NUM_BUNCHES];
	unsigned int BSC_NColl_West[5][NUM_BUNCHES];
	float        East_Collisions[5]; /* Collisions from East and West  */
	float        West_Collisions[5]; /*      (ration in Hz)            */
	float        East_LOSSES_CNTR[4], West_LOSSES_CNTR[4];  /* Cntr Losses (0-3)=BSC1-4 */
	float        Rbp_Loss[4], Rbp_Coll[4];                  /* BP ratios (0-3)=Ex,Ey,Wx,Wy */
	/* Koji(02/07/31) --> */
	unsigned int BSC_NColl_coinc[6][NUM_BUNCHES]; /* 0-3=BSC1-4, 4=factor applied, 5=standard */
	float        Coinc_Coll[NUM_BUNCHES];
	float        Coinc_sp_Coll[5];
	/* <-- Koji(02/07/31) */
  
	float        AV_lumi_8hours;
	float        AV_LUMI_8hours;
	unsigned int counter_8hours;

	float        mu[NUM_BUNCHES];
	unsigned int DPMdata[MAX_BUNCHES_NO];
	unsigned int mask;                    /* for printing DPM bits to file */

	unsigned int ScalerBuffer[32];      /* buffer for reading from the Scaler         */
	float        clc_tight_coincedences;

	float        clcLosses[16];
  
  
	unsigned short int i,j,k;              /* "for"-counters             */
	T_BOOL Continue;                    /* flag for infinite loop     */
	T_BOOL CanSendMessage;              /* flag for connection status */

	unsigned int counter;               /* it increments every loop   */

	T_INT2 AVERAGE; 
	T_INT2 BUNCH[NUM_BUNCHES];

/* ++ Ming ++ */
	T_INT4 AVERAGE32; 
	T_INT4 BUNCH32[NUM_BUNCHES];
/* -- Ming -- */

	T_INT2 BUNCH2[BSC_ARRAY_SIZE];

	FILE *F_DATA, *F_CLC_DATA, *F_ERROR, *F_DPM, *F_TEST, *F_SUMMARY;
	FILE *F_LUMI_BUNCH;  /* DT */
  
	/*struct acnet acnet_lum;*/
	void *voidptr;  /* void pointer to write acnet_lum to DPM */	
	struct acnet *lumptr;
  
	long int FileSize;
	int      FileStatus;
	char     FileName[50];

	struct tm TIME;                     /* structure for receiving SYSTEM_TIME */
	unsigned long int time32, time_old;
	unsigned long int BSC_time32, BSC_time_old;

	unsigned long int STARTtime32;
	unsigned long int start_time;

        /* diptest */
        int NcntB0[20];
        int cntpage;

/* ++ Ming diptest ++ */
        int iflg_prb;
        int iflg_prb2;
        int ib0_1;
        int ib0_2;
        int ib0_3;
        int ib0_4;
        int i1,i2,i3,i4;
        int    j2,j3,j4;
        int ioff, indx;
        /* FILE *F_DIP; */
/* -- Ming diptest -- */

	/*------------------ Start Here -------------------------------------------*/

	clcControlByte = 0x00000042; /* DPM OFF, CLC ON, Raw ON, PerBunch OFF, Test ON */
	printf("control byte %d \n", clcControlByte);
	clcReset = 0;
	clcRunActive = 0;
	lumptr = &acnet_lum; /* take address of acnet luminosity structure */
	voidptr = lumptr;

	clcInitSS_old("send.cmd");              /* Initialization of SmartSockets      */ 
	printf ("\n\n->Work started.\n");

	/*------------------ Creating new SmartSocket Message ---------------------*/
	
	mt = TipcMtLookupByNum (T_MT_NUMERIC_DATA);
	if (mt == NULL){
		TutOut ("TipcMtLookupByNum failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
		exit (2);       
	}
	msg = TipcMsgCreate (mt); 
	if (msg == NULL){
		TutOut ("TipcMsgCreate failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
		exit (2); 
	} 
	else TutOut ("->New message was created.\n");
  
	/*------------------ Initializing Message  --------------------------------*/
	clcMessageSetUp (&msg); /* subject, sender, deliveryMode, etc....             */

	/*------------------ Setting Subscribe Subject ----------------------------*/ 
	if (!TipcSrvSubjectSetSubscribe ("/clc_ready", TRUE)){
		TutOut ("TipcSrvSubjectSetSubscribe failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
		exit (2); 
	}
	else TutOut ("->Subscribe subject was set to '/clc_ready'.\n");

	/*------------------ Creating DPM Slaves ----------------------------------*/

	/*    1). DPM_7c (base 0x7c0000)            */
	sprintf(VME_InitStr,"vme:/addrtype=std/priv=user/space=data/base=0x7c0000/size=0x20000");
	VMEstatus = VISIONopen(&DPM_7c, VME_InitStr, "");
	if (VMEstatus != 0){
		printf ("Couldn't create DPM_7c slave: <error %d>\n", VMEstatus);
		exit (1); 
	}
	else printf ("->DPM_7c Slave was created.\n");
	/*    2). DPM_bc (base 0xbc0000)            */
	sprintf(VME_InitStr,"vme:/addrtype=std/priv=user/space=data/base=0xbc0000/size=0x20000");
	VMEstatus = VISIONopen(&DPM_bc, VME_InitStr, "");
	if (VMEstatus != 0){
		printf ("Couldn't create DPM_bc slave: <error %d>\n", VMEstatus);
		exit (1); 
	}
	else printf ("->DPM_bc Slave was created.\n");
	/*    3). DPM_dc (base 0xdc0000)            */
	sprintf(VME_InitStr,"vme:/addrtype=std/priv=user/space=data/base=0xdc0000/size=0x20000");
	VMEstatus = VISIONopen(&DPM_dc, VME_InitStr, "");
	if (VMEstatus != 0){
		printf ("Couldn't create DPM_dc slave: <error %d>\n", VMEstatus);
		exit (1); 
	}
	else printf ("->DPM_dc Slave was created.\n");
	/*    4). DPM_ec (base 0xec0000)            */
	sprintf(VME_InitStr,"vme:/addrtype=std/priv=user/space=data/base=0xec0000/size=0x20000");
	VMEstatus = VISIONopen(&DPM_ec, VME_InitStr, "");
	if (VMEstatus != 0){
		printf ("Couldn't create DPM_ec slave: <error %d>\n", VMEstatus);
		exit (1); 
	}
	else printf ("->DPM_ec Slave was created.\n");
	/*    5). DPM_f4 (base 0xf40000)            */
	sprintf(VME_InitStr,"vme:/addrtype=std/priv=user/space=data/base=0xf40000/size=0x20000");
	VMEstatus = VISIONopen(&DPM_f4, VME_InitStr, "");
	if (VMEstatus != 0){
		printf ("Couldn't create DPM_f4 slave: <error %d>\n", VMEstatus);
		exit (1); 	
	}
	else printf ("->DPM_f4 Slave was created.\n");
	/*    6). FAN (base 0x600000)            */
	sprintf(VME_InitStr,"vme:/addrtype=std/priv=user/space=data/base=0x600000/size=0x20000");
	VMEstatus = VISIONopen(&FAN, VME_InitStr, "");
	if (VMEstatus != 0){
		printf ("Couldn't create FAN slave: <error %d>\n", VMEstatus);
		exit (1); 
	}
	else printf ("->FAN Slave was created.\n");
	/*    7). SCALER (base 0x38001800)            */
	sprintf(VME_InitStr,"vme:/addrtype=ext/priv=user/space=data/base=0x38001800/size=1000");
	VMEstatus = VISIONopen(&SCALER, VME_InitStr, "");
	if (VMEstatus != 0){
		printf ("Couldn't create SCALER slave: <error %d>\n", VMEstatus);
		exit (1); 	
	}
	else printf ("->SCALER Slave was created.\n");
	/*    8). ACNDPM for acnet  (base 0x3c0000)      */
	sprintf(VME_InitStr,"vme:/addrtype=std/priv=user/space=data/base=0x3c0000/size=0x20000");
	VMEstatus = VISIONopen(&ACNDPM, VME_InitStr, "");
	if (VMEstatus != 0){
		printf ("Couldn't create ACNDPM slave: <error %d>\n", VMEstatus);
		exit (1); 
	}
	else printf ("->ACNDPM Slave was created.\n");
	/*------------------ Configure DPMs ----------------------------------------*/
	clcVMESlaveA24D16SetUp (&DPM_7c);
	printf ("->DPM_7c Slave was configured.\n");
	clcVMESlaveA24D16SetUp (&DPM_bc);
	printf ("->DPM_bc Slave was configured.\n");
	clcVMESlaveA24D16SetUp (&DPM_dc);
	printf ("->DPM_dc Slave was configured.\n");
	clcVMESlaveA24D16SetUp (&DPM_ec);
	printf ("->DPM_ec Slave was configured.\n");
	clcVMESlaveA24D16SetUp (&DPM_f4);
	printf ("->DPM_f4 Slave was configured.\n");
	clcVMESlaveA24D16SetUp (&ACNDPM);
	printf ("->ACNDPM Slave was configured.\n");   /* acnet dpm */
	clcVMESlaveA24D16SetUp (&FAN);
	printf ("->FAN Slave was configured.\n");
	clcVMESlaveA32D32SetUp (&SCALER);
	printf ("->SCALER Slave was configured.\n");

	/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
	/* !!                                                                   !! */
	/* !!                W O R K I N G   P A R T                            !! */
	/* !!                                                                   !! */
	/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */

	/*------------------ Dynamic Memory Allocation ----------------------------*/
	buffer_7c = malloc (128*1024);
	buffer_bc = malloc (128*1024);
	buffer_dc = malloc (128*1024);
	buffer_ec = malloc (128*1024);
	buffer_f4 = malloc (128*1024);

	if ( (buffer_7c == NULL)||(buffer_bc == NULL)||(buffer_dc == NULL)||
		(buffer_ec == NULL)||(buffer_f4 == NULL) ){
			TutOut ("Can't allocate memory for buffers!");
			exit(3);
	}
	TutOut ("->Memory allocated.\n");
	/* ----------------- Opening LOG-files  ---------------------------------- */
	F_DATA = F_CLC_DATA = F_DPM = F_TEST = NULL;
	F_ERROR = F_SUMMARY = F_LUMI_BUNCH = NULL;
 
        /* +++ Ming diptest +++ */
	/* F_DIP = NULL; */
        /* --- Ming diptest --- */

	F_DATA = fopen ("/cdf/code-common/cdfonline/clc/rawdata.txt", "a");
	if (F_DATA == NULL){
		printf ("->'rawdata.txt' file open error!\n");
		goto exit;
	}
	TutOut ("->'rawdata.txt' file was opened.\n");

	F_CLC_DATA = fopen ("/cdf/code-common/cdfonline/clc/clcdata.txt", "a");
	if (F_CLC_DATA == NULL){
		printf ("->'clcdata.txt' file open error!\n");
		goto exit;  
	}
	TutOut ("->'clcdata.txt' file was opened.\n");

	F_DPM = fopen ("/cdf/code-common/cdfonline/clc/DPMdata.txt", "a");
	if (F_DPM == NULL){
		printf ("->'DPMdata.txt' file open error!\n");
		goto exit;
	}
	TutOut ("->'DPMdata.txt' file was opened.\n");

	F_ERROR = fopen ("/cdf/code-common/cdfonline/clc/s_error.log", "a");
	if (F_ERROR == NULL){
		printf ("->'s_error.log' file open error!\n");
		goto exit;
	}
	TutOut ("->'s_error.log' file was opened.\n");

	F_SUMMARY = fopen("/cdf/code-common/cdfonline/clc/summary.log", "a");
	if (F_SUMMARY == NULL){
		printf ("->'summary.log' file open error!\n");
		goto exit;
	}
	TutOut ("->'summary.log' file was opened.\n");

	F_TEST = fopen ("/cdf/code-common/cdfonline/clc/test.txt", "a");
	if (F_TEST == NULL){
		printf ("->'test.txt' file open error!\n");
		goto exit;
	}
	TutOut ("->'test.txt' file was opened.\n");

	F_LUMI_BUNCH = fopen("/cdf/code-common/cdfonline/clc/lumi_per_bunch.txt","a");  /* DT */
	if (F_LUMI_BUNCH == NULL){
		printf ("->'lumi_per_bunch.log' file open error!\n");
		goto exit;
	}
	TutOut ("->'lumi_per_bunch.log' file was opened.\n");

	TIME = clcGetLocalTime();
	fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	fprintf (F_ERROR, "Program restarts... (crate was rebooted) \n");
	fclose (F_ERROR);
	F_ERROR = fopen ("/cdf/code-common/cdfonline/clc/s_error.log", "a");

	fprintf (F_SUMMARY, "\n\n----------------------------------------\n");
	fprintf (F_SUMMARY, "%d/%d/%d (%02d:%02d:%02d) ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	fprintf (F_SUMMARY, "Crate was rebooted \n\n");
	fclose (F_SUMMARY);
	F_SUMMARY = fopen ("/cdf/code-common/cdfonline/clc/summary.log", "a");

	/* ----------------- Initializing FAN (Enable all Inputs) ---------------- */
	data16 = 0x006f;
	VMEstatus = VISIONwrite (FAN, 0x000c, 2, &VMErealbytes, &data16);
	if (VMEstatus != 0){
		printf ("!!!!! ->Couldn't Enable FAN Inputs: <error %d>\n", VMEstatus);
		goto exit;
	}  

	/* ----------------- Initializing Variables ------------------------------ */
	for (i=0;i<MAX_BUNCHES_NO;i++)
		DPMdata[i] = lumi_159[i] = 0;  /* DT */

	STARTtime32 = time (NULL); /* start point for 8-hours logging */
	time32 = BSC_time32 = 0;
	start_time = 0;
  
	for (i=0;i<NUM_BUNCHES;i++){
		for(j=0;j<METHODS;j++)	
			lumi36[j][0][0][i]  = lumi36[j][0][1][i] = lumi36[j][1][1][i] = lumi36[j][1][0][i] = 0.;
		mu[i] =0;

		for (j=0;j<5;j++)East_Losses[j][i] = West_Losses[j][i] = 0;
   
		Coinc_Coll[i] = coinc_coll[i] =0;
		east_losses[i] = west_losses[i] = 0;           
	}
  
	East_LOSSES = West_LOSSES = 0;
	EAST_TOT_LOSSES = WEST_TOT_LOSSES = 0;   
	COINC_TOT_COLL = 0;
	AV_INS_WEST_LOSS = AV_INS_EAST_LOSS = 0;
	AV_TOT_WEST_LOSS = AV_TOT_EAST_LOSS = 0;
	AV_INS_COINC_COLL = AV_TOT_COINC_COLL = 0;  

	clc_tight_coincedences = 0;
	clc_lumi_scaler = CLC_LUMI_scaler = 0;
	for(j=0;j<METHODS;j++)lumi[j][0][0]=lumi[j][0][1]=lumi[j][1][0]=lumi[j][1][1]=0;
	Run_LUMI = Run_LUMI_GLIVE =  old_LUMI = old_LUMI_GLIVE = 0;
	AV_lumi_8hours = AV_LUMI_8hours = 0;
	counter_8hours = 0;

	Continue = CanSendMessage=TRUE;
	counter = 0;
	printf ("->Infinite Loop Started...\n");
                                                                             /*
           oooooooooooooooooooooooooooooooooooooooooo
           o                                        o
           o <<<   I N F I N I T E    L O O P   >>> o
           o                                        o
           oooooooooooooooooooooooooooooooooooooooooo                        */
  
  
	while (Continue){
    /* check if program should hold    */
    while (clcControlByte & 0x00000010) sleep(1);/* do NOTHING, just wait...*/

    /*  if (clcControlByte & 0x00000001)       check if we should exit */
    /* Continue = FALSE;*/  

    /* ------------------ GETTING Time --------------------------------------- */
    TIME = clcGetLocalTime();
    /* ------------------ Reset Luminosity  --------------------------------------- */
    if (clcReset>0){
	 	for(j=0;j<METHODS;j++)clcResetLumi(lumi36[j][1][0],lumi36[j][1][1],NUM_BUNCHES);
	fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
    	fprintf (F_ERROR, " Total  Luminosity was reset\n");      
      	fclose (F_CLC_DATA);
      	clcGetFileName (FileName, "clcdata/clcdata_",TIME);

      	/* save file in "clcdata" directory and open the new one */
	FileStatus = copy ("/cdf/code-common/cdfonline/clc/clcdata.txt", FileName);
	if (FileStatus == 0){
	   printf ("->File \"clcdata.txt\" was copied to \"clcdata\" directory.\n");    
	   /* create the new LOG-file */
	   F_CLC_DATA = fopen ("/cdf/code-common/cdfonline/clc/clcdata.txt", "w");
	   if (F_CLC_DATA == NULL){
	      printf ("->ERROR: Can't create new file.\n");
	      fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	      fprintf (F_ERROR, "Couldn't empty \"clcdata.txt\"\n");
	      /* STOP logging in "clcdata.txt" */
	      clcControlByte &= 0xffffffbf;
	   }
	   printf ("->New file \"clcdata.txt\" was created.\n");
	}
	else{
	    printf ("->ERROR: Can't copy file.\n");
	    fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	    fprintf (F_ERROR, "Couldn't copy \"clcdata.txt\"\n"); 
	    /* STOP logging in "clcdata.txt" */
	    clcControlByte &= 0xffffffbf;
	    /* file remains closed... */
	}
      	clcReset = 0;
    }
                                                                               /*
    ooooooooooooooooooooooooooooooooooooo
    o                                   o
    o <<<   S C A L E R   P A R T   >>> o
    o                                   o
    ooooooooooooooooooooooooooooooooooooo                                      */

    /* ------------------ ENABLING / DISABLING Scaler ------------------------ */
  
    /*  1. Clear all counters and overflows   */
    data32 = 0x000;               /* any data */
    VMEstatus = VISIONwrite (SCALER, 0x20, sizeof (data32), &VMErealbytes, &data32);
    if (VMEstatus != 0){
	fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	fprintf (F_ERROR, "Couldn't Clear Scaler Counters: <error %d>\n", VMEstatus);
	goto dpm_part;
    }

    /*  2. Enable all counters                */
    data32 = 0x000;               /* any data */
    VMEstatus = VISIONwrite (SCALER, 0x028, sizeof (data32), &VMErealbytes, &data32);
    if (VMEstatus != 0){
	fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	fprintf (F_ERROR, "Couldn't Enable Scaler: <error %d>\n", VMEstatus);
	goto dpm_part;
    }
    
    /*  3. Getting the system TIME         */
    if (BSC_time32 == 0)BSC_time_old = BSC_time32 = time (NULL);
    	/* first measurement: dt should be 0 */
    else{ 
      /* regular regime */
      BSC_time_old = BSC_time32;
      BSC_time32 = time (NULL);
    }

    /*  4. Wait for some time (Scaler counts) */
    sleep (PAUSE);            /* 1 sec paused */

    /*  5. Disable all counters               */
    data32 = 0x000;               /* any data */
    VMEstatus = VISIONwrite (SCALER, 0x02c, sizeof (data32), &VMErealbytes, &data32);
    if (VMEstatus != 0){
	fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	fprintf (F_ERROR, "Couldn't Disable Scaler: <error %d>\n", VMEstatus);
	goto dpm_part;
    }
    
    /* ---------------- Read DATA from the Scaler ------------------------------ */
    VMEstatus = VISIONread (SCALER, 0x280, sizeof (ScalerBuffer), &VMErealbytes, ScalerBuffer);
    if (VMEstatus != 0){
	fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	fprintf (F_ERROR, "Couldn't read from the Scaler: <error %d>\n", VMEstatus);
	goto dpm_part;
    }
    
    /* ----- Inst. and total Luminosity using BSCs and SCALER ---------------- */
    clc_tight_coincedences = (float)ScalerBuffer[29]/PAUSE;
    clc_lumi_scaler_old = clc_lumi_scaler;
    clc_lumi_scaler     = clcGetscaler_InstLumi (clc_tight_coincedences);
    CLC_LUMI_scaler = CLC_LUMI_scaler + clcGetTotalLumi(clc_lumi_scaler_old, BSC_time_old, clc_lumi_scaler, BSC_time32);
    
  dpm_part:
                                                                               /*
    ooooooooooooooooooooooooooooooo
    o                             o
    o <<<   D P M   P A R T   >>> o
    o                             o
    ooooooooooooooooooooooooooooooo                                            */

    /*  Getting the system TIME */
    if (time32 == 0){
      /* first measurement: dt should be 0 */
      time_old = time32 = time (NULL);
      start_time = time_old;
    }
    else{ 
      /* regular regime */
      time_old = time32;
      time32 = time (NULL);
    }
    
    if ((time32 - STARTtime32) > 60*60){
      /* 1 hour passed, print summary statistics */
      fprintf (F_SUMMARY, "Last 60 min until %d/%d/%d (%02d:%02d:%02d):\n",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
      fprintf (F_SUMMARY, "<Inst. Luminosity> = %6.4f E30\n", AV_lumi_8hours);
      fprintf (F_SUMMARY, " Total Luminosity  = %6.4f nb-1\n\n", AV_LUMI_8hours);
      fclose (F_SUMMARY);
      F_SUMMARY = fopen("/cdf/code-common/cdfonline/clc/summary.log", "a");
      /* re-initialization */
      STARTtime32 = time(NULL); 
      AV_lumi_8hours = AV_LUMI_8hours = 0;
      counter_8hours = 0;
    }
                                                                               /*
    ooooooooooooooooooooo
    o                   o
    o <<<   C L C   >>> o
    o                   o
    ooooooooooooooooooooo                                                      */

    /*   Initialization    */
    for (i=0;i<NUM_BUNCHES;i++){     /* i -> bunch_No */
      N_hits_Sum[i] = N_hits_Sum_GLIVE[i] =N_noHits_Sum[i]= 0;
      N_total[i] = N_total_GLIVE[i] = N_coinc[i] = 0;
    }
    for (i=0;i<159;i++)N_hits_Sum_159[i] = N_total_159[i] = 0;/* DT */

    /* diptest */
    for (i=0;i<20;i++) {
      NcntB0[i] = 0;
    }
    cntpage = 0;

/* ++ Ming diptest ++ */
    iflg_prb = 0;
    iflg_prb2 = 0;
    ib0_1 = 0;
    ib0_2 = 0;
    ib0_3 = 0;
    ib0_4 = 0;
/* -- Ming diptest -- */

    PagesCount = PAGES_No;
    while (PagesCount > 0){
    	/* ----------------- Initializing DPM's AddressRegisters to 0x0000 ------- */
      	data16 = 0x1234; /* test data  */
      
      	/*   1. Initialize DPM_7c        */
      	VMEstatus = VISIONwrite (DPM_7c, 0x0000, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't initialize DPM_7c address register: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	/*   2. Initialize DPM_bc        */
      	VMEstatus = VISIONwrite (DPM_bc, 0x0000, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't initialize DPM_bc address register: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	/*   3. Initialize DPM_dc        */
      	VMEstatus = VISIONwrite (DPM_dc, 0x0000, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't initialize DPM_dc address register: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	/*   4. Initialize DPM_ec        */
      	VMEstatus = VISIONwrite (DPM_ec, 0x0000, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't initialize DPM_ec address register: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
     
      	/* ----------------- Disabling CDF Clocks from FAN -------------------------- */
     	data16 = 0x0000;
      	VMEstatus = VISIONwrite (FAN, 0x04, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't disable FAN Outputs: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      
      	/* ----------------- Changing to front panel Mode (1) -------------------- */
      	data16 = 0x0001;
      	/*   1. Change DPM_7c mode       */
      	VMEstatus = VISIONwrite (DPM_7c, 0x020002, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_7c to FrontPanelMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	/*   2. Change DPM_bc mode       */
      	VMEstatus = VISIONwrite (DPM_bc, 0x020002, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_bc to FrontPanelMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	/*   3. Change DPM_dc mode       */
      	VMEstatus = VISIONwrite (DPM_dc, 0x020002, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_dc to FrontPanelMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	/*   4. Change DPM_ec mode       */
      	VMEstatus = VISIONwrite (DPM_ec, 0x020002, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_ec to FrontPanelMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      
      	/* ----------------- Enabling CDF Clocks from FAN ------------------------ */
      	data16 = 0x00ff;
      	VMEstatus = VISIONwrite (FAN, 0x04, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't enable FAN Outputs: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
            
      	/* ----------------- Pause (fill DPMs with DATA) -------------------------- */
      	data16 = 0;
      	data32 = 0;
      	while (data16 != 0x8000){
	    VMEstatus = VISIONread (DPM_7c, 0x020000, 2, &VMErealbytes, &data16);
	    data32 ++;

	    if (data32 == 100000){ /* timeout */
	    	fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	    	fprintf (F_ERROR, "DPM timeout error: check STROBE signal!\n");
    	    	if (clcControlByte & 0x00000004)
	    	    printf  ("DPM timeout error: check STROBE signal!\n");
	    	break;
	    }
      	}
    
      	/* ----------------- Returning to normal Mode (0) ------------------------ */
      	data16 = 0x0000;
      	/*   1. Change DPM_7c mode       */
      	VMEstatus = VISIONwrite (DPM_7c, 0x020002, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_7c to NormalMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	/*   2. Change DPM_bc mode       */
      	VMEstatus = VISIONwrite (DPM_bc, 0x020002, 2, &VMErealbytes, &data16);
      	if(VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_bc to NormalMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	/*   3. Change DPM_dc mode       */
      	VMEstatus = VISIONwrite (DPM_dc, 0x020002, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_dc to NormalMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	/*   4. Change DPM_ec mode       */
      	VMEstatus = VISIONwrite (DPM_ec, 0x020002, 2, &VMErealbytes, &data16);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_ec to NormalMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      
      	/*------------------ Getting DATA and Making Calculations ----------------- */
      	/* Read the DATA from DPMs                                  */
      	VMEstatus = VISIONread (DPM_7c, 0x000, 128*1024, &VMErealbytes, (void *)buffer_7c);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't read from DPM_7c: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	VMEstatus = VISIONread (DPM_bc, 0x000, 128*1024, &VMErealbytes, (void *)buffer_bc);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't read from DPM_bc: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	VMEstatus = VISIONread (DPM_dc, 0x000, 128*1024, &VMErealbytes, (void *)buffer_dc);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't read from DPM_dc: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      	VMEstatus = VISIONread (DPM_ec, 0x000, 128*1024, &VMErealbytes, (void *)buffer_ec);
      	if (VMEstatus != 0){
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't read from DPM_ec: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
                                                                               /*
          oooooooooooooooooooooooooooooooooooooooooooooooo
          o                                              o
          o <<<   C L C   C A L C U L A T I O N S    >>> o
          o                                              o
          oooooooooooooooooooooooooooooooooooooooooooooooo                     */

	i1 = 0;
	i2 = 0;
	i3 = 0;
	i4 = 0;

      	/*   Initialization    */
      	NextCycle = AG = B0_found = FALSE;
      	offset = bunch_No = bucket_No = 0;
      	/*      ANALYSING BLOCK                  */
      	for (j=0;j<BufferSize;j++){/* begin block analysing */	

	    /* test for the B0 */
	    if (buffer_7c[j] & 0x08080808){

	      i1 = 0;
	      i2 = 0;
	      i3 = 0;
	      i4 = 0;

	      iflg_prb2 = 0;
	      /* ++ Ming diptest ++ */
              if ( (!(buffer_bc[j] & 0x08080808)) ||
                   (!(buffer_dc[j] & 0x08080808)) ||
                   (!(buffer_ec[j] & 0x08080808)) ) {
		/* printf  ("### B0 not find in other DPM !!! %d ###\n",j); */
                iflg_prb = 1;
		iflg_prb2 = 1;
                if (!(buffer_bc[j] & 0x08080808)) {
		  ib0_2 = 1;
                }
                if (!(buffer_dc[j] & 0x08080808)) {
		  ib0_3 = 1;
                }
                if (!(buffer_ec[j] & 0x08080808)) {
		  ib0_4 = 1;
                }

		for (ioff =-10; ioff<11; ioff++) {
		  indx = j + ioff;
		  if (indx>=0) {
		    if (buffer_bc[indx] & 0x08080808) {
		      i2 = ioff;
		    }
		    if (buffer_dc[indx] & 0x08080808) {
		      i3 = ioff;
		    }
		    if (buffer_ec[indx] & 0x08080808) {
		      i4 = ioff;
		    }
		  }
		}

	      }
	      /* -- Ming diptest -- */

	      B0_found = TRUE;
	      offset = CLC_OFFSET;
	      if (offset == 0)NextCycle = TRUE;/* NEW CYCLE */
	      /* diptest */
	      ++NcntB0[cntpage];
	    }

	    j2 = j + i2;
	    j3 = j + i3;
	    j4 = j + i4;

	    if (j2 < 0) {j2 = j;}
	    if (j3 < 0) {j3 = j;}
	    if (j4 < 0) {j4 = j;}

	    if (!B0_found) continue;

	    if (NextCycle) {              /* bunch init */
	    	bucket_No=bunch_No = 0;
	    	NextCycle = AG = FALSE;
	    }

	    if (offset > 0){ /* calculate offset */
	    	offset --;
	    	if (offset == 0)NextCycle = TRUE;/* NEW CYCLE will be next step */
	    	if (bucket_No == 0)continue; /* goto the next element */	
	    }

	    if (bucket_No == 159){
	    	/* ERROR: new cycle didn't initialize bunch_No (no B0 signal) */
	    	bucket_No=bunch_No = 0;
	    	B0_found = AG = FALSE;
	    	continue;
	    }

	    if((bucket_No==34)||(bucket_No==87)||(bucket_No==140))AG = TRUE;
	                  /* Abort GAP started     */      

	    if ((bucket_No==53)||(bucket_No==106))AG = FALSE;
	    	        /* Abort GAP finished    */

	    if (bucket_No<53)data32=bucket_No;                     /* 0 < bucket_No < 53 */
	    else if (bucket_No < 106)data32 = bucket_No - 53;      /* 53 < bucket_No < 106 */
	     	 else data32 = bucket_No - 106;                    /* 106 < bucket_No < 159 */

	    if (!(data32 % 3))BC = TRUE;              /* bunch crossing is ON  */
	    else BC = FALSE;	                      /* bunch crossing is OFF */	

	    /* DT.begin: calculate luminosity every bucket */
	    /* get DATA per bucket                         */
	    N_West=clcGetSignalsNumber(buffer_7c[j])+clcGetSignalsNumber(buffer_bc[j2]);
	    N_East=clcGetSignalsNumber(buffer_dc[j3])+clcGetSignalsNumber(buffer_ec[j4]);
    	    N_hits_Sum_159[bucket_No] += N_West + N_East;   /* total sum */
	    N_total_159[bucket_No]++;      /* TOTAL number of bucket crossings */
	    /* DT.end                                       */ 

	    if ((BC) && (!AG)) {
	      gLive=0;
	      if ((j + CLC_OFFSET_GLIVE) < BufferSize)
	      	    if (buffer_7c[j+CLC_OFFSET_GLIVE] & 0x04040404)gLive=1;
	    	if ((N_East > 0) && (N_West > 0)){ 
	    	    /* increment Sum in case of the coincedences only */
	    	    N_hits_Sum[bunch_No] += N_West + N_East;   /* total sum */
	    	    if(gLive) N_hits_Sum_GLIVE[bunch_No]+= N_West+N_East; /* sum with GLIVE */
	        }  
			/* -->Valentin (Sep 6th 2001)  ZERO CROSSING METHOD  */
	    	else N_noHits_Sum[bunch_No]++;
			/* <--Valentin; plus subsequent additions to get luminosity */
	    	N_total[bunch_No]++;      /* TOTAL number of bunch crossings */
			if(gLive)N_total_GLIVE[bunch_No]++;
	    	if (N_West*N_East != 0)N_coinc[bunch_No]++; /* Number of co-incidences */
	    	bunch_No ++;
	    }
	    bucket_No ++;
      	}
      
      	if (!B0_found)if (clcControlByte & 0x00000004)
	  printf ("-> Error: There is no B0 signal in CLC DPMs!\n");

      	/* Repeat DPM operations again to increase statistics */
      	PagesCount --;
        /* diptest */
        ++cntpage;
    }
                                                                               /*
    ooooooooooooooooooooo
    o                   o
    o <<<   B S C   >>> o
    o                   o
    ooooooooooooooooooooo                                                      */

    /*   Initialization    */
    for (i=0;i<NUM_BUNCHES;i++){      /* i -> bunch_No */      
      for (j=0;j<5;j++){              /* j -> BSC_No    */
	BSC_N_East[j][i] = BSC_N_West[j][i] = 0;
	BSC_NColl_East[j][i] = BSC_NColl_West[j][i] = 0;
      }
      /* Koji(02/07/31) --> */
      for (j=0;j<6;j++){
	BSC_NColl_coinc[j][i] = 0;
      }
      /* <-- Koji(02/07/31) */
    }

    for (i=0;i<3;i++){
      BSC_N_East_AG[i] = BSC_N_West_AG[i] = 0;
      BSC_N_East_IN[i] = BSC_N_West_IN[i] = 0;
    }
    for (i=0;i<4;i++){
      East_LOSSES_CNTR[i] = West_LOSSES_CNTR[i] = 0;
      Rbp_Loss[i] = Rbp_Coll[i] = 0;
    }
    for (i=0;i<5;i++){
      /* Koji(02/07/31) --> */
      Coinc_sp_Coll[i] = 0;
      /* <-- Koji(02/07/31) */ 
      East_Collisions[i] = West_Collisions[i] = 0;
    }

    PagesCount = BSC_PAGES_No;
    while (PagesCount > 0){

      /* ----------------- Initializing DPM's AddressRegisters to 0x0000 ------- */
      data16 = 0x1234; /* test data  */
      
      /*   1. Initialize DPM_f4        */
      VMEstatus = VISIONwrite (DPM_f4, 0x0000, 2, &VMErealbytes, &data16);
      if (VMEstatus != 0)
	{
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't initialize DPM_f4 address register: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
      
      /* ----------------- Changing to front panel Mode (1) -------------------- */
      data16 = 0x0001;
      
      /*   1. Change DPM_f4 mode       */
      VMEstatus = VISIONwrite (DPM_f4, 0x020002, 2, &VMErealbytes, &data16);
      if (VMEstatus != 0)
	{
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_f4 to FrontPanelMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
                  
      /* ----------------- Pause (fill DPMs with DATA) -------------------------- */
      data16 = 0;
      data32 = 0;
      while (data16 != 0x8000){
	VMEstatus = VISIONread (DPM_f4, 0x020000, 2, &VMErealbytes, &data16);
	data32 ++;

	if (data32 == 100000){ /* timeout */
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "DPM timeout error: check STROBE signal!\n");

	  if (clcControlByte & 0x00000004)
	    printf  ("DPM timeout error: check STROBE signal!\n");
	  break;
	}
      }
    
      /* ----------------- Returning to normal Mode (0) ------------------------ */
      data16 = 0x0000;
      
      /*   1. Change DPM_f4 mode       */
      VMEstatus = VISIONwrite (DPM_f4, 0x020002, 2, &VMErealbytes, &data16);
      if (VMEstatus != 0)
	{
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't change DPM_f4 to NormalMode: <error %d>\n", VMEstatus);
	  goto data_sending;
	}  
      
      /*------------------ Getting DATA and Making Calculations ----------------- */
      
      /* Read the DATA from DPMs                                  */
      VMEstatus = VISIONread (DPM_f4, 0x000, 128*1024, &VMErealbytes, (void *)buffer_f4);
      if (VMEstatus != 0)
	{
	  fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
	  fprintf (F_ERROR, "Couldn't read from DPM_f4: <error %d>\n", VMEstatus);
	  goto data_sending;
	}
                                                                               /*
          oooooooooooooooooooooooooooooooooooooooooooooooo
          o                                              o
          o <<<   B S C   C A L C U L A T I O N S    >>> o
          o                                              o
          oooooooooooooooooooooooooooooooooooooooooooooooo                     */

      /* Initialization */
      NextCycle = FALSE;
      offset = 0;
      B0_found = FALSE;
      
      bunch_No = 0;
      bucket_No = 0;
      AG = FALSE;
      
      /*      ANALYSING BLOCK                  */
      for (j=0;j<BufferSize;j++){
	/* block analysing begins */
	/* test for the B0 */
	if (buffer_f4[j] & 0x00080000){
	  
	  B0_found = TRUE;
	  offset = BSC_OFFSET;
	  if (offset == 0){
	    /* NEW CYCLE */
	    NextCycle = TRUE;
	  }
	}
	
	if (!B0_found)
	  continue;
	
	if (NextCycle){
	  /* bunch init */
	  bunch_No = 0;
	  bucket_No = 0;
	  AG = FALSE;
	  NextCycle = FALSE;
	}
	
	if (offset > 0){
	  /* calculate offset */
	  offset --;
	  
	  if (offset == 0){
	    /* NEW CYCLE will be next step */
	    NextCycle = TRUE;
	  }
	  
	  if (bucket_No == 0)
	    continue; /* goto the next element */	
	}
	
	if (bucket_No == 159){
	  /* ERROR: new cycle didn't initialize bunch_No (no B0 signal) */
	  bunch_No = 0;
	  bucket_No = 0;
	  AG = FALSE;
	  
	  B0_found = FALSE;
	  continue;
	}
	
	if ( (bucket_No == 34) ||
	     (bucket_No == 87) ||
	     (bucket_No == 140) ){
	  AG = TRUE;              /* Abort GAP started     */
	}      
	
	if ( (bucket_No == 53)||
	     (bucket_No == 106)){
	  AG = FALSE;	        /* Abort GAP finished    */
	}
	
	if (bucket_No < 53){
	  /* 0 < bucket_No < 53 */
	  data32 = bucket_No;
	}
	else if (bucket_No < 106){
	  /* 53 < bucket_No < 106 */
	  data32 = bucket_No - 53;
	}
	else{
	  /* 106 < bucket_No < 159 */
	  data32 = bucket_No - 106;
	}
	
	if (!(data32 % 3))
	  BC = TRUE;	        /* bunch crossing is ON  */
	else 
	  BC = FALSE;	        /* bunch crossing is OFF */	
	
	if (AG){
	  /* get DATA per bunch */	
	  event = buffer_f4[j];

	  /* Losses in AG from all 4 counters */
	  if (clcGetWestLossesNo(event)) {
	    if ((bucket_No >= 35) && (bucket_No < 52)) 
	      BSC_N_West_AG[0]++; 
	    else if ((bucket_No >= 88) && (bucket_No < 105)) 
	      BSC_N_West_AG[1]++; 
	    else if ((bucket_No >= 141) && (bucket_No < 158)) 
	      BSC_N_West_AG[2]++; 
	  }
	  if (clcGetEastLossesNo(event)) {
	    if ((bucket_No >= 35) && (bucket_No < 52)) 
	      BSC_N_East_AG[0]++;
	    else if ((bucket_No >= 88) && (bucket_No < 105)) 
	      BSC_N_East_AG[1]++; 
	    else if ((bucket_No >= 141) && (bucket_No < 158)) 
	      BSC_N_East_AG[2]++; 
	  }
	}

	if ((!BC) && (!AG)){
	  /* get DATA per bunch */	
	  event = buffer_f4[j];
	  
	  /* Losses in AG from all 4 counters */
	  if (clcGetWestLossesNo(event)) {
	    if ((bucket_No >= 1) && (bucket_No < 33)) 
	      BSC_N_West_IN[0]++; 
	    else if ((bucket_No >= 54) && (bucket_No < 86)) 
	      BSC_N_West_IN[1]++; 
	    else if ((bucket_No >= 107) && (bucket_No < 139)) 
	      BSC_N_West_IN[2]++; 
	  }
	  if (clcGetEastLossesNo(event)) {
	    if ((bucket_No >= 1) && (bucket_No < 33)) 
	      BSC_N_East_IN[0]++;
	    else if ((bucket_No >= 54) && (bucket_No < 86)) 
	      BSC_N_East_IN[1]++; 
	    else if ((bucket_No >= 107) && (bucket_No < 139)) 
	      BSC_N_East_IN[2]++; 
	  }
	}

	if ((BC) && (!AG)){
	  /* get DATA per bunch */	
	  event = buffer_f4[j];

	  /* a) look on closest cells also */
	  /*
	  if (j > 0) 
	    event |= buffer_f4[j-1];
	  if (j < (BufferSize-1))
	    event |= buffer_f4[j+1];
	  */

	  /* b) Collisions from all 4 counters */
	  if (clcGetWestCollisionsNo(event)) BSC_NColl_West[4][bunch_No]++; /* West Collisions */
	  if (clcGetEastCollisionsNo(event)) BSC_NColl_East[4][bunch_No]++; /* East Collisions */

	  /* c) Collisions per counter*/
	  mask = 0x00000001;   /* Collisions byte: |4W|3W|2W|1W|4E|3E|2E|1E| */
	  for (i=0;i<4;i++){
	    if (event & mask)
	      BSC_NColl_East[i][bunch_No] ++;  
	  
	    mask *= 2;
	  }
	  /* mask = 0x00000010 */
	  for (i=0;i<4;i++){
	    if (event & mask)
	      BSC_NColl_West[i][bunch_No] ++; 
	    
	    mask *= 2;
	  }

	  /* Koji(02/07/31) --> */
          /* One-by-One Coincidence between East and West Collisions */
	  mask = 0x00000001; 
	  for (i=0;i<4;i++){
	    if ((event & mask) && (event & mask*16))
	      BSC_NColl_coinc[i][bunch_No] ++;  

	    mask *= 2;
	  }
	  /* <-- Koji(02/07/31) */	    

	  /* d) Losses from all 4 counters */
	  if (clcGetWestLossesNo(event)) BSC_N_West[4][bunch_No]++; /* West Losses */
	  if (clcGetEastLossesNo(event)) BSC_N_East[4][bunch_No]++; /* East Losses */

	  /* e) Losses per counter*/
	  mask = 0x00000100;      /* Losses byte: |4W|3W|2W|1W|4E|3E|2E|1E| */ 
	  for (i=0;i<4;i++){
	    if (event & mask)
	      BSC_N_East[i][bunch_No] ++;  
	  
	    mask *= 2;
	  }
	  /* mask = 0x00001000 */
	  for (i=0;i<4;i++){
	    if (event & mask)
	      BSC_N_West[i][bunch_No] ++; 
	    
	    mask *= 2;
	  }

	  /* f) Co-incedences */
	  /*
	  if (BSC_N_West[4][bunch_No] * BSC_N_East[4][bunch_No] != 0)
	    BSC_N_coinc[bunch_No] ++;
	  */
          
	  if (clcGetWestCollisionsNo(event) * clcGetEastCollisionsNo(event) != 0)
	    BSC_NColl_coinc[5][bunch_No] ++;

	  /* Koji(02/07/31) --> */
	  /* Factor applied coincidence */
	  if (clcGetWestCollisionsNo(event) * clcGetEastCollisionsNo(event) != 0)
	    BSC_NColl_coinc[4][bunch_No] += 
	      ((float)(clcGetWestCollisionsNo(event)+clcGetEastCollisionsNo(event)))/2;
	  /* <-- Koji(02/07/31) */

	  bunch_No ++;
	}
	

	/* BEAM SHOWER COUNTERS - DPM LOGGING*/
	/*if (buffer_f4[j] & 0xfff7ffff){*/
	if (buffer_f4[j] & 0xfff7ffff){
	  if (clcControlByte & 0x00000080){
	    
	    fprintf (F_DPM, "DPM[%3d] = ", bucket_No);
	    
	    data32 = buffer_f4[j];
	    mask = 0x80000000;
	    for (i=0;i<32;i++){
	      if (data32 & mask){
		fprintf (F_DPM, "1");
	      }
	      else {
		fprintf (F_DPM, "0");
	      }
	      
	      if (!((i+1) % 8)){
		fprintf (F_DPM, " "); /* space between bytes */
	      }
	      
	      mask /= 2;
	    }
	    
	    fprintf (F_DPM, "\n");
	    DPMdata[bucket_No]++;
	  }
	}
	
	bucket_No ++;
      }

      if (!B0_found)
	if (clcControlByte & 0x00000004)
	  printf ("-> Error: There is no B0 signal in BSC DPM!\n");

      /* Repeat DPM operations again to increase statistics */
      PagesCount --;
    }

	/*********************************************/
	/*                                           */
	/* Final calculations after BLOCK analysis   */
	/*                                           */ 
	/*********************************************/
	 
	 for(i=0;i<METHODS;i++)for(j=0;j<2;j++)lumi2Sum[i][j]=0;
	 
    for (i=0;i<NUM_BUNCHES;i++){
      
		if (N_total[i] != 0){
			noHits_prob[i]= (float)N_noHits_Sum[i]/N_total[i];
			N_hits_Average = (float)N_hits_Sum[i] / N_total[i]; 
			N_hits_Average_GLIVE = (float)N_hits_Sum_GLIVE[i] / N_total[i]; 
      } 
      else { /* if B0 signal wasn't found we shouldn't be confused! */
			N_hits_Average = N_hits_Average_GLIVE = 0;
			noHits_prob[i]=1.0;
      }
      
		for(j=0;j<METHODS;j++)for(k=0;k<2;k++)lumiInstOld36[j][k][i] = lumi36[j][0][k][i];
      
		lumi36[0][0][0][i] = noHits_prob[i]>0.?-log(noHits_prob[i])/.020988/CRSEC:0.;
      /* ^^^ -log(P0)/(sigma*132ns*159buckets) /10^30 (units...)  ^^^ */
		lumi36[1][0][0][i] = clcGetInstLumi (N_hits_Average);
		lumi36[2][0][0][i] = ComputeMu(noHits_prob[i])/.020988/SIG_INEL;
		
		
		
		if(N_total[i])lumi36[0][0][1][i]= lumi36[0][0][0][i]*N_total_GLIVE[i]/N_total[i];
	   else lumi36[0][0][1][i]=0.;
		lumi36[1][0][1][i] = clcGetInstLumi (N_hits_Average_GLIVE);
		if(N_total[i])lumi36[2][0][1][i]= lumi36[2][0][0][i]*N_total_GLIVE[i]/N_total[i];
	   else lumi36[2][0][1][i]=0.;
		
		for(j=0;j<METHODS;j++)for(k=0;k<2;k++){
			lumi2Bucket[j][k]=clcGetTotalLumi (lumiInstOld36[j][k][i], time_old, lumi36[j][0][k][i], time32);	
			lumi2Sum[j][k]+= lumi2Bucket[j][k]; /* sum for all buckets of two consecutive times integr lumi */
			lumi36[j][1][k][i] += lumi2Bucket[j][k];
		}
      
      /* ->  Rates of hits  (NOT USED YET)             */
      if (N_total != 0)mu[i] = (float)N_coinc[i] / N_total[i];   
      else mu[i] = 0;
      /* ->  BEAM LOSSES FROM BSCs (per bunch)         */
      for (j=0;j<5;j++){
			East_Losses[j][i] = (float)BSC_N_East[j][i]*1000/(4.33*BSC_PAGES_No); /* in Hz */
			West_Losses[j][i] = (float)BSC_N_West[j][i]*1000/(4.33*BSC_PAGES_No); /* in Hz */
      }

      /* -> 5) COLLISIONS FROM BSCs         */
      for (j=0;j<5;j++){
			East_Collisions[j] += (float)BSC_NColl_East[j][i]*1000/(4.33*BSC_PAGES_No);
			West_Collisions[j] += (float)BSC_NColl_West[j][i]*1000/(4.33*BSC_PAGES_No);
      }
      
      /* -> 6) Co-incedences rate from Collisions            */
      /* Koji(02/07/31) --> */
      for (j=0;j<5;j++){
	Coinc_sp_Coll[j] += BSC_NColl_coinc[j][i]*1000/(4.33*BSC_PAGES_No); /* in Hz */
      }
      Coinc_Coll[i] = BSC_NColl_coinc[5][i]*1000/(4.33*BSC_PAGES_No); /* in Hz */
      /* <-- Koji(02/07/31) */
      
      /* -> 7) Total Losses (integrated) from BSCs       */
      east_losses_old = east_losses[i];east_losses[i] = East_Losses[4][i]; 
      EAST_TOT_LOSSES += (clcGetBSC_TotalLumi (east_losses_old, time_old, east_losses[i], time32)*1e33);
      west_losses_old = west_losses[i];west_losses[i] = West_Losses[4][i];
      WEST_TOT_LOSSES += (clcGetBSC_TotalLumi (west_losses_old, time_old, west_losses[i], time32)*1e33);

      /* -> 8) Total Collisions (integrated) from BSCs       */
      coinc_coll_old = coinc_coll[i];coinc_coll[i] = Coinc_Coll[i];
      COINC_TOT_COLL += (clcGetBSC_TotalLumi (coinc_coll_old, time_old, coinc_coll[i], time32)*1e33);
    }

    /* DT.begin: Final calculations after BLOCK analysing(per bucket) */
    for (i=0;i<MAX_BUNCHES_NO;i++){
      if (N_total_159[i] != 0)N_hits_Average = (float)N_hits_Sum_159[i] / N_total_159[i]; 
      else N_hits_Average = 0;/* if B0 signal wasn't found we shouldn't be confused! */
      lumi_159[i]   = clcGetInstLumi (N_hits_Average);
    }
    /* DT.end                                                         */

    /*   <<<<<<<   T O T A L   C O L L I S I O N S   >>>>>>>   */
    AV_INS_COINC_COLL = clcGetSum (Coinc_Coll, NUM_BUNCHES) / NUM_BUNCHES;
    AV_TOT_COINC_COLL = COINC_TOT_COLL / NUM_BUNCHES;

    /*   <<<<<<<   T O T A L   L O S S E S   >>>>>>>   */
    East_LOSSES = clcGetSum (East_Losses[4], NUM_BUNCHES);
    West_LOSSES = clcGetSum (West_Losses[4], NUM_BUNCHES);
    AV_INS_EAST_LOSS = East_LOSSES / NUM_BUNCHES;	      
    AV_INS_WEST_LOSS = West_LOSSES / NUM_BUNCHES;	      
    AV_TOT_EAST_LOSS = EAST_TOT_LOSSES / NUM_BUNCHES;  
    AV_TOT_WEST_LOSS = WEST_TOT_LOSSES / NUM_BUNCHES;  

    /*   <<<<<<<   B E A M   P O S I T I O N   >>>>>>>   */ 
    for (i=0;i<4;i++){
      East_LOSSES_CNTR[i] = clcGetSum (East_Losses[i], NUM_BUNCHES);
      West_LOSSES_CNTR[i] = clcGetSum (West_Losses[i], NUM_BUNCHES);
    }
    if (East_LOSSES != 0) {
      Rbp_Loss[0] = (East_LOSSES_CNTR[1]+East_LOSSES_CNTR[3]) / clcGetSum(East_LOSSES_CNTR, 4);
      Rbp_Loss[1] = (East_LOSSES_CNTR[2]+East_LOSSES_CNTR[3]) / clcGetSum(East_LOSSES_CNTR, 4);
    }
    if (West_LOSSES != 0) {
      Rbp_Loss[2] = (West_LOSSES_CNTR[1]+West_LOSSES_CNTR[3]) / clcGetSum(West_LOSSES_CNTR, 4);
      Rbp_Loss[3] = (West_LOSSES_CNTR[2]+West_LOSSES_CNTR[3]) / clcGetSum(West_LOSSES_CNTR, 4);
    }
    if (East_Collisions[4] != 0) {
      Rbp_Coll[0] = (East_Collisions[1]+East_Collisions[3]) / clcGetSum(East_Collisions, 4); 
      Rbp_Coll[1] = (East_Collisions[2]+East_Collisions[3]) / clcGetSum(East_Collisions, 4); 
    }
    if (West_Collisions[4] != 0) {
      Rbp_Coll[2] = (West_Collisions[1]+West_Collisions[3]) / clcGetSum(West_Collisions, 4); 
      Rbp_Coll[3] = (West_Collisions[2]+West_Collisions[3]) / clcGetSum(West_Collisions, 4); 
    }

    /*   <<<<<<<   A V E R A G E S   >>>>>>>   */
 
    /* AVERAGE Luminosities    */
    for(i=0;i<METHODS;i++)for(j=0;j<2;j++)for(k=0;k<2;k++)
	 	lumi[i][j][k] = clcGetSum(lumi36[i][j][k], NUM_BUNCHES);
    
    if (clcRunActive) 
    	Run_LUMI += lumi2Sum[METHOD][1];
    
    
    /* <<<   SUMMARY STATISTICS CALCULATION   >>> */
    counter_8hours ++;
    AV_lumi_8hours += (lumi[METHOD][0][0] - AV_lumi_8hours)/counter_8hours;
    AV_LUMI_8hours += lumi2Sum[METHOD][1];

	if (clcControlByte & 0x00000004){
      printf ("---------------------------------\n");
      printf ("Lumi_0[%d] = %6.4f E30\n", counter, lumi36[1][0][0][0]);   /*TEST!!!*/
      printf ("<Lumi>[%d] = %6.4f E30\n", counter, lumi[1][0][0]);   /*TEST!!!*/
      printf ("LUMI_0[%d] = %6.4f nb-1\n\n", counter, lumi36[1][1][0][0]);         /*TEST!!!*/

      printf ("East_LOSSES[%d] = %6.2f \n", counter, East_LOSSES);   /*TEST!!!*/
      for (i=0;i<NUM_BUNCHES;i++)if (East_Losses[4][i] != 0)
	   	printf ("      East[%2d] = %6.2f \n",i , East_Losses[4][i]);

      printf ("West_LOSSES[%d] = %6.2f \n", counter, West_LOSSES);   /*TEST!!!*/
      for (i=0;i<NUM_BUNCHES;i++)if (West_Losses[4][i] != 0)
	   	printf ("      West[%2d] = %6.2f \n",i , West_Losses[4][i]);
    }

  data_sending:
                                                                                 /*
    ooooooooooooooooooooooooooooooooooooooooo
    o                                       o
    o <<<   D A T A   S E N D I N G     >>> o
    o                                       o
    ooooooooooooooooooooooooooooooooooooooooo                                    */
 
    /* ---------------- Filling the ACNET Structures --------------------------- */
    /* oooooooooooooooo D A T A   -> T e v a t r o n ooooooooooooooooooooooooooo */
    
    /* BSC losses - proton and antiproton */
    /*  !!!!!!!!!!!!!! check this later  acnet_lum.plos.total = (float)ScalerBuffer[8]/PAUSE;
    acnet_lum.alos.total = (float)ScalerBuffer[9]/PAUSE; */

    /* Scaler Total Losses */
     East_scaler_Losses = (float)(ScalerBuffer[8]+ScalerBuffer[9]+ScalerBuffer[10]+ScalerBuffer[11])/(4*PAUSE);
     West_scaler_Losses = (float)(ScalerBuffer[12]+ScalerBuffer[13]+ScalerBuffer[14]+ScalerBuffer[15])/(4*PAUSE);

    acnet_lum.plos.total = West_LOSSES;
    acnet_lum.alos.total = East_LOSSES;

    for (i=0;i<NUM_BUNCHES;i++){
      acnet_lum.plos.bunch[i] = West_Losses[4][i];
      acnet_lum.alos.bunch[i] = East_Losses[4][i];
    }
    /* Temporarily the first 3 elements of B0ALOS (bunches) are replaced 
       with proton losses in 3 abort gaps. */
    acnet_lum.alos.bunch[0] = (float)BSC_N_West_AG[0]*1000/(4.33*BSC_PAGES_No*17);
    acnet_lum.alos.bunch[1] = (float)BSC_N_West_AG[1]*1000/(4.33*BSC_PAGES_No*17);
    acnet_lum.alos.bunch[2] = (float)BSC_N_West_AG[2]*1000/(4.33*BSC_PAGES_No*17);
    acnet_lum.alos.bunch[33] = (float)BSC_N_East_AG[0]*1000/(4.33*BSC_PAGES_No*17);
    acnet_lum.alos.bunch[34] = (float)BSC_N_East_AG[1]*1000/(4.33*BSC_PAGES_No*17);
    acnet_lum.alos.bunch[35] = (float)BSC_N_East_AG[2]*1000/(4.33*BSC_PAGES_No*17);
        
    /* luminosity - inst, total, live (GLIVE) */
    acnet_lum.luminosity.total       = (float)lumi[METHOD][0][0]; 
    acnet_lum.live_luminosity.total  = (float)lumi[METHOD][0][1];
    acnet_lum.total_luminosity.total = lumi[METHOD][1][0];
    acnet_lum.total_live_luminosity.total = lumi[METHOD][1][1];
    
    acnet_lum.luminosity_e.total       = (float)lumi[METHOD2][0][0]; 
    acnet_lum.live_luminosity_e.total  = (float)lumi[METHOD2][0][1];
    acnet_lum.total_luminosity_e.total = lumi[METHOD2][1][0];
    acnet_lum.total_live_luminosity_e.total = lumi[METHOD2][1][1];
    
    for (i=0;i<NUM_BUNCHES;i++){
      acnet_lum.luminosity.bunch[i]       = (float)lumi36[METHOD][0][0][i];
      acnet_lum.live_luminosity.bunch[i]  = (float)lumi36[METHOD][0][1][i];
      acnet_lum.total_luminosity.bunch[i] = lumi36[METHOD][1][0][i];
      acnet_lum.total_live_luminosity.bunch[i] = lumi36[METHOD][1][1][i];
      
      acnet_lum.luminosity_e.bunch[i]       = (float)lumi36[METHOD2][0][0][i];
      acnet_lum.live_luminosity_e.bunch[i]  = (float)lumi36[METHOD2][0][1][i];
      acnet_lum.total_luminosity_e.bunch[i] = lumi36[METHOD2][1][0][i];
      acnet_lum.total_live_luminosity_e.bunch[i] = lumi36[METHOD2][1][1][i];
      
    }
	 
	 /* acnet_lum.luminosity_e.bunch[0]=lumi[2][0][0];  TEST Corrected empty */
    
	 acnet_lum.clc_Z_position = (float)counter; /*TEST!!!*/
    
    /* CLC losses - for test purposes */
    for (i=0;i<16;i++){ 
      clcLosses[i] = (float)ScalerBuffer[16+i]/PAUSE;
      acnet_lum.clc_scalers[i] = clcLosses[i];
    }

    for (i=0;i<4;i++){ 
      acnet_lum.bsc_cntr_losses[i]     = West_LOSSES_CNTR[i];
      acnet_lum.bsc_cntr_losses[i+4]   = East_LOSSES_CNTR[i];
      acnet_lum.bsc_beam_position[i]   = Rbp_Loss[i];
      acnet_lum.bsc_beam_position[i+4] = Rbp_Coll[i];
    }

    for (i=0;i<3;i++){ 
      acnet_lum.losses_ag[i]   = (float)BSC_N_West_AG[i]*1000/(4.33*BSC_PAGES_No*17);
      acnet_lum.losses_ag[i+3] = (float)BSC_N_East_AG[i]*1000/(4.33*BSC_PAGES_No*17);
      acnet_lum.losses_in[i]   = (float)BSC_N_West_IN[i]*1000/(4.33*BSC_PAGES_No*22);
      acnet_lum.losses_in[i+3] = (float)BSC_N_East_IN[i]*1000/(4.33*BSC_PAGES_No*22);
    }

    /*   Write to ACNDPM  */

    VMEstatus = VISIONwrite(ACNDPM, 0x0000,(unsigned int) sizeof(acnet_lum), &VMErealbytes, voidptr);
    /*data16 = 0x1234; test data  
            VMEstatus = VISIONwrite (ACNDPM, 0x0000, 2, &VMErealbytes, &data16);*/
    if (VMEstatus != 0){
		fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
		fprintf (F_ERROR, "Couldn't initialize ACNDPM address register: <error %d>\n", VMEstatus);
    }
     
    /*------------------ Writing DATA to the file -----------------------------*/
    /* a). MAIN part */
    if ((clcDATAfloat_not_zero(&acnet_lum.plos.total, 1, 5)) || 
	(clcDATAfloat_not_zero(&acnet_lum.alos.total, 1, 5))){
            if (clcControlByte & 0x00000020){
	       /* ------------ check file size ---------- */
	       FileSize = ftell (F_DATA);
	       if (FileSize > 1000000){
		  fclose (F_DATA);
		  clcGetFileName (FileName,"rawdata/rawdata_",TIME);

		  /* save file in "rawdata" directory and open the new one */
	   	  FileStatus = copy ("/cdf/code-common/cdfonline/clc/rawdata.txt", FileName);
		  if (FileStatus == 0){
	    	     printf ("->File \"rawdata.txt\" was copied to \"rawdata\" directory.\n");
	    
	    	     /* create the new LOG-file */
		     F_DATA = fopen ("/cdf/code-common/cdfonline/clc/rawdata.txt", "w");
	    	     if (F_DATA == NULL){
	      		printf ("->ERROR: Can't create new file.\n");
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "Couldn't empty \"rawdata.txt\"\n");

			/* STOP logging in "rawdata.txt" */
			clcControlByte &= 0xffffffdf;
		     }
		     printf ("->New file \"rawdata.txt\" was created.\n");
		  }
		  else{
		      printf ("->ERROR: Can't copy file.\n");
		      fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
		      fprintf (F_ERROR, "Couldn't copy \"rawdata.txt\"\n");

		      /* STOP logging in "rawdata.txt" */
		      clcControlByte &= 0xffffffdf;

		      /* file remains closed... */
	          }
	       }
            }      
      
            if (clcControlByte & 0x00000020){
	        /* --------- print the DATA ----------- */
		fprintf (F_DATA, "\n%d/%d/%d (%02d:%02d:%02d)\n",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
		fprintf (F_DATA, "------------------------\n");
		fprintf (F_DATA, "Luminosity      = %e\n", clc_lumi_scaler);
		fprintf (F_DATA, "PLOS.Total(DPM) = %8.1f\n", acnet_lum.plos.total);
		fprintf (F_DATA, "ALOS.Total(DPM) = %8.1f\n", acnet_lum.alos.total);
                fprintf (F_DATA, "PLOS.Total(SCL) = %8.1f\n", West_scaler_Losses);
		fprintf (F_DATA, "ALOS.Total(SCL) = %8.1f\n", East_scaler_Losses);
		fprintf (F_DATA, "  Counter  = %d\n", counter);
	   }
    }
  
    /* b). CLC TEST part */    
    /* diptest */
    if (clcDATAfloat_not_zero(clcLosses, 10, 5)){
    /* if (TRUE){ */

		if (clcControlByte & 0x00000040){
			/* ------------ check file size ---------- */
			FileSize = ftell (F_CLC_DATA);
			if (FileSize > 1000000){
				fclose (F_CLC_DATA);
				clcGetFileName (FileName, "clcdata/clcdata_",TIME);
			
				/* save file in "clcdata" directory and open the new one */
				FileStatus = copy ("/cdf/code-common/cdfonline/clc/clcdata.txt", FileName);
				if (FileStatus == 0){
					printf ("->File \"clcdata.txt\" was copied to \"clcdata\" directory.\n");
	    
		 			/* create the new LOG-file */
					F_CLC_DATA = fopen ("/cdf/code-common/cdfonline/clc/clcdata.txt", "w");
					if (F_CLC_DATA == NULL){
						printf ("->ERROR: Can't create new file.\n");
						fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
						fprintf (F_ERROR, "Couldn't empty \"clcdata.txt\"\n");
					
						/* STOP logging in "clcdata.txt" */
						clcControlByte &= 0xffffffbf;
					}
					printf ("->New file \"clcdata.txt\" was created.\n");
				}
				else{
					printf ("->ERROR: Can't copy file.\n");
					fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
					fprintf (F_ERROR, "Couldn't copy \"clcdata.txt\"\n");
	    
					/* STOP logging in "clcdata.txt" */
					clcControlByte &= 0xffffffbf;

					/* file remains closed... */
				}
			}

	 	}
	 	if (clcControlByte & 0x00000040){
			/* --------- print the DATA ----------- */
			/* fprintf (F_CLC_DATA, "\n%d/%d/%d (%02d:%02d:%02d)\n",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec); */
			/* Ming(June 5th 2001)++ */
			fprintf (F_CLC_DATA, "\nVersion = %6.2f %d/%d/%d (%02d:%02d:%02d)\n",VERSION_ID, TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			/* Ming-- */
			fprintf (F_CLC_DATA, "counter  = %d\n", counter);
			fprintf (F_CLC_DATA, "------------------------\n");
	
			for (i=0;i<16;i++)
				fprintf (F_CLC_DATA, "data[%02d] = %8.1f\n",i ,clcLosses[i]);

			fprintf(F_CLC_DATA,"Average_Inst_Lumi=%10.5f\nAverage_Total_Lumi=%10.5f\n",
				lumi[1][0][0],lumi[1][1][0]);

			fprintf(F_CLC_DATA,"Average_Inst_GLIVE=%10.5f\nAverage_Total_GLIVE=%10.5f\n",
				lumi[1][0][1], lumi[1][1][1]);
			
			fprintf(F_CLC_DATA,"\nAverage_Inst(approx empty x)=%10.5f\n", lumi[0][0][0]); /* corrected empty crossing */
			fprintf(F_CLC_DATA,"\nAverage_Inst_Glive(approx empty x)=%10.5f\n", lumi[0][0][1]); /* corrected empty crossing */
			
			fprintf(F_CLC_DATA,"Average_Inst(empty x)=%10.5f\n",lumi[2][0][0]);
			fprintf(F_CLC_DATA,"Average_Tot(empty x)=%10.5f\n",lumi[2][1][0]);
			fprintf(F_CLC_DATA,"Average_Inst_Glive(empty x)=%10.5f\n",lumi[2][0][1]);
			fprintf(F_CLC_DATA,"Average_Tot_Glive(empty x)=%10.5f\n",lumi[2][1][1]);   
			fprintf(F_CLC_DATA,"\nRun_Total_Lumi=%10.5f\n", Run_LUMI);
			
                        /* fprintf(F_CLC_DATA,"%d %d %d %d %d =\n",NcntB0[0],NcntB0[1],NcntB0[2],NcntB0[3],NcntB0[4]); */
			/* fprintf(F_CLC_DATA,"%d %d %d %d %d =\n",NcntB0[5],NcntB0[6],NcntB0[7],NcntB0[8],NcntB0[9]); */
			/* fprintf(F_CLC_DATA,"%d %d %d %d %d %d =\n",N_total[0],N_total[1],N_total[2],N_total[3],N_total[4],N_total[5]); */
			/* fprintf(F_CLC_DATA,"%d %d %d %d %d %d =\n",N_total[6],N_total[7],N_total[8],N_total[9],N_total[10],N_total[11]); */
			/* fprintf(F_CLC_DATA,"%d %d %d %d %d %d =\n",N_total[12],N_total[13],N_total[14],N_total[15],N_total[16],N_total[17]); */
			/* fprintf(F_CLC_DATA,"%d %d %d %d %d %d =\n",N_total[18],N_total[19],N_total[20],N_total[21],N_total[22],N_total[23]); */
			/* fprintf(F_CLC_DATA,"%d %d %d %d %d %d =\n",N_total[24],N_total[25],N_total[26],N_total[27],N_total[28],N_total[29]); */
			/* fprintf(F_CLC_DATA,"%d %d %d %d %d %d =\n",N_total[30],N_total[31],N_total[32],N_total[33],N_total[34],N_total[35]); */
			/* for (i=0; i<10; i++) { */
			/* if (NcntB0[i]==0) { */
			/* fprintf(F_CLC_DATA,"page_no_B0\n"); */
			/* } */
			/* } */
			/* for (i=0; i<36; i++) { */
			/* if (N_total[i]==0) { */
			/* fprintf(F_CLC_DATA,"bunch_zero_cnt\n"); */
			/* } */
			/*} */

                        /* +++ Ming diptest +++ */
                        if (iflg_prb==0) {
			  fprintf(F_CLC_DATA,"%d %d %d %d noprb\n",ib0_1,ib0_2,ib0_3,ib0_4);
			}
                        if (iflg_prb!=0) {
			  fprintf(F_CLC_DATA,"%d %d %d %d yesprb\n",ib0_1,ib0_2,ib0_3,ib0_4);
			}
                        /* --- Ming diptest --- */

	 	}
	}
    
	/* c). BSC TEST part */   
	if ((East_LOSSES != 0) || (West_LOSSES != 0)){
 
		if (clcControlByte & 0x00000002){
			/* ------------ check file size ---------- */
			FileSize = ftell (F_TEST);
			if (FileSize > 1000000){
				fclose (F_TEST);
				clcGetFileName (FileName, "tstdata/test_",TIME);

				/* save file in "tstdata" directory and open the new one */
				FileStatus = copy ("/cdf/code-common/cdfonline/clc/test.txt", FileName);
				if (FileStatus == 0){
					printf ("->File \"test.txt\" was copied to \"tstdata\" directory.\n");
	    
					/* create the new LOG-file */
					F_TEST = fopen ("/cdf/code-common/cdfonline/clc/test.txt", "w");
					if (F_TEST == NULL){
						printf ("->ERROR: Can't create new file.\n");
						fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
						fprintf (F_ERROR, "Couldn't empty \"test.txt\"\n");

						/* STOP logging in "test.txt" */
						clcControlByte &= 0xfffffffd;
					}
					printf ("->New file \"test.txt\" was created.\n");
				}
				else{
					printf ("->ERROR: Can't copy file.\n");
					fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
					fprintf (F_ERROR, "Couldn't copy \"test.txt\"\n");

					/* STOP logging in "test.txt" */
					clcControlByte &= 0xfffffffd;

					/* file remains closed... */
				}
			}
		}
		if (clcControlByte & 0x00000002){
			/* --------- print the DATA ----------- */
			fprintf (F_TEST, "\n%d/%d/%d (%02d:%02d:%02d)\n",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_TEST, "counter  = %d\n", counter);
			fprintf (F_TEST, "------------------------\n");
	
			/* Koji(02/07/31) --> */
			fprintf (F_TEST, "            East_LOSSES   West_LOSSES     COLLISION (East, West, 1-by-1) \n");
			fprintf (F_TEST, "Inst. Rate:  %10.2f    %10.2f    %10.2f    %10.2f [kHz] \n", 
				 East_LOSSES/1e3, West_LOSSES/1e3, AV_INS_COINC_COLL*NUM_BUNCHES/1e3,
				 Coinc_sp_Coll[4]/1e3);
			fprintf (F_TEST, "Inte. Rate:  %10.2f    %10.2f    %10.2f [kHz] \n", 
				EAST_TOT_LOSSES/1e3, WEST_TOT_LOSSES/1e3, AV_TOT_COINC_COLL*NUM_BUNCHES/1e3);
			fprintf (F_TEST, "  Cntr  #1:  %10.2f    %10.2f    %10.2f    %10.2f     %10.2f \n", 
				East_LOSSES_CNTR[0], West_LOSSES_CNTR[0], East_Collisions[0], West_Collisions[0], 
				Coinc_sp_Coll[0]);
			fprintf (F_TEST, "  Cntr  #2:  %10.2f    %10.2f    %10.2f    %10.2f     %10.2f \n", 
				East_LOSSES_CNTR[1], West_LOSSES_CNTR[1], East_Collisions[1], West_Collisions[1], 
				Coinc_sp_Coll[1]);
			fprintf (F_TEST, "  Cntr  #3:  %10.2f    %10.2f    %10.2f    %10.2f     %10.2f \n", 
				East_LOSSES_CNTR[2], West_LOSSES_CNTR[2], East_Collisions[2], West_Collisions[2], 
				Coinc_sp_Coll[2]);
			fprintf (F_TEST, "  Cntr  #4:  %10.2f    %10.2f    %10.2f    %10.2f     %10.2f \n", 
				East_LOSSES_CNTR[3], West_LOSSES_CNTR[3], East_Collisions[3], West_Collisions[3], 
				Coinc_sp_Coll[3]);
			/* Koji (04/03/15) */
			/*
			for (i=0;i<NUM_BUNCHES;i++) {
				if (East_Losses[4][i]+West_Losses[4][i]+Coinc_Coll[i] != 0) {
					fprintf (F_TEST, "  Bunch %2d     %8.2f      %8.2f      %8.2f \n",i,
						East_Losses[4][i], West_Losses[4][i],Coinc_Coll[i]);
				}
			}
			*/
			/* <-- Koji(02/07/31) */
		}
	}

	/* d). Luminosity between bunches TEST part */   
	/* DT.begin: Luminosity per bunch */
	if (clcControlByte & 0x00000008){
		/* ------------ check file size ---------- */
		FileSize = ftell (F_LUMI_BUNCH);
		if (FileSize > 1000000){
			fclose (F_LUMI_BUNCH);
			clcGetFileName (FileName, "per_bunch/lumi_per_bunch_",TIME);
			
			/* save file in "per_bunch" directory and open the new one */
			FileStatus = copy ("/cdf/code-common/cdfonline/clc/lumi_per_bunch.txt", FileName);
			if (FileStatus == 0){
				printf ("->File \"lumi_per_bunch.txt\" was copied to \"per_bunch\" directory.\n");
	  
	   		/* create the new LOG-file */
				F_LUMI_BUNCH = fopen ("/cdf/code-common/cdfonline/clc/lumi_per_bunch.txt", "w");
				if (F_LUMI_BUNCH == NULL){
					printf ("->ERROR: Can't create new file.\n");
					fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
					fprintf (F_ERROR, "Couldn't empty \"lumi_per_bunch.txt\"\n");
	    
					/* STOP logging in "lumi_per_bunch.txt" */
					clcControlByte &= 0xfffffff7;
				}
				printf ("->New file \"lumi_per_bunch.txt\" was created.\n");
			}
			else{
				printf ("->ERROR: Can't copy file.\n");
				fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
				fprintf (F_ERROR, "Couldn't copy \"lumi_per_bunch.txt\"\n");

				/* STOP logging in "lumi_per_bunch.txt" */
				clcControlByte &= 0xfffffff7;
	  
				/* file remains closed... */
			}
		}
	}
   
	if (clcControlByte & 0x00000008){
		/* --------- print the DATA ----------- */
		fprintf (F_LUMI_BUNCH, "\n%d/%d/%d (%02d:%02d:%02d)\n",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
		fprintf (F_LUMI_BUNCH, "counter  = %d\n", counter);
		fprintf (F_LUMI_BUNCH, "------------------------\n");
		for (i=0;i<159;i++)
			fprintf (F_LUMI_BUNCH, "lumi[%3d] = %8.6f \n",i, (lumi_159[i]/1.e30));
      /* DT.end                         */ 
	}

   if (0 == (counter % 100)){
		if (clcControlByte & 0x00000004){
			printf ("Writting information to the file...\n");
			printf ("please wait...\n");
      }

		/* open and close file every 100*(7..8) seconds in order to flash buffer */
		fclose (F_ERROR);
		F_ERROR = fopen ("/cdf/code-common/cdfonline/clc/s_error.log", "a");

		fclose (F_DATA);
		if (clcControlByte & 0x00000020)
			F_DATA = fopen ("/cdf/code-common/cdfonline/clc/rawdata.txt", "a");
      
		fclose (F_CLC_DATA);
		if (clcControlByte & 0x00000040)
			F_CLC_DATA = fopen ("/cdf/code-common/cdfonline/clc/clcdata.txt", "a");
      
		fclose (F_TEST);
		if (clcControlByte & 0x00000002)
			F_TEST = fopen ("/cdf/code-common/cdfonline/clc/test.txt", "a");

		fclose (F_LUMI_BUNCH);
		if (clcControlByte & 0x00000008)
			F_LUMI_BUNCH = fopen ("/cdf/code-common/cdfonline/clc/lumi_per_bunch.txt", "a");
      

		/* DPM data -> for CLC_OFFSET definition etc... */
		fclose (F_DPM);
		if (clcControlByte & 0x00000080){
			F_DPM = fopen ("/cdf/code-common/cdfonline/clc/DPMdata.txt", "a");
	
			fprintf (F_DPM, "\n%d/%d/%d (%02d:%02d:%02d)\n",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_DPM, "------------------------\n");
			fprintf (F_DPM, "counter = %d\n", counter);
			for (i=0;i<MAX_BUNCHES_NO;i++)
			if (DPMdata[i] != 0){
				fprintf (F_DPM, "DATA[%3d] = %d\n",i, DPMdata[i]);
				DPMdata[i] = 0;
			}
	
			fprintf (F_DPM, "ooooooooooooooooooooooooooooooooooooo\n\n");
			fclose (F_DPM);
			F_DPM = fopen ("/cdf/code-common/cdfonline/clc/DPMdata.txt", "a");

			/* ------------ check file size ---------- */
			FileSize = ftell (F_DPM);
			if (FileSize > 1000000){
				fclose (F_DPM);
				clcGetFileName (FileName, "dpmdata/DPMdata_",TIME);

				/* save file in "dpmdata" directory and open the new one */
				FileStatus = copy ("/cdf/code-common/cdfonline/clc/DPMdata.txt", FileName);
				if (FileStatus == 0){
					printf ("->File \"DPMdata.txt\" was copied to \"dpmdata\" directory.\n");
	    
					/* create the new LOG-file */
					F_DPM = fopen ("/cdf/code-common/cdfonline/clc/DPMdata.txt", "w");
					if (F_DPM == NULL){
						printf ("->ERROR: Can't create new file.\n");
						fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
						fprintf (F_ERROR, "Couldn't empty \"DPMdata.txt\"\n");

						/* STOP logging in "DPMdata.txt" */
						clcControlByte &= 0xffffff7f;
					}
					printf ("->New file \"DPMdata.txt\" was created.\n");
				}
				else{
					printf ("->ERROR: Can't copy file.\n");
					fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> FILE error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
					fprintf (F_ERROR, "Couldn't copy \"DPMdata.txt\"\n");

					/* STOP logging in "DPMdata.txt" */
					clcControlByte &= 0xffffff7f;

					/* file remains closed... */
				}
			}
		}

		if (clcControlByte & 0x00000004)
			printf ("          ...done!\n");
	}
    
	/*------------------ Complete and send Message -----------------------------*/
	/* ooooooooooooooooo D A T A   -> C D F  D A Q oooooooooooooooooooooooooooo */
	if (CanSendMessage){
                                                                               /*
      ooooooooooooooooooooooooooooooo
      o                             o
      o <<<   C L C   P A R T   >>> o
      o                             o
      ooooooooooooooooooooooooooooooo                                          */

		/*  0. Truncate all previous fields (if any)   */
		if (!TipcMsgSetNumFields (msg, 0)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgSetNumFields failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}
      
		/*  1. Append L_inst with GLIVE  */
		for (i=0;i<NUM_BUNCHES;i++)BUNCH32[i]= clcTransformFloat32 (lumi36[METHOD][0][1][i]);
      
		if (!TipcMsgAppendInt4Array (msg, BUNCH32, NUM_BUNCHES)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2Array failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
	   	goto loop_exit; 
		}
      
		/*  2. Append L_total with GLIVE  */
		for (i=0;i<NUM_BUNCHES;i++)BUNCH32[i]= clcTransformFloat32 (lumi36[METHOD][1][1][i]);
      
		if (!TipcMsgAppendInt4Array (msg, BUNCH32, NUM_BUNCHES)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2Array failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}
		/*  3. Append L_inst (no GLIVE) */
		for (i=0;i<NUM_BUNCHES;i++)BUNCH32[i]= clcTransformFloat32 (lumi36[METHOD][0][0][i]);
      
		if (!TipcMsgAppendInt4Array (msg, BUNCH32, NUM_BUNCHES)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2Array failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}
      /*  4. Append L_total (no GLIVE) */
		for (i=0;i<NUM_BUNCHES;i++)BUNCH32[i]= clcTransformFloat32 (lumi36[METHOD][1][0][i]);
      /* TEST FEB 06 2003 BUNCH32[0]=1111; */
		/* TEST FEB 06 */
		if (!TipcMsgAppendInt4Array (msg, BUNCH32, NUM_BUNCHES)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2Array failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}    
		/*  5. Append <L_inst> with GLIVE  */
		AVERAGE32 = clcTransformFloat32 (lumi[METHOD][0][1]); 
			/* TEST FEB 06 2003 AVERAGE32=3333;*/
		if (!TipcMsgAppendInt4 (msg, AVERAGE32)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
		/*  6. Append <L_total> with GLIVE  */
		AVERAGE32 = clcTransformFloat32 (lumi[METHOD][1][1]);
		if (!TipcMsgAppendInt4 (msg, AVERAGE32)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
		/*  7. Append <L_inst>  (no GLIVE)  */
		AVERAGE32 = clcTransformFloat32 (lumi[METHOD][0][0]);
		if (!TipcMsgAppendInt4 (msg, AVERAGE32)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
		/*  8. Append <L_total> (no GLIVE)  */
		AVERAGE32 = clcTransformFloat32 (lumi[METHOD][1][0]);
		if (!TipcMsgAppendInt4 (msg, AVERAGE32)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}   
		/*  9. Append <L_inst> scaler */
		AVERAGE32 = clcTransformFloat32 (clc_lumi_scaler);
		if (!TipcMsgAppendInt4 (msg, AVERAGE32)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
		/*  10. Append <L_total> scaler */
		AVERAGE32 = clcTransformFloat32 (CLC_LUMI_scaler);
		if (!TipcMsgAppendInt4 (msg, AVERAGE32)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
      
		/*  11. Append TIME stamp  */
		/*     Lo byte */
		AVERAGE = (time32 & 0x0000FFFF);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
      
		/*     Hi byte */
		data32 = time32;
		for (i=0;i<16;i++)data32 /= 2;
      
		AVERAGE = (data32 & 0x0000FFFF);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
                                                                               /*
		ooooooooooooooooooooooooooooooo
		o                             o
		o <<<   B S C   P A R T   >>> o
		o                             o
		ooooooooooooooooooooooooooooooo                                          */

		/*  1. Append Collisions from E*W BSC */
		for (i=0;i<NUM_BUNCHES;i++)BUNCH[i]= clcTransformFloat (Coinc_Coll[i]);
      
		if (!TipcMsgAppendInt2Array (msg, BUNCH, NUM_BUNCHES)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2Array failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}
		/*  2. Append Losses from BSC-W (OR) */
		for (i=0;i<NUM_BUNCHES;i++)BUNCH[i]= clcTransformFloat (West_Losses[4][i]);
      
		if (!TipcMsgAppendInt2Array (msg, BUNCH, NUM_BUNCHES)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2Array failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}
		/*  3. Append Losses from BSC-E (OR) */
		for (i=0;i<NUM_BUNCHES;i++)BUNCH[i]= clcTransformFloat (East_Losses[4][i]);
      
		if (!TipcMsgAppendInt2Array (msg, BUNCH, NUM_BUNCHES)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2Array failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}
		/*  4. Append Losses from BSC-W counters */
		for (i=0;i<NUM_BUNCHES;i++) {
			for (j=0;j<4;j++)BUNCH2[i*4+j]= clcTransformFloat (West_Losses[j][i]);
		}
		if (!TipcMsgAppendInt2Array (msg, BUNCH2, BSC_ARRAY_SIZE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2Array failed: error %ld <%s>\n", TutErrNumGet(), TutErrStrGet());	
			goto loop_exit; 
		}
		/*  5. Append Losses from BSC-E counters  */
		for (i=0;i<NUM_BUNCHES;i++) {
			for (j=0;j<4;j++)BUNCH2[i*4+j]= clcTransformFloat (East_Losses[j][i]);
		}
		if (!TipcMsgAppendInt2Array (msg, BUNCH2, BSC_ARRAY_SIZE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2Array failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}
		/*  6. Append <Coll_inst> from E*W BSC */
		AVERAGE = clcTransformFloat (AV_INS_COINC_COLL);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
		/*  7. Append <Coll_total> from E*W BSC */
		AVERAGE = clcTransformFloat (AV_TOT_COINC_COLL);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
		/*  8. Append <Loss_inst> from BSC-W (proton) */
		AVERAGE = clcTransformFloat (AV_INS_WEST_LOSS);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){	
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
		/*  9. Append <Loss_total> from BSC-W (proton) */
		AVERAGE = clcTransformFloat (AV_TOT_WEST_LOSS);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
		/*  10. Append <Loss_inst> from BSC-E (antiproton) */
		AVERAGE = clcTransformFloat (AV_INS_EAST_LOSS);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
		/*  11. Append <Loss_total> from BSC-E (antiproton) */
		AVERAGE = clcTransformFloat (AV_TOT_EAST_LOSS);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  

		/*  12. Append TIME stamp  */
		/*     Lo byte */
		AVERAGE = (time32 & 0x0000FFFF);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
      
		/*     Hi byte */
		data32 = time32/65536;
		AVERAGE = (data32 & 0x0000FFFF);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  

		/*  13. Append TIME stamp 2 */
		/*     Lo byte */
		AVERAGE = (start_time & 0x0000FFFF);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  
      
		/*     Hi byte */
		data32 = start_time/65536; /*(2^16)*/
		AVERAGE = (data32 & 0x0000FFFF);
		if (!TipcMsgAppendInt2 (msg, AVERAGE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcMsgAppendInt2 failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}  	
		/* ------------ S E N D I N G   M E S S A G E -------------------------- */
		/*  Try to send DATA via RTserver            */  
		if (!TipcSrvMsgSend (msg, TRUE)){
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcSrvMsgSend failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}
      
		/*  Flush buffered outgoing messages         */  
		if (!TipcSrvFlush()){ 
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER error: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "TipcSrvFlush failed: error %ld <%s>\n", TutErrNumGet (), TutErrStrGet());
			goto loop_exit; 
		}
	}
    
	/*  Wait for ACKNOLEDGE message        */  
	ACK_msg = TipcSrvMsgNext (1.0); 
	if (ACK_msg == NULL){
		if (CanSendMessage){
			TutOut ("->Lost Connection to 9U VME Crate...\n");	  
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "Lost Connection to 9U VME Crate...\n");	  
			fclose (F_ERROR);
			F_ERROR = fopen ("/cdf/code-common/cdfonline/clc/s_error.log", "a");
			CanSendMessage = FALSE;
   	}
	}
   else{
		TipcMsgDestroy (ACK_msg); 
		if (!CanSendMessage){
			TutOut ("->Connection to 9U VME Crate Restored!..\n");	  	    
			fprintf (F_ERROR, "%d/%d/%d (%02d:%02d:%02d) -> SENDER: ",TIME.tm_mon, TIME.tm_mday, TIME.tm_year, TIME.tm_hour, TIME.tm_min, TIME.tm_sec);
			fprintf (F_ERROR, "Connection to 9U VME Crate Restored!..\n");	  	    
			fclose (F_ERROR);
			F_ERROR = fopen ("/cdf/code-common/cdfonline/clc/s_error.log", "a");
			CanSendMessage = TRUE; 
		}
	}    
	
loop_exit:
	     
	counter++;
	/*clcPrintIntDATA(buffer_7c, 256);*/
	/*if (counter == 1)Continue = FALSE; */   /* TEST!!! Stop Loop - DEBUG MODE */
	if (clcControlByte & 0x00000001)     /* check if we should exit */
	Continue = FALSE; 
 }   /* End of Loop */
  /*-----------rdf--------------------------------------------------------------- */

exit:
	fclose (F_TEST);fclose (F_ERROR);
	fclose (F_DATA);fclose (F_CLC_DATA);
	fclose (F_DPM);fclose (F_LUMI_BUNCH);        /* DT */

	printf ("->All Files were closed.\n");

	/* Free allocated memory */
	free (buffer_7c);free (buffer_bc);
	free (buffer_dc);free (buffer_ec);free (buffer_f4);

	/*  Destroying DPM Slaves  */
	VISIONclose(DPM_7c);VISIONclose(DPM_bc);
	VISIONclose(DPM_dc);VISIONclose(DPM_ec);
	VISIONclose(DPM_f4);VISIONclose(FAN);
	VISIONclose(SCALER);VISIONclose(ACNDPM);
	printf ("->ALL DPM Slaves were closed.\n");

	/*  Destroying SmartSockets Objects  */
	TipcMsgDestroy (msg);
	TipcMtDestroy (mt);

	/* Destroying the connection to the RTserver */
	TipcSrvDestroy(T_IPC_SRV_CONN_NONE); 

	printf ("\n->PROGRAM FINISHED!\n\n");
	return (0); /*     O.K.     */
} /* clcsend */