; $Id: dcs_bgd_subtract.pro,v 1.10 2005/02/14 17:50:13 azuah Exp $
; Written by J.R.D. Copley.
;************************************************************************************************
;###############################################################################
;
; LICENSE:
;  The software in this file is written by an employee of 
;  National Institute of Standards and Technology 
;  as part of the DAVE software project.
;
;  The DAVE software package is not subject to copyright protection
;  and is in the public domain. It should be considered as an
;  experimental neutron scattering data reduction, visualization, and
;  analysis system. As such, the authors assume no responsibility
;  whatsoever for its use, and make no guarantees, expressed or
;  implied, about its quality, reliability, or any other
;  characteristic. The use of certain trade names or commercial
;  products does not imply any endorsement of a particular product,
;  nor does it imply that the named product is necessarily the best
;  product for the stated purpose. We would appreciate acknowledgment
;  if the DAVE software is used or if the code in this file is
;  included in another product.
;
;###############################################################################
pro dcs_bgd_subtract,dcs_base,sumfiles,n_sumfiles,nhedet,fbdecision,logentry=logentry,$
	fbdata_qty=fbdata_qty,fbdata_err=fbdata_err,fbnormalization=fbnormalization
;************************************************************************************************
; This is a procedure to construct the time-averaged epithermal background for
; later subtraction. The quanities returned are as follows:
; fbdata_qty --- an nhedet-element array containing the total background count rate for each
; 	detector per external pulser count; the external pulser is assumed to be running at
; 	!ext_pgen Hz (see code at the end of "dcs_normalization_counts"), in which case
; 	!ext_pgen*fbdata_qty is the background count rate in counts/sec.
; fbdata_err --- the corresponding error.
; fbnormalization --- an nhedet-element array containing 1s and 0s depending whether or not
; 	the detector is masked.
;
compile_opt strictarr
;
; Possible values of decision are as follows:
; 0 - To skip the dark count subtraction click "Skip".\\
; 1 - To compute time-averaged dark counts click "Compute".\\
; 2 - To compute and save time-averaged dark counts click "Compute/save".\\
; 3 - To restore time-averaged dark counts click "Restore".\\
; 4 - To enter an overall average dark count rate click "Overall".\\
;
case fbdecision of
	0: return
	1:
	2:
	3: begin
		file=!dcs_outp_directory+!dcs_rootname+".dkc"
		if (not file_test(file)) then file=!dcs_default_root+".dkc" $
			else file=!dcs_rootname+".dkc"
		fullfilename=dialog_pickfile(filter="*.dkc",/fix_filter,$
			path=!dcs_outp_directory,/must_exist,$
			file=file,get_path=file_path,$
			title="Select the dark count background file.")
		cancel=fullfilename eq ""
		if (cancel) then fbdecision=-1
		if (not cancel) then begin
			if (strlowcase(strmid(fullfilename,3,/reverse)) ne ".dkc") then $
				fullfilename=fullfilename+".dkc"
			restore,filename=fullfilename
			logentry=logentry+string(10B)+$
				"Dark count backgrounds have been restored from file "+fullfilename
		endif
		return
	end
	4:	begin
		title="Enter beam closed count rate per detector"
		text=["Mean beam closed count rate (counts/h)","Associated error"]
		value=["",""]
		dave_get_values,group_leader=dcs_base,title,text,value,/checkall
		fbdata_qty=(fltarr(nhedet)+1)*float(value[0])/3600.0/!ext_pgen
		fbdata_err=(fltarr(nhedet)+1)*float(value[1])/3600.0/!ext_pgen
		fbnormalization=(fltarr(nhedet)+1)*1.0
		logentry=logentry+string(10B)+$
			"A mean background count rate has been supplied: ("+value[0]+"+/-"+value[1]+"/detector/h."
		return
	end
	else: begin
		x=dialog_message("Invalid value of fbdecision: "+fbdecision)
		fbdecision=5; force a return to the main menu
		return
	end
endcase
;
if (n_sumfiles[4] eq 0) then begin
	x=dialog_message("Cannot compute: no background file",/error)
	fbdecision=-1; force another decision
	return
endif

nfiles=fix(total(n_sumfiles)); this is the number of summed data files.
filename=sumfiles[nfiles-1]; this is the name of the background summed data file.
;
; Restore the background summed data file.
restore,filename=filename
;
; Fast background normalization counts for fast background run
fbnormalization=(*(*(*davePtr).dataStrPtr).specificPtr).fbnormalization_sum
;
;	Determine fast background per pulse of the external pulser, I_B-bar(d).
ch_ms=(*(*(*davePtr).dataStrPtr).specificPtr).ch_ms
ch_srdenom=(*(*(*davePtr).dataStrPtr).specificPtr).ch_srdenom
speriod=(60000000.0/ch_ms)*ch_srdenom
ngtchan0=(*(*(*davePtr).dataStrPtr).specificPtr).ngtchan0
twid=transpose((*(*(*davePtr).dataStrPtr).specificPtr).tchanlook[0,0:ngtchan0-1]*0.05)
;
nhedet=(*(*(*davePtr).dataStrPtr).specificPtr).nhedet
unitvec_nhedet=intarr(nhedet)+1
;
twidPtr=ptr_new(twid#unitvec_nhedet,/no_copy)
fbdata_qty=total((*(*(*davePtr).dataStrPtr).commonStr.histPtr).qty*(*twidPtr),1)/$
	max(fbnormalization)
fbdata_err=sqrt(fbdata_qty/max(fbnormalization))
fbnormalization=fbnormalization/max(fbnormalization)
ptr_free,twidPtr
;
logentry=logentry+string(10B)+"Dark count backgrounds have been calculated."
;
if (!debug) then $
	print,"Average counts/detector/hour = ",$
		total(fbdata_qty)/913*3600*!ext_pgen," +/- ",total(fbdata_err)/913*3600*!ext_pgen
;
if (fbdecision eq 2) then begin
	repeat begin
		file=!dcs_rootname+".dkc"
		fullfilename=dialog_pickfile(filter="*.dkc",/fix_filter,$
			path=!dcs_outp_directory,$
			file=file,get_path=file_path,$
			title="Define the dark count background file.")
		cancel=fullfilename eq ""
		compok=strcmp(file_path,!dcs_outp_directory,/fold_case)
		if (not cancel and not compok) then res=dialog_message("You may not change the directory.")
	endrep until (cancel or compok)
	if (not cancel) then begin
		if (strlowcase(strmid(fullfilename,3,/reverse)) ne ".dkc") then $
			fullfilename=fullfilename+".dkc"
		save,filename=fullfilename,fbdata_qty,fbdata_err,fbnormalization
		logentry=logentry+string(10B)+"Dark count backgrounds have been saved in file "+filename
	endif
endif
;
free_all_ptrs,davePtr
;
end