; $Id: dcs_modifybeamclosedrawdatafile.pro,v 1.5 2003/11/11 16:57:02 john Exp $
; Written by J.R.D. Copley.
;************************************************************************************************
pro dcs_modifybeamclosedrawdatafile,event
;************************************************************************************************
;
compile_opt strictarr
;
; This is a procedure that reads one or more DCS raw data files that are presumed to be beam closed
; files. It then redistributes the data among the time channels according to the widths
; of the channels in the files themselves or according to the widths of the channels in a beam open
; file such as a sample file. The modified data are written to new files with the first character
; "B" (or some other character) rather than "2".
;
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([$
			'Modify one or more beam closed raw data files','',$
			'This is a procedure that reads one or more DCS raw',$
			'data files that are presumed to be beam closed',$
			'files. It then redistributes the data among',$
			'the time channels according to the widths',$
			'of the channels in the files themselves or',$
			'according to the widths of the channels in a beam open',$
			'file such as a sample file. The modified data',$
			'are written to new files with the first character',$
			'"B" (or some other character) rather than "2".',$
			'','Do you wish to proceed?'],$
			/question)
		if (res eq "No") then goto,sensitize
	endif
endelse
;
res=dialog_message(["You may use a beam open file to define a modified",$
	"set of channel widths, or you may simply redistribute intensity",$
	"within the beam closed files.","","Do you wish to use a beam open file?"],/question)
nobeamopenfile=res eq "No"
if (not nobeamopenfile) then begin
	beamopenfile=dialog_pickfile(path="C:\DCS data\testdata\",$
		title="Select a beam open file.",filter="*.dcs*")
	if (beamopenfile[0] eq "" or beamopenfile[0] eq " ") then goto,sensitize
endif
;
; 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
;
if (nobeamopenfile) then goto,done_reading
;
inputfilename=beamopenfile[0]
;
; 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": openr,unitr,inputfilename,/swap_if_little_endian,compress=compressed,/get_lun
	"L": openr,unitr,inputfilename,/swap_if_big_endian,compress=compressed,/get_lun
	else: begin
		error="Cannot determine byte ordering of file named "+inputfilename
		goto,sensitize
	end
endcase
;
readu,unitr,header
;
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
	name=string(name)
	case dt of
		1: begin; read scalar
			readu,unitr,padding
			readu,unitr,scalar
		end
		2: begin; read matrix
			readu,unitr,n1,n2
			readu,unitr,padding
			nhi=n1>n2
			nlo=n1<n2
			if (nlo eq 1) then data=dblarr(nhi) else data=dblarr(n1,n2)
			readu,unitr,data
			case name of
				"tchanlook": begin
					tchanlook=data
					tchanlook0999=reform(data[0,0:999])
					period=total(tchanlook0999)
					fraction=tchanlook0999/period
					break
				end
				else:
			endcase
			end
		5: begin; read string
			readu,unitr,nchars; read number of characters in string element
			if (nchars gt 0) then begin
				str=bytarr(nchars)
				readu,unitr,str; read string element
			endif
		end
		7: begin; read string array
			readu,unitr,nstrgs; read number of strings in array
			strarray=strarr(nstrgs)
			for j=1,nstrgs do begin
				readu,unitr,nchars; read number of characters in string element
				str=bytarr(nchars)
				readu,unitr,str; read string element
			endfor
		end
		else:
	endcase
endwhile
free_lun,unitr
;
done_reading:
;
beamclosedfiles=dialog_pickfile(path="C:\DCS data\testdata\",$
	title="Select one or more beam closed files",filter="*.dcs*",get_path=gpath,/multiple_files)
if (beamclosedfiles[0] eq "") then goto,sensitize
beamclosedfiles=beamclosedfiles[sort(beamclosedfiles)]
;
; Read each file, modify it, and write a new file.
nfiles=n_elements(beamclosedfiles)
print,"There are ",nfiles," files to be processed."
;
firstletter="B"
for k=0,nfiles-1 do begin
	inputfilename=beamclosedfiles[k]
;
	outputfilename=gpath+firstletter+strmid(inputfilename,strlen(gpath)+1)
	cancel=1
	while (file_test(outputfilename)) do begin
		res=dialog_message(["The proposed output file,",outputfilename,"already exists.",$
			"You must specify a different first letter."],/error)
		repeat begin
			dave_get_values,"Enter first letter of file","First letter",firstletter,$
				cancel=cancel,group_leader=group_leader
			if (cancel) then goto,sensitize
			if (strlen(firstletter) ne 1) then res=dialog_message("Specify a single letter.",/error)
		endrep until (strlen(firstletter) eq 1)
		outputfilename=gpath+firstletter+strmid(inputfilename,strlen(gpath)+1)
	endwhile
;
	print,"Reading "+inputfilename
;
; 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
			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
			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
	writeu,unitw,header
;
	msg="You may need to clean up files created during this session."
	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
		writeu,unitw,nlgth
		writeu,unitw,name
		writeu,unitw,dldocgf
		writeu,unitw,dt
		name=string(name)
		case dt of
			1: begin; read scalar
				readu,unitr,padding
				writeu,unitw,padding
				readu,unitr,scalar
				writeu,unitw,scalar
			end
			2: begin; read matrix
				readu,unitr,n1,n2
				writeu,unitw,n1,n2
				readu,unitr,padding
				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
				case name of
					"tchanlook": begin
						if (nobeamopenfile) then begin
							tchanlook=data
							tchanlook0999=reform(data[0,0:999])
							period=total(tchanlook0999)
							fraction=tchanlook0999/period
						endif else begin
							data=tchanlook
						endelse
					end
					"histodata": begin
						datasumovert=total(data[0:999,*],1)
						data0999=fraction#datasumovert
						data=[data0999,data[1000:1023,*]]
					end
					else:
				endcase
				writeu,unitw,data
			end
			5: begin; read string
				readu,unitr,nchars; read number of characters in string element
				writeu,unitw,nchars
				if (nchars gt 0) then begin
					str=bytarr(nchars)
					readu,unitr,str; read string element
					writeu,unitw,str
				endif
			end
			7: begin; read string array
				readu,unitr,nstrgs; read number of strings in array
				writeu,unitw,nstrgs
				strarray=strarr(nstrgs)
				for j=1,nstrgs do begin
					readu,unitr,nchars; read number of characters in string element
					writeu,unitw,nchars
					str=bytarr(nchars)
					readu,unitr,str; read string element
					writeu,unitw,str
				endfor
			end
			else:
		endcase
	endwhile
	print,"File "+outputfilename+" written."
	print,""
endfor
;
res=dialog_message(["Normal exit"],/information)
;
sensitize:
if (n_elements(event) gt 0) then widget_control,event.top,sensitive=1
close,/all
;
end