; $Id: dcs_patchrawdatafile.pro,v 1.9 2005/09/14 13:51:57 jrdcopley Exp $
; Written by J.R.D. Copley.
;************************************************************************************************
pro dcs_patchrawdatafile_getanswers_event,event
;************************************************************************************************
;
compile_opt strictarr
;
widget_control,event.top,get_uvalue=pstate
;
for k=0,n_elements((*pstate).bsc)-1 do $
	if (event.id eq (*pstate).bsc[k]) then (*pstate).sc_answer[k]=1-(*pstate).sc_answer[k]
;
for k=0,n_elements((*pstate).bvc)-1 do $
	if (event.id eq (*pstate).bvc[k]) then (*pstate).vc_answer[k]=1-(*pstate).vc_answer[k]
;
for k=0,n_elements((*pstate).bst)-1 do $
	if (event.id eq (*pstate).bst[k]) then (*pstate).st_answer[k]=1-(*pstate).st_answer[k]
;
for k=0,n_elements((*pstate).bsa)-1 do $
	if (event.id eq (*pstate).bsa[k]) then (*pstate).sa_answer[k]=1-(*pstate).sa_answer[k]
;
if (event.id eq (*pstate).bhh[0]) then (*pstate).hh_answer=1-(*pstate).hh_answer
if (event.id eq (*pstate).bhh[1]) then (*pstate).hd_answer=1-(*pstate).hd_answer
;
if (event.id eq (*pstate).done) then begin
	widget_control,event.top,/destroy
	return
endif
;
if (event.id eq (*pstate).canc) then begin
	(*pstate).hd_answer=999
	widget_control,event.top,/destroy
	return
endif
;
widget_control,event.top,set_uvalue=pstate
;
end


;************************************************************************************************
pro dcs_patchrawdatafile_getanswers,group_leader=group_leader,squans,vquans,strngs,starrs,$
	sc_answer,vc_answer,st_answer,sa_answer,hh_answer,hd_answer
;************************************************************************************************
;
compile_opt strictarr
;
nsquans=n_elements(squans)
nvquans=n_elements(vquans)
nstrngs=n_elements(strngs)
nstarrs=n_elements(starrs)
;
if (group_leader eq 0) then begin
	top=widget_base(/col)
endif else begin
	top=widget_base(/col,/modal,group_leader=group_leader)
endelse
	void=widget_label(top,value='Check the variables you wish to modify')
	tlb=widget_base(top,/row)
		basesc=widget_base(tlb,/col,/frame)
			void=widget_label(basesc,value='SCALARS')
			buttsc=widget_base(basesc,/nonexclusive,/col)
				bsc=lonarr(nsquans)
				for k=0,nsquans-1 do bsc[k]=widget_button(buttsc,value=squans[k])
		basevc=widget_base(tlb,/col,/frame)
			void=widget_label(basevc,value='VECTORS')
			buttvc=widget_base(basevc,/nonexclusive,/col)
				bvc=lonarr(nvquans)
				for k=0,nvquans-1 do bvc[k]=widget_button(buttvc,value=vquans[k])
		basest=widget_base(tlb,/col,/frame)
			void=widget_label(basest,value='STRINGS')
			buttst=widget_base(basest,/nonexclusive,/col)
				bst=lonarr(nstrngs)
				for k=0,nstrngs-1 do bst[k]=widget_button(buttst,value=strngs[k])
		basesa=widget_base(tlb,/col,/frame)
			void=widget_label(basesa,value='STRING ARRAYS')
			buttsa=widget_base(basesa,/nonexclusive,/col)
				bsa=lonarr(nstarrs)
				for k=0,nstarrs-1 do bsa[k]=widget_button(buttsa,value=starrs[k])
		basehh=widget_base(tlb,/col,/frame)
			void=widget_label(basehh,value='ARRAYS')
			butthh=widget_base(basehh,/nonexclusive,/col)
				bhh=lonarr(2)
				bhh[0]=widget_button(butthh,value='histohigh')
				bhh[1]=widget_button(butthh,value='histodata')
	done=widget_button(top,value='Done')
	canc=widget_button(top,value='Cancel')
centertlb,top
widget_control,top,/realize
state={done:done,$
	canc:canc,$
	bsc:bsc,$
	bvc:bvc,$
	bst:bst,$
	bsa:bsa,$
	bhh:bhh,$
	sc_answer:intarr(nsquans),$
	vc_answer:intarr(nvquans),$
	st_answer:intarr(nstrngs),$
	sa_answer:intarr(nstarrs),$
	hh_answer:0,$
	hd_answer:0}
	pstate=ptr_new(state)
widget_control,top,set_uvalue=pstate
xmanager,'dcs_patchrawdatafile_getanswers',top
sc_answer=(*pstate).sc_answer
vc_answer=(*pstate).vc_answer
st_answer=(*pstate).st_answer
sa_answer=(*pstate).sa_answer
hh_answer=(*pstate).hh_answer
hd_answer=(*pstate).hd_answer
ptr_free,pstate
;
end


;************************************************************************************************
pro dcs_patchrawdatafile,event
;************************************************************************************************
;
compile_opt strictarr
;
; This is a procedure that reads a DCS raw data file, patches it, and writes a new one
; with the first character "P" (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([$
			'Patch a DCS raw data file','',$
			'This is a procedure that reads a DCS raw data file,',$
			'patches it, and writes a new one with the first',$
			'character "P" (or some other character) rather than "2".',$
			'','Do you wish to proceed?'],$
			/question)
		if (res eq "No") then goto,sensitize
	endif
endelse
;
inputfilename=dialog_pickfile(path="C:\DCS data\testdata\",$
	title="Select a DCS raw data file",filter="*.dcs*",get_path=gpath)
if (inputfilename eq "") then goto,sensitize
;
firstletter="P"
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
;
nofirstline=0
;
; Determine whether file was created before or after Nov 1, 2003.
pos=strpos(inputfilename,'.dcs')
fname=strmid(inputfilename,0,pos)
pos=strpos(fname,'_',/reverse_search)
fname=strmid(fname,pos-8,8)
afterNov2003=(fname gt 20031101)
;
; Define scalar quantities
squans=["ch_ms","ch_res","ch_srdenom","ch_srmode","ch_wl","tsdmin",$
	"coll_mean","coll_amp"]
;
; Define vector quantities
vquans=["ch_input","ch_delay","ch_phase"]
;
; Define string quantities
strngs=['comments']
if (afterNov2003) then strngs=[strngs,'user']
;
; Define string array quantities
starrs=['highsource']
;
dcs_patchrawdatafile_getanswers,group_leader=group_leader,squans,vquans,strngs,starrs,$
	sc_answer,vc_answer,st_answer,sa_answer,hh_answer,hd_answer
if (hd_answer eq 999) then goto,sensitize
;
omithisto=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": 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
;
; 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
	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
			;
			; Patchable scalars
			index=where(name eq squans,cnt)
			if (cnt eq 1) then begin
				if (sc_answer[index]) then begin
					dave_get_values,"Enter new value",name,scalar,cancel=cancel,group_leader=group_leader
					if (cancel) then goto,sensitize
					scalar=double(scalar[0])
				endif
			endif
			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
			;
			; Patchable vectors
			index=where(name eq vquans,cnt)
			if (cnt eq 1) then begin
				if (vc_answer[index]) then begin
					vname=strarr(n_elements(data))+name
					dave_get_values,"Enter new values",vname,data,cancel=cancel,group_leader=group_leader
					if (cancel) then goto,sensitize
					data=double(data)
				endif
			endif
			;
			; The array "histohigh".
			if (hh_answer and name eq "histohigh") then begin
				max1=1024
				max2=18
				hhagain:
				loop=0
				repeat begin
					loop=loop+1
					vname=[$
						"t index (0-"+strcompress(max1-1,/remove_all)+")",$
						"d index (0-"+strcompress(max2-1,/remove_all)+")"]
					indices=[-1,-1]
					title="Enter histohigh indices"
					if (loop gt 1) then title=title+"    *****TRY AGAIN*****"
					dave_get_values,title,vname,indices,cancel=cancel,group_leader=group_leader
					if (cancel) then goto,sensitize
				endrep until (0 le indices[0] and indices[0] lt max1 and $
					0 le indices[1] and indices[1] lt max2)
				vname="Histohigh["+strcompress(indices[0],/remove_all)+","+$
					strcompress(indices[1],/remove_all)+"]"
				vval=data[indices[0],indices[1]]
				dave_get_values,"Enter new value",vname,vval,cancel=cancel,group_leader=group_leader
				if (cancel) then goto,sensitize
				data[indices[0],indices[1]]=vval
				data=double(data)
				res=dialog_message("Modify another element of ''histohigh''?",/question)
				if (res eq "Yes") then goto,hhagain
			endif
			;
			; The array "histodata".
			if (hd_answer and name eq "histodata") then begin
				max1=1024
				max2=913
				hdagain:
				loop=0
				repeat begin
					loop=loop+1
					vname=[$
						"t index (0-"+strcompress(max1-1,/remove_all)+")",$
						"d index (0-"+strcompress(max2-1,/remove_all)+")"]
					indices=[-1,-1]
					title="Enter histodata indices"
					if (loop gt 1) then title=title+"    *****TRY AGAIN*****"
					dave_get_values,title,vname,indices,cancel=cancel,group_leader=group_leader
					if (cancel) then goto,sensitize
				endrep until (0 le indices[0] and indices[0] lt max1 and $
					0 le indices[1] and indices[1] lt max2)
				vname="Histodata["+strcompress(indices[0],/remove_all)+","+$
					strcompress(indices[1],/remove_all)+"]"
				vval=data[indices[0],indices[1]]
				dave_get_values,"Enter new value",vname,vval,cancel=cancel,group_leader=group_leader
				if (cancel) then goto,sensitize
				data[indices[0],indices[1]]=vval
				data=double(data)
				res=dialog_message("Modify another element of ''histodata''?",/question)
				if (res eq "Yes") then goto,hdagain
			endif
			writeu,unitw,data
		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
			;
			; Patchable strings
			index=where(name eq strngs,cnt)
			if (cnt eq 1) then begin
				if (st_answer[index]) then begin
					dave_get_values,"Enter new value",name,str,cancel=cancel,group_leader=group_leader
					if (cancel) then goto,sensitize
					nchars=strlen(str)
				endif
			endif
;
			writeu,unitw,nchars
			if (nchars gt 0) then begin
				writeu,unitw,str
			endif
		end
;
		7: begin; read string array
			readu,unit,nstrgs; read number of strings in array
			strarray=strarr(nstrgs)
			strlgths=intarr(nstrgs)
			for j=1,nstrgs do begin
				readu,unit,nchars; read number of characters in string element
				strlgths[j-1]=nchars
				str=bytarr(nchars)
				readu,unit,str; read string element
				strarray[j-1]=strjoin(string(str)); store, joined, in strarray
			endfor
			;
			; Patchable string arrays
			index=where(name eq starrs,cnt)
			if (cnt eq 1) then begin
				if (sa_answer[index]) then begin
					vname=strcompress(strarr(nstrgs)+name+'['+string(indgen(nstrgs))+']',/remove_all)+$
						' '+strcompress('('+string(strlgths)+' chars)',/remove_all)
					dave_get_values,"Enter new values",vname,strarray,cancel=cancel,group_leader=group_leader
					if (cancel) then goto,sensitize
				endif
			endif
			;
			writeu,unitw,nstrgs
			for j=1,nstrgs do begin
				nchars=strlen(strarray[j-1])
				if (nchars ne strlgths[j-1]) then begin
					res=dialog_message(['For element'+strcompress(j-1)+':',$
						'the number of characters has changed from'+strcompress(strlgths[j-1])+' to'+$
						strcompress(nchars)+'.','Do you wish to proceed?'],/question,/default_no)
					if (res='Yes') then goto,sensitize
				endif
				if (nchars eq 0) then begin
					nchars=3
					strarray[j-1]='   '
				endif
				writeu,unitw,nchars
				str=bytarr(nchars)
				for k=0,nchars-1 do begin
					str[k]=byte(strmid(strarray[j-1],k,1))
				endfor
				writeu,unitw,str
			endfor
		end
;
		else:
	endcase
endwhile
;
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
;
end