esrf

Beamline Instrument Software Support
SPEC Macro documentation: [ Macro Index | BCU Home ]

#%TITLE% xia.mac
#%NAME%
#   Macros to work with XIA ( DXP ) detectors
#%DESCRIPTION%
#
#%SETUP%
# The only setup needed is done by:
#%BR% %B%xiasetup%B% [device name]
#%BR% ROIs can eventually be defined in the setup using %B%xiaroi%B%
#%BR% Counters can be disabled using %B%xiacntoff%B%
#%BR% Detector to be displayed can be set using %B%xiadisplay%B%

#%INTERNALS%

def _xia_print(type, msg) '{
	tty_cntl("md"); printf("XIA %s: ", type); tty_cntl("me")
	printf("%s\n", msg)
}'

# ---------------------------------------------------------
# Device setup / menu
# ---------------------------------------------------------

#%UU% 
#%MDESC%
#  Menu to give access to all xia functionalities
def xia '{

   if (!XIA_NBMOD) {
	_xia_print("Error", "No device configured. Use xiasetup first.")
	exit
   }

   inloop = 1
   while(inloop) {
	clscreen()
      	tty_cntl("md")
      	printf("\n\t\t<XIA DETECTOR>\n") 
      	tty_cntl("me")

	tty_cntl("md"); printf("\n\t%s", length(XIA_DEV)?XIA_DEV:"Unknown"); tty_cntl("me")
	printf(" ( %d detectors )\n\t", XIA_NBMOD);
	tty_cntl("us"); 
	str= "                 "
	for (ii=0; ii<length(XIA_DEV); ii++) str= str " "
	printf("%s", str)
	tty_cntl("ue")
	print

      	printf("\n   1. DSP configuration . . . .: ")
      	tty_cntl("md"); printf("%s", XIA_CONFIG?XIA_CONFIG:"None"); tty_cntl("me")
	print

      	printf("\n   2. ROIs . . . . . . . . . . : ")
      	tty_cntl("md");printf("%s",XIA_USINGROI?"Active":"Off");tty_cntl("me")

      	printf("\n   3. Counters (icr/ocr/lt). . : ")
      	tty_cntl("md");printf("%s",XIA_USINGCNT?"Active":"Off"); tty_cntl("me")

      	printf("\n   4. Plot detectors . . . . . :")
	str= ""
	for (i=0; i<XIA_NBMOD; i++) { if (XIA_DISPLAY[i]) { str= str sprintf(" %d", i+1) }}
	tty_cntl("md"); printf("%s", str==""?" None":str); tty_cntl("me")

	print
      	printf("\n   5. XIA on scans/ct . . . . .: ")
      	tty_cntl("md"); printf("%s",XIA_ON?"Active":"Off"); tty_cntl("me")

      	printf("\n   6. Time mode . . . . . . . .: ")
      	tty_cntl("md");printf("%s",XIA_REALTIME?"Real":"Live"); tty_cntl("me")

	printf("\n   7. External Gate . . . . . .: ")
	tty_cntl("md");printf("%s",XIA_GATE?"Off":"On"); tty_cntl("me")
	print

      	printf("\n   8. Save options . . . . . . : ")
      	printf("\n       - During scans . . . . .: ")
      	tty_cntl("md");printf("%s",XIA_SAVE?"On":"Off");tty_cntl("me")
      	printf("\n       - During ct / xiaacq . .: ")
      	tty_cntl("md");printf("%s",XIA_SAVECT?"On":"Off");tty_cntl("me")
      	if (XIA_SAVE || XIA_SAVECT ) {
          	if (XIA_DEFFILE)  {
              		printf("\n       - To standard file  . . : ")
              		tty_cntl("md");printf("\n           (%s)\n",DATAFILE);tty_cntl("me")
          	} else {
              		printf("\n       - File Prefix .  . . . .: ")
              		tty_cntl("md");printf("%s",XIA_PREFIX);tty_cntl("me")
              		printf("\n       - File Suffix . . . . . : ")
              		tty_cntl("md");printf("%s\n",XIA_SUFFIX);tty_cntl("me")
          	}
      	}

	print

      	option = getval("\n     Option ---> ",0)
      	printf("\n")
      	if (option == 0) inloop = 0 
      	else if (option == 1) {
		xiaconfigure
		input("... Press Enter ...")
	}
      	else if (option == 2) xiaroimenu
      	else if (option == 3) xiacntmenu
      	else if (option == 4) xiadisplaymenu
      	else if (option == 5) {
		if (XIA_ON) xiaoff
		else xiaon
	}
      	else if (option == 6) {
		XIA_REALTIME= XIA_REALTIME?0:1
	}
	else if (option == 7) { 
		local gate; gate= XIA_GATE?0:1; xiasetgate gate 
		input("... Press Enter ...")
	}
      	else if (option == 8) xiasavesetup
   }

}'

#%UU% 
#%MDESC% Shortcut to xia
def xiamenu 'xia'

#%UU% <0|1>
#%MDESC% Setup external gate usage
#%BR% 0 means external gate, 1 means ignore gate
#
def xiasetgate '{
	if (!$#) {
		print "xiasetgate <0|1>\n (0 means external gate, 1 means ignore gate)\n"
		exit
	}
	else {
		gate= $1
		if (esrf_io(XIA_DEV, "XiaSetGateMode", gate)==-1) {
			_xia_print("Error", "Cannot change gate mode on server")
		}
		if ((gate=esrf_io(XIA_DEV, "XiaGetGateMode"))==-1) {
			_xia_print("Error", "Cannot read gate mode")
		}
		else { XIA_GATE= gate }
		_xia_print("Gate", sprintf("%s", XIA_GATE?"Ignore":"Enable"))
	}
}'
		


#%UU% <device_name> [<timeout> <host>]
#%MDESC% Setup XIA device.
#%BR% Optionnally, timeout can be specified (default=10). Depending on the number of
#detectors used, configuration may be long and %B%xiaconfigure%B% will return
#a timeout error. For a 13 element detectors, a timeout of 20 may be good.
#%BR% %B%host%B% is the PC name where is running the device server. It is only used
#in macro %B%xiaconfigure%B% to give the list of configuration files (using ssh).
def xiasetup '{
   local timout

   global XIA_ON   
   global XIA_DEV XIA_HOST XIA_NBMOD XIA_CONFIG XIA_GATE
   global XIA_MODSIZE XIA_DATASIZE

   global XIA_REALTIME

   global XIA_PID[] XIA_DISPLAY[]

   global XIA_USINGCNT
   global XIA_USINGROI XIA_ROI[] XIA_ROIVAL[] XIA_DETDISABLE[]

   global XIA_SAVE XIA_SAVECT XIA_DEFFILE
   global XIA_PREFIX XIA_SUFFIX XIA_N
   global XIA_TOSAVE XIA_INSCAN
   global ESRF_ERR

   ESRF_ERR = -1

   XIA_MODSIZE   = 1028
   XIA_DATASIZE  = 1024
  
   if (list_n(XIA_ROI)<0) list_init XIA_ROI
 
   if (!$#) {
	XIA_DEV= getval("\n\nEnter XIA device name", XIA_DEV)
	timout= getval("Device timeout in sec.", 10)
	XIA_HOST= getval("\nXia device host computer", XIA_HOST)
   }
   else {
   	XIA_DEV= "$1"
	timout= $2?$2:10
	XIA_HOST= length("$3")?"$3":0
   }

   if ((XIA_NBMOD=esrf_io(XIA_DEV, "XiaGetNumDet"))==-1) {
	_xia_print("Error", sprintf("Cannot connect to device %s", XIA_DEV))
	XIA_NBMOD= 0
	XIA_CONFIG= 0
	xiaoff
	_xia_print("Setup", "FAILED.")
#	exit
   }
   else {
	if (esrf_io(XIA_DEV, "tcp")==-1) {
		_xia_print("Error", sprintf("Cannot set tcp mode on %s", XIA_DEV))
	}
	if (esrf_io(XIA_DEV, "timeout", timout)==-1) {
		_xia_print("Error", sprintf("Cannot set timeout on %s", XIA_DEV))
	}
   	if ((XIA_CONFIG=esrf_io(XIA_DEV, "XiaGetLastConfig"))==-1) {
		_xia_print("Error", sprintf("Cannot get configuration file from %s", XIA_DEV))
		XIA_CONFIG= 0
	}
	if ((XIA_GATE=esrf_io(XIA_DEV, "XiaGetGateMode"))==-1) {
		_xia_print("Error", sprintf("Cannot get gate mode from %s", XIA_DEV))
		XIA_GATE= 1
	}
   	if (whatis("XIA_ON") & 0x8000000 ) { xiaon }
	xia_createarrays()
   }
   if (whatis("XIA_USINGCNT") & 0x8000000) { xiacntoff }

   blmenuadd("XIA Detector","XIA Setup","xiabody","_xia_")
   setup_tail("xia")
}'

#%IU%
#%MDESC%
#  Clears up all definition for xia.
#  Called when xiasetup removed from setup file
def xiaunsetup '{
   xiaoff
   cdef("","","_xia_","delete")
}'

#%IU%
#%MDESC%
#  Called only from blmenu
def xiabody(mode) '{
   if (mode == 1 ) {
       if (XIA_ON) xiaoff
       else xiaon
   }
   if (mode == 2 ) { xia }
   return(XIA_ON?"On":"Off")
}'

#%UU%
#%MDESC%
# Activates XIA detector in scans/counts macros.
#
def xiaon '{
   local st
global ESRF_ERR

  ESRF_ERR = -1

   if ( (st=esrf_io(XIA_DEV, "XiaStatus"))==-1) {
	_xia_print("Error", sprintf("Cannot get status of device %s\n", XIA_DEV))
	xiaoff
   } else {
	_xia_print("Status", st)
       	cdef("user_getcounts",";xia_getcounts;xia_save;","xia")
       	cdef("user_prepcount",";xia_prepcount;","xia")
       	cdef("measure0",";xia_scansave;","xia")
       	cdef("measure2",";XIA_TOSAVE=0;XIA_INSCAN=0;","xia")
       	cdef("prompt_mac",";XIA_TOSAVE=0;XIA_INSCAN=0;","xia")
       	cdef("end_mac",";xia_guiclose;","xia")
       	cdef("begin_mac",";xiaon;","xia")

       	xia_guirun
       	xia_createarrays()

       	XIA_ON= 1
   }
}'

#%UU%
#%MDESC% Print device status
def xiastatus '{
    local st
    if ((st=esrf_io(XIA_DEV, "XiaStatus"))==-1) {
	_xia_print("Error", sprintf("Cannot get status of device %s\n", XIA_DEV))
    }
    else {
	_xia_print("Status", st)
    }
}'

#%UU%
#%MDESC%
#  Deactivates control of XIA detector
#  It will be called automatically when xiasetup is removed from setup
#
def xiaoff '{
   XIA_ON = 0
   cdef("","","xia","delete")
   xia_guiclose   
}'

#%IU% ()
#%MDESC% Create arrays for all detectors
#
def xia_createarrays() '{
     local size
    
     size = XIA_NBMOD * XIA_MODSIZE
     ulong array XIA_ALLDATA[size][1]
     double array XIA_LVT[XIA_NBMOD]
     double array XIA_DT[XIA_NBMOD]
     ulong array XIA_ICR[XIA_NBMOD]
     ulong array XIA_OCR[XIA_NBMOD]

     for ( i = 0;i < XIA_NBMOD; i++ ) {
         arrname = sprintf("XIA_PLOT%d",i+1)
         shared ulong array @arrname[XIA_DATASIZE][2]
         array_op("fill",@arrname[][0])
     }
}'

# ---------------------------------------------------------
# XIA Counters
# ---------------------------------------------------------

#%UU%
#%MDESC%
# Enable XIA counters
def xiacnton '{
	_xiacntset(1)
}'

#%UU%
#%MDESC%
# Disable XIA counters
def xiacntoff '{
	_xiacntset(0)
}'

#%IU% (state)
#%MDESC% Set XIA counters on (state==1) or off (state==0)
#%BR% If counters are off, all XIA counters are disabled
def _xiacntset(st) '{
	local i num di
	XIA_USINGCNT= st
	di= st?0:1
	for (i=0; i<XIA_NBMOD; i++) {
	    if ((num=cnt_num(sprintf("xicr%d", i+1))) != -1) counter_par(num, "disable", di)
	    if ((num=cnt_num(sprintf("xocr%d", i+1))) != -1) counter_par(num, "disable", di)
	    if ((num=cnt_num(sprintf("xlt%d", i+1))) != -1) counter_par(num, "disable", di)
	    if ((num=cnt_num(sprintf("xdt%d", i+1))) != -1) counter_par(num, "disable", di)
	}
}'


#%UU%
#%MDESC% Display XIA counters configured in current spec session
#
def xiacntshow '{
    tty_cntl("md"); printf("\n<XIA Counters configuration>\n"); tty_cntl("me")

    printf("\n--> XIA counters are now ");
    tty_cntl("md"); printf("%s", XIA_USINGCNT?"Active":"Off"); tty_cntl("me")    

    printf("\n\nDet.| ICR    state | OCR    state | LiveTime  st.| DeadTime  st.|")
    printf("\n    | (mne=xicrN)  | (mne=xocrN)  | (mne=xltN)   | (mne=xdtN)   |")
    printf("\n----|--------------|--------------|--------------|--------------|")
    for (i=0; i<XIA_NBMOD; i++) {
	printf("\n %2d ", i+1)
	cntnum = cnt_num(sprintf("xicr%d", i+1))
	printf("| %3s ", cntnum==-1?"no":"yes")
	if (cntnum != -1) { 
		printf("%8s ", counter_par(cntnum, "disable")?"disabled":"enabled") 
	}
	else { printf("%8s ", "-") }
	cntnum = cnt_num(sprintf("xocr%d", i+1))
	printf("| %3s ", cntnum==-1?"no":"yes")
	if (cntnum != -1) { 
		printf("%8s ", counter_par(cntnum, "disable")?"disabled":"enabled") 
	}
	else { printf("%8s ", "-") }
	cntnum  = cnt_num(sprintf("xlt%d", i+1))
	printf("| %3s ", cntnum==-1?"no":"yes")
	if (cntnum != -1) { 
		printf("%8s ", counter_par(cntnum, "disable")?"disabled":"enabled") 
	}
	else { printf("%8s ", "-") }
	cntnum= cnt_num(sprintf("xdt%d", i+1))
	printf("| %3s ", cntnum==-1?"no":"yes")
	if (cntnum != -1) {
		printf("%8s ", counter_par(cntnum, "disable")?"disabled":"enabled")
	}
	else { printf("%8s ", "-") }
	printf("|")
    }
    print
}'

#%UU%
#%MDESC% XIA counters menu.
def xiacntmenu '{
	st= yesno("\n\nUse XIA counters [xicr,xocr,xlt,xdt]", XIA_USINGCNT)
	st= st?1:0
	_xiacntset(st)
	if (XIA_USINGCNT) {
		clscreen()
		xiacntshow
		printf("\nTo be used, counters must be added in spec config\n")
		input ("\n... Press Enter ...")
	}
}'

# ---------------------------------------------------------
# FILE SAVINGS
# ---------------------------------------------------------
   
#%UU% [<scans> <ct-acq> <deffile> [<prefix>] [<suffix>]]
#%MDESC% Without any arguments, will prompt for saving settings.
#%BR% With arguments:
#%BR% %B%scans%B%: if =1, save spectra during scans, 0 otherwise
#%BR% %B%ct-acq%B%: if =1, save spectra during ct/xiaacq, 0 otherwise
#%BR% %B%deffile%B%: if =1, save to current session datafile,
#%BR%			=0, save to separate file using prefix and suffix for filename
#%BR% %B%prefix%B%: file prefix
#%BR% %B%suffix%B%: file suffix
def xiasavesetup '{
    if (!$#) {
    	XIA_SAVE= yesno("  - Save spectra during scans",XIA_SAVE)
    	XIA_SAVECT= yesno("  - After ct or xiaacq ",XIA_SAVECT)
    	if (XIA_SAVE || XIA_SAVECT) {
       		XIA_DEFFILE= yesno("  - Save to standard datafile ",0)
       		if (XIA_DEFFILE == 0) {
           		XIA_PREFIX= getval("  - Prefix for files ",XIA_PREFIX)
           		XIA_SUFFIX= getval("  - Suffix for files ",XIA_SUFFIX)
		}
       }
    }
    else {
	XIA_SAVE= $1
	XIA_SAVECT= $2
	XIA_DEFFILE= $3
	XIA_PREFIX= "$4"
	XIA_SUFFIX= "$5"
    }
}'

def xia_save '{
    if (XIA_INSCAN && XIA_TOSAVE)
       _xiasave

    if (!XIA_INSCAN && XIA_SAVECT)
       _xiasave 
}'

def xia_scansave '{
    XIA_INSCAN = 1
    if (XIA_SAVE) XIA_TOSAVE = 1
}'

def _xiasave '{
   local i

   if (!XIA_TOSAVE && !XIA_DEFFILE) {
      XIA_N++
   }

   for ( i=0;i<XIA_NBMOD;i++) {
     if (XIA_DEFFILE) {
        file = DATAFILE
     } else {
        if (XIA_TOSAVE) {
           pfx = sprintf("%s_mod%02d_%04d_",XIA_PREFIX,i+1,SCAN_N)
           file  = xia_filename(pfx,NPTS,XIA_SUFFIX)
        } else {
           pfx = sprintf("%s_mod%02d_",XIA_PREFIX,i+1)
           file  = xia_filename(pfx,XIA_N,XIA_SUFFIX)
        }
     }

     #  Save headers
     if ( !XIA_TOSAVE ) { # out of scans
        if (XIA_DEFFILE) { # to standard file
            HEADING = sprintf("xiaacq %f - mod %d",COUNT_TIME,i+1)
            SCAN_N = savestdheader(file,3,SCAN_N)
        } else {
            HEADING = sprintf("xiaacq %f - mod %d",COUNT_TIME,i+1)
            savestdheader(file,3,SCAN_N)
        }
        fprintf(file,"#@MCA %%16C\n")
        fprintf(file,"#@CHANN %d 0 %d 1\n",XIA_DATASIZE,XIA_DATASIZE-1)
        fprintf(file,"#@CALIB 0 1 0\n")
	fprintf(file,"#@DXPCFG %s\n", XIA_CONFIG)
	fprintf(file,"#@XIA %.1f %.2f %.2f\n", XIA_LVT[i], XIA_ICR[i], XIA_OCR[i])
     } else {   # during scans but not to standard file
        if (!XIA_DEFFILE) {
            HEADING = sprintf("xia-scanacq mod-%d scan-%d pt-%d",i+1,SCAN_N,NPTS)
            savestdheader(file,3,SCAN_N)
            savecntheader(file)
	    fprintf(file,"#@DXPCFG %s\n", XIA_CONFIG)
	    fprintf(file,"#@XIA %.1f %.2f %.2f\n", XIA_LVT[i], XIA_ICR[i], XIA_OCR[i])
        }
     }
     #  else scan and deffile --> no headers

     #  Save data
     arrname = sprintf("XIA_PLOT%d",i+1)
     savemcadata(file,@arrname[][1],dummy,"%16C")

     print "Saving XIA (chan." i+1 ") to " file " scan no " SCAN_N

     if (!XIA_DEFFILE) close(file)
   }
}'

#%IU%
#%MDESC%
#  Create filename using specified prefix and suffix
def xia_filename(prefix, number, suffix) '{
  local ch dig fname fmt ix

  fname = prefix suffix

  if (index(fname,"#") == 0) {
    fname = sprintf("%s%04d%s", prefix, number, suffix)
    return (fname)
  }

  while (ix = index(fname,"#")) {
    sscanf(fname,"%*[^#]#%1s%d",ch,dig)
    if (dig == 0) 
      fmt = substr (fname,1,ix-1) "%03d" substr (fname,ix+2)
    else  
      fmt = substr (fname,1,ix-1) sprintf("%%0%dd",dig) substr (fname,ix+3)

    if (ch == "p")
      fname = sprintf(fmt,NPTS)
    else if (ch == "n")
      fname = sprintf(fmt,SCAN_N)
    else if (ch == "r")
      fname = sprintf(fmt,number)
    else 
      fname = substr (fname,1,ix-1) substr (fname,ix+1)
  }    

  return (fname)
}'

# ---------------------------------------------------------
# ROIs
# ---------------------------------------------------------

#%UU%
#%MDESC% Menu to Add/Modify/Delete/Save/Load rois
#
def xiaroimenu '{
    local nb key file found
    local cmne cdet cmin cmax clvt cdt norm imne
    local cdis sdis ndis ddis ii

    XIA_USINGROI = yesno("\n\nIntegrate XIA on ROI counters",XIA_USINGROI)
    while (XIA_USINGROI) {
	nb= _xiaroishow()
	tty_move(0,nb++, \
	"\[md\]A\[se\]dd/\[md\]R\[se\]emove/\[md\]M\[se\]odify, \[md\]D\[se\]isable, \[md\]L\[se\]oad/\[md\]S\[se\]ave or \[md\]Q\[se\]uit ? ")
	while ((key=input(-1))=="") {}
	key=substr(key,1,1)
	printf("\n\n")
	if (key=="q"||key=="Q") break
	else if (key=="r"||key=="R") {
		cmne= getval("Counter mnemonic",0)
		if (cmne!="0") {
			if ((ii=index(cmne, "*"))>0) {
				norm= substr(cmne, 1, ii-1)
				for (ii=1; ii<=XIA_NBMOD; ii++) {
					list_remove(XIA_ROI, sprintf("%s%d", norm, ii))
				}
				list_remove(XIA_ROI, sprintf("%ssum", norm))
			}
			else {
				list_remove(XIA_ROI, cmne)
			}
		}
	}
	else if (key=="a"||key=="A") {
		printf("\nEnter 1-%d for single ROI on given detector number,", XIA_NBMOD)
		printf("\n       0   for a fixed SUM on all detectors,")
		printf("\n      -1   for a SUM on other ROIs [1-%d],", XIA_NBMOD)
		printf("\n      -2   for adding same ROI on all detectors [1-%d]", XIA_NBMOD)
		cdet= getval(" : ", -3)

		if (cdet>=0) { cmne= getval("\nCounter mnemonic",0) }
		else if (cdet==-1||cdet==-2) { cmne= getval("\nCounter mnemonic suffix",0) }
		else { cmne=0 }
		if (cmne) {
			if (int(cdet)!=-1) {
				cmin= getval("First channel ", 0)
				cmax= getval("Last channel  ", XIA_DATASIZE-1)
				clvt= yesno("LiveTime correction ", 0)
				cdt= yesno("DeadTime correction ", 0)
				norm= getval("Normalize by counter [0 for none]", 0)
			}
			else {
				cmin=cmax=clvt=cdt=norm=0
			}
			if (!_xiaroiadd(cmne, cdet, cmin, cmax, clvt, cdt, norm))
				input("\n... Press Enter ...")
		}
	}
	else if (key=="m"||key=="M") {
		cmne= getval("Counter mnemonic", 0)
		if ((ii=index(cmne,"*"))>0) {
			imne= substr(cmne, 1, ii-1)
			cmne= sprintf("%s1", imne)
			cmin= getval("First channel ", XIA_ROI[cmne]["min"])
			cmax= getval("Last channel  ", XIA_ROI[cmne]["max"])
			clvt= yesno("LiveTime correction ", XIA_ROI[cmne]["lvt"])
			cdt= yesno("DeadTime correction ", XIA_ROI[cmne]["dt"])
			norm= getval("Normalize by counter [0 for none]", XIA_ROI[cmne]["norm"])
			for (ii=1; ii<=XIA_NBMOD; ii++) {
				cmne= sprintf("%s%d", imne, ii)
				if (list_check(XIA_ROI, cmne)>0) {
					XIA_ROI[cmne]["min"]= cmin
					XIA_ROI[cmne]["max"]= cmax
					XIA_ROI[cmne]["lvt"]= clvt
					XIA_ROI[cmne]["dt"]= cdt
					XIA_ROI[cmne]["norm"]= norm
				}
			}
		}
		else if (list_check(XIA_ROI, cmne)>0) {
			printf ("\nROI: counter=%s , detector=%d\n", cmne, XIA_ROI[cmne]["det"])
			XIA_ROI[cmne]["min"]= getval("First channel ", XIA_ROI[cmne]["min"])
			XIA_ROI[cmne]["max"]= getval("Last channel  ", XIA_ROI[cmne]["max"])
			XIA_ROI[cmne]["lvt"]= yesno("LiveTime correction ", XIA_ROI[cmne]["lvt"])
			XIA_ROI[cmne]["dt"]= yesno("DeadTime correction ", XIA_ROI[cmne]["dt"])
			XIA_ROI[cmne]["norm"]= getval("Normalize by counter [0 for none]", XIA_ROI[cmne]["norm"])
		}
	}
	else if (key=="d"||key=="D") {
		print "Disable one detector in ROI which computes SUM:"
		sdis= ""
		for (ii=1; ii<=XIA_NBMOD; ii++) {
			if (XIA_DETDISABLE[ii]) sdis= sdis sprintf("%d ", ii)
		}
		cdis= getval("Enter Detector numbers to disable separated by space [0 for none]", sdis)
		xiadetenable 0
		if (cdis!=0) {
			ndis= split(cdis, ddis)
			for (ii=0; ii<ndis; ii++)
				xiadetdisable ddis[ii]
		}
	}
	else if (key=="s"||key=="S") {
		file= getval("Save ROIs to file [0:default file]", 0)
		if (file=="0") xiaroisave
		else xiaroisave file
		input("... Press Enter ...")
	}
	else if (key=="l"||key=="L") {
		file= getval("Load ROIs from file [0:default file]", 0)
		if (file=="0") xiaroiload
		else xiaroiload file
		input("... Press Enter ...")
	}
    }
}'

#%UU% [<filename>]
#%MDESC% Save rois in a file. If <filename> is not specified, save to the standard location
#
def xiaroisave '{
	local filename mne roi rmne

	if ($#==1) filename="$1"
	else filename= sprintf("%s/local/spec/userconf/xiaroi.def.%s", BLISSADM, USER)
	unix(sprintf("/bin/rm -f %s",filename))

	if (on(filename)==-1) {
		_xia_print("Error", sprintf("Cannot open file %s", filename))
	}
	else {
		offt
		for (roi=1; roi<=list_n(XIA_ROI); roi++) {
		    rmne=mne= list_item(XIA_ROI, roi)
		    if (XIA_ROI[mne]["det"]==-1) {
			rmne= XIA_ROI[mne]["norm"]
		    }
		    printf("%s %d %d %d %d %d %s\n", rmne, XIA_ROI[mne]["det"], \
			XIA_ROI[mne]["min"], XIA_ROI[mne]["max"], XIA_ROI[mne]["lvt"], \
			XIA_ROI[mne]["dt"], XIA_ROI[mne]["norm"])
		}
		ont; close(filename)
		_xia_print("ROI", sprintf("Saved to %s", filename))
	}
}'

#%UU% [<filename>]
#%MDESC% Load rois from a file. If <filename> is not specified, load from the standard location
#%BR% Loading rois from file will erase current roi settings.
def xiaroiload '{
	local filename line pars
	local cmne cdet cmin cmax cnorm

	if ($#==1) filename="$1"
	else filename= sprintf("%s/local/spec/userconf/xiaroi.def.%s", BLISSADM, USER)

	if (unix(sprintf("test -r %s", filename))) {
		_xia_print("Error", sprintf("Cannot find file %s", filename))
	}
	else {
		list_init XIA_ROI
		for (line=getline(filename);line!=-1;line=getline(filename)) {
			if (split(line,pars)==7) {
				_xiaroiadd(pars[0], int(pars[1]), int(pars[2]), int(pars[3]), \
						int(pars[4]), int(pars[5]), pars[6])
			}
		}
		getline(filename, "close")
		_xia_print("ROI", sprintf("%d rois have been loaded from %s", \
						list_n(XIA_ROI), filename))
	}
}'

#%UU% <roimne> <detector> <first> <last> [<lvt_corr>] [<dt_corr>] [<mne_norm>]
#%MDESC% Define a new roi. If no arguments are given, run xiaroimenu.
#%BR% Arguments are:
#%BR% %B%roimne%B%  : counter mnemonic for the roi (should be defined in spec config)
#%BR% %B%detector%B%: If >0, define the detector number,
#%BR% 			 =0, the roi is an average on all detectors of a fixed roi defined by [first:last]
#%BR% 			 =-1, add an average roi named <roimne>sum, computed using <roimne>1-N
#%BR%			 =-2, add roi on all detectors, named <roimne>1-N
#%BR% %B%first%B%   : first channel
#%BR% %B%last%B%    : last channel
#%BR% %B%lvt_corr%B%: if =1, normalize roi by livetime, 0 otherwise
#%BR% %B%dt_corr%B% : if =1, deadtime correction, 0 otherwise
#%BR% %B%mne_norm%B%: Normalize the roi using the given counter
#
def xiaroi '{
    	if (list_n(XIA_ROI)<0) list_init XIA_ROI
   	if ($#>=2) {
		_xiaroiadd("$1",$2,$3,$4,$5,$6,"$7")
		xiaroion
	}
	else {
		xiaroimenu
	}
}'

#%IU% (mne, det, min, max, lvt, dt, norm)
#%MDESC% Add one ROI definition. It returns 0 if failed, the number of created ROIs otherwise.
#%BR% See xiaroi for details about parameters
#
def _xiaroiadd(mne, cdet, min, max, lvt, dt, norm) '{
	local imne idet cmin cmax
	cmin= min>=0?min:0
	cmax= max>XIA_DATASIZE-1?XIA_DATASIZE:max
	if (cdet==-2) {
		for (idet=1; idet<=XIA_NBMOD; idet++) {
			imne= sprintf("%s%d", mne, idet)
			_xiaroiinsert(imne, idet, cmin, cmax, lvt, dt, norm)
		}
		return (XIA_NBMOD)
	}
	else if (cdet==-1) {
		imne= sprintf("%ssum", mne)
		_xiaroiinsert(imne, -1, 0, 0, 0, 0, mne)
		return (1)
	}
	else if (cdet>=0 && cdet<=XIA_NBMOD) {
		_xiaroiinsert(mne, cdet, cmin, cmax, lvt, dt, norm)
	}
	else {
		_xia_print("Error", sprintf("Wrong detector number (%d) for ROI %s", cdet, mne))
		return (0)
	}
	return (0)
}'

#%IU%
def _xiaroiinsert(mne, det, min, max, lvt, dt, norm) '{
	list_add(XIA_ROI, mne)
	XIA_ROI[mne]["det"]= det
	XIA_ROI[mne]["min"]= min
	XIA_ROI[mne]["max"]= max
	XIA_ROI[mne]["lvt"]= lvt
	XIA_ROI[mne]["dt"]= dt
	XIA_ROI[mne]["norm"]= norm
}'
	
#%UU% <detector_number>
#%MDESC% Disable detector in ROI which computes SUM on all det.
#
def xiadetdisable '{
	if ($#!=1) {
		print "USAGE: xiadetdisable <detector_number>"
		exit
	}
	XIA_DETDISABLE[$1]= 1
}'

#%UU% <dectector_number>
#%MDESC% Enable detector in ROI which computes SUM on all det.
#%BR% if <detector_number>==0: enable all configured detectors.
#
def xiadetenable '{
	if ($#!=1) {
		print "USAGE: xiadetenable <detector_number>"
		print "if <detector_number>==0, enable all detectors"
		exit
	}
	if ($1==0) {
		for (ii=1; ii<=XIA_NBMOD; ii++)
			XIA_DETDISABLE[ii]= 0
	}
	else {
		XIA_DETDISABLE[$1]= 0
	}
}'

#%UU%
#%MDESC%
#   Deactivates use of ROI counters
def xiaroioff '{
    XIA_USINGROI = 0
}'

#%UU%
#%MDESC%
#   Activates use of ROI counters
def xiaroion '{
    XIA_USINGROI = 1
}'

#%UU%
#%MDESC%
#   Shows ROI definition
def xiaroishow '_xiaroishow()'

def _xiaroishow() '{
    local module roi incfg
    local nb nroi tcnt

    if ((nroi=list_n(XIA_ROI))<0) list_init XIA_ROI

    clscreen()
    tty_move(0,1,"\[md\]<XIA ROI Definition>\[me\]")
    tty_move(0,3,sprintf("--> ROIs are now \[md\]%s\[me\]", XIA_USINGROI?"Active":"Off"))
    tty_move(0,5,"            Counter     From   To  Config  LVT  DT Norm.")

    nb= 6
    tty_move(0,nb++,"Avg all det. -------------------------------------------")
    for (roi=1; roi<=nroi; roi++) {
	if (list_getpar(XIA_ROI, roi, "det")==-1) {
		tcnt= sprintf("<%s%d-%s%d>", list_getpar(XIA_ROI,roi,"norm"), 1, \
					list_getpar(XIA_ROI,roi,"norm"), XIA_NBMOD)
		tty_move(0, nb++, \
			sprintf("\[md\]            %6s %15s   %s  %s %s %6s\[me\]", \
			list_item(XIA_ROI,roi), tcnt, \
			(cnt_num(XIA_ROI[roi])==-1)?" No":"Yes", \
			" No", " No", "-"))
	}
    }
		
    for (module=0; module<=XIA_NBMOD; module++) {
	if (module) {
	    if (XIA_DETDISABLE[module])
		tty_move(0,nb++, sprintf("Detector %2d [disable in avg] ---------------------------",module))
	    else
	        tty_move(0,nb++, sprintf("Detector %2d --------------------------------------------",module))
	}

	for (roi=1; roi<=nroi; roi++) {
		if (list_getpar(XIA_ROI,roi,"det")==module) {
			tty_move(0, nb++, \
			sprintf("\[md\]            %6s      %4d %4d    %s  %s %s %6s\[me\]", \
				list_item(XIA_ROI,roi), list_getpar(XIA_ROI,roi,"min"), \
				list_getpar(XIA_ROI,roi,"max"), (cnt_num(XIA_ROI[roi])==-1)?" No":"Yes", \
				list_getpar(XIA_ROI,roi,"lvt")?"Yes":" No", \
				list_getpar(XIA_ROI,roi,"dt")?"Yes":" No", \
				list_getpar(XIA_ROI,roi,"norm")=="0"?"-":list_getpar(XIA_ROI,roi,"norm")))
		}
	}
    }
    nb++
    return (nb)
}'

#%IU%
#%MDESC%
#
def xia_getcounts '{
   local i num
   local roinb roimne roinum roival roiuse

   xia_stop

   cdef("cleanup_once","","xia_running","delete")

   xia_readdata

   if (XIA_USINGCNT) {
  	for (i= 0;i< XIA_NBMOD;i++) {
 		if ((num=cnt_num(sprintf("xicr%d", i+1)))!=-1) S[num]= XIA_ICR[i]
 		if ((num=cnt_num(sprintf("xocr%d", i+1)))!=-1) S[num]= XIA_OCR[i]
 		if ((num=cnt_num(sprintf("xlt%d", i+1)))!=-1) S[num]= XIA_LVT[i]
 		if ((num=cnt_num(sprintf("xdt%d", i+1)))!=-1) S[num]= XIA_DT[i]
	}
   }

   roinb= list_n(XIA_ROI)
   if (XIA_USINGROI && roinb>0) {
   	for (roi=1; roi<=list_n(XIA_ROI); roi++) {
		roimne= list_item(XIA_ROI, roi)
		if (XIA_ROI[roimne]["det"]==0) {
			for (roival=roiuse=i=0; i<XIA_NBMOD; i++) {
				if (!XIA_DETDISABLE[i+1]) {
					roival+= _xiaroicalc(roimne, i)
					roiuse++
				} 
			}
			if (roiuse) { XIA_ROIVAL[roimne]= roival/roiuse }
			else { XIA_ROIVAL[roimne]= 0 }
			if ((roinum= cnt_num(roimne))!=-1)
				S[roinum]= XIA_ROIVAL[roimne]
		}
		else if (XIA_ROI[roimne]["det"]>0) {
			XIA_ROIVAL[roimne]= _xiaroicalc(roimne, XIA_ROI[roimne]["det"]-1)
			if ((roinum= cnt_num(roimne))!=-1)
				S[roinum]= XIA_ROIVAL[roimne]
		}
	}
	for (roi= 1; roi<=list_n(XIA_ROI); roi++) {
		roimne= list_item(XIA_ROI, roi)
		if (XIA_ROI[roimne]["det"]==-1) {
			for (roival=roiuse=i=0; i<XIA_NBMOD; i++) {
				if (!XIA_DETDISABLE[i+1]) {
					imne= sprintf("%s%d", XIA_ROI[roimne]["norm"], i+1)
					roival+= XIA_ROIVAL[imne]
					roiuse++
				}
			}
			if (roiuse) { XIA_ROIVAL[roimne]= roival/roiuse }
			else { XIA_ROIVAL[roimne]= 0 }
			if ((roinum= cnt_num(roimne))!=-1)
				S[roinum]= XIA_ROIVAL[roimne]
		}
	}
   }
   xia_plotit
}'

#%IU% (mne, ndet)
#%MDESC% Return the computed roi using detector number <ndet> and parameters from roi <mne>
#
def _xiaroicalc(mne, ndet) '{
	local beg end sum

	beg= ndet*XIA_MODSIZE + XIA_ROI[mne]["min"]
	end= ndet*XIA_MODSIZE + XIA_ROI[mne]["max"]
	sum= array_op("sum", XIA_ALLDATA[beg:end])

	if (XIA_ROI[mne]["lvt"] && XIA_LVT[ndet]>0) {
		sum= sum/XIA_LVT[ndet]
	}
	if (XIA_ROI[mne]["dt"] && XIA_OCR[ndet]>0) {
		sum= sum * (XIA_ICR[ndet]/XIA_OCR[ndet])
	}
	if (XIA_ROI[mne]["norm"]!="0") {
		if ((norm= cnt_num(XIA_ROI[mne]["norm"]))!=-1) {
			if (S[norm]>0) sum= sum / norm
		}
	}
	return (sum)
}'

# ---------------------------------------------------------
# TIMES
# ---------------------------------------------------------

#%UU%
#%MDESC% Reports livetime, icr, ocr, deadtime of last acquisition
#
def xiatimes '{
	local i
	_xia_print("Times", "")
	printf("\nDetector LiveTime    ICR    OCR DeadTime")
	for (i=0; i<XIA_NBMOD; i++) {
		printf("\n      %2d %8.2f %6d %6d  %5.1f %%", i+1, \
			XIA_LVT[i], XIA_ICR[i], XIA_OCR[i], XIA_DT[i])
	}
	if (XIA_NBMOD) {
		printf("\n Average %8.2f %6d %6d  %5.1f %%\n", \
			array_op("sum", XIA_LVT[0:XIA_NBMOD-1])/XIA_NBMOD,\
			array_op("sum", XIA_ICR[0:XIA_NBMOD-1])/XIA_NBMOD,\
			array_op("sum", XIA_OCR[0:XIA_NBMOD-1])/XIA_NBMOD,\
			array_op("sum", XIA_DT[0:XIA_NBMOD-1])/XIA_NBMOD)
	}
}'

# ---------------------------------------------------------
# ACQUISITION
# ---------------------------------------------------------

#%IU%
#%MDESC% Start counting on XIA. Called when xiaon at every ct or scan macro 
#
def xia_prepcount '{
    xia_start
    cdef("cleanup_once","xia_stop;","xia_running")
}'

#%IU%
#%MDESC%
#  Starts the detector
def xia_start '{
   esrf_io(XIA_DEV,"XiaStart",0)
}'

#%IU%
#%MDESC%
#   Reads data from detector
def xia_readdata '{
   esrf_io(XIA_DEV,"XiaReadAllSpectrum",XIA_ALLDATA)
   for (i=0; i<XIA_NBMOD; i++) {
       	end = (i+1) * XIA_MODSIZE
	XIA_LVT[i]= XIA_ALLDATA[end-4]/1000
	XIA_ICR[i]= XIA_ALLDATA[end-3]
	XIA_OCR[i]= XIA_ALLDATA[end-2]
	if (XIA_ICR[i]>0) 
		XIA_DT[i]= (1-XIA_OCR[i]/XIA_ICR[i])*100
	else 	XIA_DT[i]= 100.
   }
}'

#%IU%
#%MDESC%
#  Stops the detector
def xia_stop '{
   esrf_io(XIA_DEV,"XiaStop")
}'


#%UU% [ acq-time ] 
#%MDESC%
#  start acquisition and display  spectrum
#
def xiaacq '{
   local acqtime sltime

   acqtime= $1
   sltime= acqtime/10
   if (sltime<0.1) sltime= 0.1
   if (sltime>5) sltime= 5.

   for (i=0; i<XIA_NBMOD+3; i++) { print }
   cdef("cleanup_once",";_xiaacqcleanup;","_xiaacq")
   xia_stop
   COUNT_TIME= acqtime
   xia_start

   if (!acqtime) {
	sleep(sltime)
	while (1) {
		xia_readdata
		xia_plotit
		_xiaacqtimes
		sleep(sltime)
		if (_xiaacqmenu()==0) break
	}
   }
   else if (XIA_REALTIME) {
	tcount(COUNT_TIME)
	sleep(sltime)

   	while (wait(0x22)) {
      	   xia_readdata
      	   xia_plotit
	   _xiaacqtimes
      	   sleep(sltime)
      	   if (_xiaacqmenu()==0) break
   	}                                                               
   }
   else {
      sleep(sltime)
      while (1) {
	   xia_readdata
	   xia_plotit
	   avgtime= xia_avglivetime()
	   if (avgtime >= COUNT_TIME) break
	   _xiaacqtimes
	   sleep(sltime)
	   if (_xiaacqmenu()==0) break
      }
   }

   xia_stop
   cdef("","","_xiaacq","delete")
   xia_readdata
   xia_plotit
   _xiaacqtimes
   xia_save
}'

#%IU%
#%MDESC% Report livetime, ICR, OCR, deadtime during an acquisition
#
def _xiaacqtimes '{
	local cy
	cy= -3 -XIA_NBMOD
	tty_move(0, cy++, "\[md\]Detector LiveTime    ICR    OCR DeadTime\[me\]")
	for (i=0; i<XIA_NBMOD; i++) {
		tty_move(0, cy++, sprintf("      %2d %8.2f %6d %6d  %5.1f %%", i+1, \
				XIA_LVT[i], XIA_ICR[i], XIA_OCR[i], XIA_DT[i]))
	}
	tty_move(0, cy++, sprintf(" \[md\]Average\[me\] %8.2f %6d %6d  %5.1f %%\n", \
			array_op("sum", XIA_LVT[0:XIA_NBMOD-1])/XIA_NBMOD,\
			array_op("sum", XIA_ICR[0:XIA_NBMOD-1])/XIA_NBMOD,\
			array_op("sum", XIA_OCR[0:XIA_NBMOD-1])/XIA_NBMOD,\
			array_op("sum", XIA_DT[0:XIA_NBMOD-1])/XIA_NBMOD))
}'

#%IU%
#%MDESC% Cleanup macro for xiaacq
#
def _xiaacqcleanup '{
   tty_cntl("md"); printf("Acquisition Stopped."); tty_cntl("me")
   xia_stop
   cdef("","","_xiaacq","delete")
}'

#%IU%
#%MDESC%
#  Menu accessible during acquisition
#  Return 0 for a stop command, 1 otherwise
def _xiaacqmenu() '{
   local key
   tty_move(0, -1, " ... Press \"s\" to stop acquisition ...")
   key= input(-1)
   key= substr(key, 0, 1)
   if (key=="s" || key=="S") {
	tty_move(0, -1, "\[md\]Acquisition stopped.\[me\]                  ")
	return (0)
   }
   return (1)
}'

# ---------------------------------------------------------
# DXP CONFIGURATON
# ---------------------------------------------------------

#%IU%
#%MDESC% List configuration files on the host server
#
def _xialistconfig '{
	local rep
	rep= esrf_db(XIA_DEV, "XiaPath")
	if (rep!=-1) {
		printf("\nList of configuration files:")
		printf("\n(host: %s, directory: %s)\n", XIA_HOST, rep)
		if (unix(sprintf("ssh %s \"cd %s; ls -R *.sav\"", XIA_HOST, rep))) {
			_xia_print("Error", sprintf("Cannot ssh on %s", XIA_HOST))
		}
		print
	}
}'
		
#%UU%
#%MDESC%
# Download a configuration file and perform basic calibrations
def xiaconfigure '{
   local filename

   _xia_print("Configuration")
   if ($#==1) {
       filename = "$1"
   }
   else {
       if (XIA_HOST!=0) _xialistconfig
       filename = getval("  - Configuration file: ", XIA_CONFIG)
       print
   }

   printf("  - downloading %s ...\n",filename)
   if ( esrf_io(XIA_DEV, "XiaDownloadConfig", filename) ) {
      printf(" Download of configuration file aborted \n")
      exit
   }

   print ("  - internal DAC calibration ...")
   if ( esrf_io(XIA_DEV, "XiaTrkdacCalib") ) {
      printf(" Internal DAC calibration aborted \n")
      exit
   }
   print ("  - preampli reset calibration ...")
   if ( esrf_io(XIA_DEV, "XiaResetCalib") ) {
      printf(" Preampli reset calibration aborted \n")
      exit
   }
   print ("  - read channels configuration ...")
   NB_MOD = esrf_io(XIA_DEV, "XiaGetNumDet")
   if ( NB_MOD == -1 ) {
	printf(" Read channels configuration aborted \n")
	exit
   }
   XIA_CONFIG = esrf_io(XIA_DEV, "XiaGetLastConfig")
   _xia_print("Configuration", "successful !!")
}'
   
# ---------------------------------------------------------
# PLOTTING
# ---------------------------------------------------------

#%IU%
#%MDESC%
#
def xia_plotit '{

   for ( i = 0;i< XIA_NBMOD;i++) {
     arrname = sprintf("XIA_PLOT%d",i+1)
     start = i * XIA_MODSIZE
     end   = start + XIA_DATASIZE - 1
     @arrname[][1] = XIA_ALLDATA[start:end]
   }
   
   xia_guirun
}'

#%IU%
#%MDESC%
#  Close all graphical interface
def xia_guiclose '{
   local i
   for (i=0; i<XIA_NBMOD; i++) {
	xia_plotclose(i)
   }
}'
	
#%IU%
#%MDESC% Checks wether the GUI is running, otherwise starts it.
#
def xia_guirun '{
  for (i=0;i<XIA_NBMOD;i++) {
     if (XIA_DISPLAY[i]==1) {
	if (XIA_GUIRESET) xia_plotclose(i)
        if (!XIA_PID[i] || unix(sprintf("kill -0 %d 2>/dev/null",XIA_PID[i]))) {
            modno = i + 1
            XIA_PID[i] =  xia_plotopen(modno)
        }
     }
     else {
	if (XIA_PID[i]) xia_plotclose(i)
     }
  }
  XIA_GUIRESET= 0
}'

#%IU%
#%MDESC%
#   Close Graphical Interface for one channel
def xia_plotclose (modno) '{
  local file pid

  file = sprintf("/tmp/xia_xiagui_%s_%s.pid",SPEC,USER)

  if (XIA_PID[modno]) unix(sprintf("kill -9 %d 2>/dev/null",XIA_PID[modno]))
  if (!unix(sprintf("test -r %s", file))) {
	pid = getline(file)
        getline(file,"close")
	if (pid!=XIA_PID[modno]) unix(sprintf("kill -9 %d 2>/dev/null", pid))
	unix(sprintf("/bin/rm -f %s", file))
  }
  XIA_PID[modno] = 0
}'

  
#%IU%
#%MDESC% 
#   Starts the Graphical Interface for one channel
#   and returns its PID number.
def xia_plotopen (modno) '{
  local pid file guicmd setfile guiset

  file = sprintf("/tmp/xia_xiagui_%s_%s.pid",SPEC,USER)
  guiset= ""
  if (XIA_GUISETFILE!=0) {
	if (XIA_GUISETTYPE==1) {
	    setfile= sprintf("%s%d", XIA_GUISETFILE,modno)
	    if (!unix(sprintf("test -r %s", setfile))) {
		guiset= sprintf("-settings %s", setfile)
	    }
	} else {
	    if (!unix(sprintf("test -r %s", XIA_GUISETFILE))) {
		guiset= sprintf("-settings %s", XIA_GUISETFILE)
	    }
	}
  }
  guicmd= sprintf("mcatcl -ver %s -shm XIA_PLOT%d %s", SPEC, modno, guiset)

  if (!unix(sprintf("test -r %s", file))) {
    pid = getline(file)
    getline(file,"close")  
    if (pid && !unix(sprintf("kill -0 %d 2>/dev/null",pid))) {
      return(pid)
    }
  }
  unix(sprintf("/bin/rm -f %s",file))
  unix(sprintf("%s >/dev/null 2>&1 & echo \$! > %s",guicmd,file))
  pid = getline(file)
  getline(file,"close")  
  unix(sprintf("/bin/rm -f %s",file))
  return (pid)
}'

# ---------------------------------------------------------
# DISPLAY SETUP
# ---------------------------------------------------------

#%UU%
#%MDESC% Setup detectors to be displayed on GUI parameters
#
def xiadisplaymenu '{
  local inloop, option
  local file, type

  inloop = 1
  while (inloop) {
    clscreen()
    tty_cntl("md")
    printf("\n<XIA> Display Setup:\n\n")
    tty_cntl("me")

    for ( i=0;i<XIA_NBMOD;i++) {
      printf("  %2d. display detector %2d : %s\n", i+1, i+1, XIA_DISPLAY[i]?"Yes":"No")
    }
    option = getval("\n     Option ---> ", 0)
    print
    if (option == 0)   inloop = 0
    if (option > 0 && option <= XIA_NBMOD+1) 
        XIA_DISPLAY[option-1] = XIA_DISPLAY[option-1]?0:1
  }
  xia_guirun
}'

#%UU% <detector_num> <0(no)|1(yes)>
#%MDESC% Open GUI display for dectector or not.
#
def xiadisplay '{
    if ($#!=2) {
	print "USAGE: xiadisplay <chan_num> <0(off)|1(on)>"
    }
    else {
	local channum state
	channum= $1 - 1
	state= $2

	if ((channum<0)||(channum>=XIA_NBMOD)) {
	    _xia_print("Error", "Wrong detector number in xiadisplay")
	    exit
	}
	if ((state!=0)&&(state!=1)) {
	    print "xiadisplay ERROR: wrong state. Should be 1(on) or 0(off)"
	    exit
	}
	XIA_DISPLAY[channum]= state==1?1:0
	xia_guirun
    }
}'

# ---------------------------------------------------------
# AVERAGE COUNTERS
# ---------------------------------------------------------
#%IU% (array)
#%MDESC% Compute average of values in array, using only enabled detectors
def _xia_calcavg(xia_array) '{
	local ii val nb
	for (ii=val=nb=0; ii<XIA_NBMOD; ii++) {
	    if (!XIA_DETDISABLE[ii+1]) {
		val+=@xia_array[ii]
		nb++
	    }
	}
 	if (nb) { val/=nb }
	return (val)
}'

#%IU% ()
#%MDESC% Compute average livatime [s].
def xia_avglivetime() '{
	return _xia_calcavg("XIA_LVT")
}'

#%IU% ()
#%MDESC% Compute average input count rate.
def xia_avgicr() '{
 	return _xia_calcavg("XIA_ICR")
}'

#%IU% ()
#%MDESC% Compute average output count rate.
def xia_avgocr() '{
	return _xia_calcavg("XIA_OCR")
}'

#%IU% ()
#%MDESC% Calculate the average dead time [percent] as function of the input
#and the output count rate.
def xia_avgdeadt() '{
	return _xia_calcavg("XIA_DT")
}'

#%MACROS%
#%IMACROS%
#%TOC%
#%AUTHOR% E.Papillon, AB - BLISS
#$Revision: 1.6 $, $Date: 2006/02/07 13:32:47 $