; $Id: dcs_sumrawdatafiles.pro,v 1.7 2004/05/19 15:41:31 john Exp $
; Written by J.R.D. Copley.
;************************************************************************************************
pro dcs_sumrawdatafiles,event
;************************************************************************************************
;
compile_opt strictarr
;
; This is a procedure that reads one or more DCS raw data files, adds them together, and writes a
; new one with a user-specified name.
;
if (n_elements(event) eq 0) then begin
	group_leader=0
endif else begin
	widget_control,event.top,sensitive=0
	group_leader=event.top
	if (widget_info(event.id,find_by_uname="help") ne 0) then begin
		res=dialog_message([$
			'Sum one or more DCS raw data files','',$
			'This is a procedure that reads one or more DCS raw',$
			'data files, adds them together, and writes a new one',$
			'with a user-specified name.',$
			'','Do you wish to proceed?'],$
			/question)
		if (res eq "No") then goto,sensitize
	endif
endelse
;
inputfilenames=dialog_pickfile(path="C:\DCS data\testdata\",$
	title="Select two or more DCS raw data files",filter="*.dcs*",get_path=gpath,/multiple_files)
if (inputfilenames[0] eq "") then goto,sensitize
inputfilenames=inputfilenames[sort(inputfilenames)]
nfiles=n_elements(inputfilenames)
if (nfiles eq 1) then begin
	res=dialog_message("You must select at least two input files")
	goto,sensitize
endif
;
; Construct suggested output file name.
root=file_basename(inputfilenames[0])
outfile=strmid(root,0,8)+strmid(root,9,strpos(root,".")-9)
for k=1,nfiles-1 do begin
	root=file_basename(inputfilenames[k])
	root=strmid(root,4,4)+strmid(root,9,strpos(root,".")-9)
	outfile=outfile+"+"+root
endfor
;
repeat begin
	outputfilename=dialog_pickfile(path=gpath,file=outfile,$
		title="Select an output file name (no extension is needed)")
	if (outputfilename eq "") then goto,sensitize
	if (strmid(outputfilename,strlen(outputfilename)-7) ne ".dcs.gz") then outputfilename=outputfilename+".dcs.gz"
	if (file_test(outputfilename)) then begin
		res=dialog_message(["The file "+outputfilename+" already exists.",$
			"Are you sure you want to replace it?"],/question)
	endif else res="Yes"
endrep until (res eq "Yes")
;
inputfilenames=reverse(inputfilenames)
;
squans=["duration","nframes"]
vquans=["detsum","grandsum","histodata","histohigh","repeats","resets","timsum","totals"]
ns=n_elements(squans)
nv=n_elements(vquans)
ps=ptrarr(ns,/allocate_heap)
pv=ptrarr(nv,/allocate_heap)
;
res=dialog_message($
	['Scalars to be summed are as follows:',squans,'',$
	 'Vectors to be summed are as follows:',vquans,'',$
	 'All other variables will be derived from the earliest file.',$
	 '','N.B. AT THE TIME OF WRITING IT IS NOT CLEAR THAT "err" IS PROPERLY COMPUTED.'],$
	 /information)
;
nofirstline=0
omithisto=0
;
for k=0,nfiles-1 do begin
;
	inputfilename=inputfilenames[k]
	firstfile=(k eq 0)
	lastfile=(k eq nfiles-1)
;
; Determine whether or not input file is compressed.
	ending=strmid(inputfilename,2,3,/reverse_offset)
	compressed=(ending eq ".gz")
;
; Read header to determine byte ordering ("endianness")
	openr,unit,inputfilename,compress=compressed,/get_lun
	header=bytarr(11)
	readu,unit,header
	free_lun,unit
;
; When opening the file take into account the endianness of the computer that is reading
; the file and writing the modified file.
	case string(header[9]) of
		"B": begin
			openr,unitr,inputfilename,/swap_if_little_endian,compress=compressed,/get_lun
			if (lastfile) then openw,unitw,outputfilename,/swap_if_little_endian,compress=compressed,/get_lun
		end
		"L": begin
			openr,unitr,inputfilename,/swap_if_big_endian,compress=compressed,/get_lun
			if (lastfile) then openw,unitw,outputfilename,/swap_if_big_endian,compress=compressed,/get_lun
		end
		else: begin
			error="Cannot determine byte ordering of file named "+inputfilename
			goto,sensitize
		end
	endcase
;
	readu,unitr,header
	if (lastfile) then writeu,unitw,header
;
; Define the types of some variables
	nlgth=0l
	dldocgf=bytarr(5)
	dt=0b
	padding=0b
	scalar=0.0d
	n1=0l
	n2=0l
	nstrgs=0l
	nchars=0l
;
	while (not eof(unitr)) do begin
		readu,unitr,nlgth; read name_length
		name=bytarr(nlgth)
		readu,unitr,name; read name
		readu,unitr,dldocgf; read 5 bytes of doc_length, doc, and global flag
		readu,unitr,dt; read data type
		if (lastfile) then begin
			writeu,unitw,nlgth
			writeu,unitw,name
			writeu,unitw,dldocgf
			writeu,unitw,dt
		endif
		name=string(name)
;
		case dt of
;
			1: begin; read scalar
				readu,unitr,padding
				if (lastfile) then writeu,unitw,padding
				readu,unitr,scalar
				index=where(name eq squans)
				index=index[0]
				if (index ge 0) then begin
					if (firstfile) then begin
						*ps[index]=scalar
					endif else begin
						*ps[index]=*ps[index]+scalar
					endelse
					if (lastfile) then writeu,unitw,*ps[index]
				endif else begin
					if (lastfile) then writeu,unitw,scalar
				endelse
			end
;
		2: begin; read matrix
				readu,unitr,n1,n2
				if (lastfile) then writeu,unitw,n1,n2
				readu,unitr,padding
				if (lastfile) then writeu,unitw,padding
				nhi=n1>n2
				nlo=n1<n2
				if (nlo eq 1) then data=dblarr(nhi) else data=dblarr(n1,n2)
				readu,unitr,data
				index=where(name eq vquans)
				index=index[0]
				if (index ge 0) then begin
					if (firstfile) then begin
						*pv[index]=data
					endif else begin
						*pv[index]=*pv[index]+data
					endelse
					if (lastfile) then writeu,unitw,*pv[index]
				endif else begin
					if (lastfile) then writeu,unitw,data
				endelse
			end
;
			5: begin; read string
				readu,unitr,nchars; read number of characters in string element
				if (lastfile) then writeu,unitw,nchars
				if (nchars gt 0) then begin
					str=bytarr(nchars)
					readu,unitr,str; read string element
					if (lastfile) then writeu,unitw,str
				endif
			end
;
			7: begin; read string array
				readu,unitr,nstrgs; read number of strings in array
				if (lastfile) then writeu,unitw,nstrgs
				strarray=strarr(nstrgs)
				for j=1,nstrgs do begin
					readu,unitr,nchars; read number of characters in string element
					if (lastfile) then writeu,unitw,nchars
					str=bytarr(nchars)
					readu,unitr,str; read string element
					if (lastfile) then writeu,unitw,str
				endfor
			end
;
			else:
		endcase
	endwhile
endfor
;
res=dialog_message(["Normal exit","","File "+outputfilename+" created."],/information)
;
sensitize:
if (n_elements(event) gt 0) then widget_control,event.top,sensitive=1
close,/all
for k=0,n_elements(ps)-1 do begin
	if (ptr_valid(ps[k])) then ptr_free,ps[k]
endfor
for k=0,n_elements(pv)-1 do begin
	if (ptr_valid(pv[k])) then ptr_free,pv[k]
endfor
;
end