; $Id: dcstoolsdetectors.pro,v 1.14 2005/02/14 17:50:34 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 DCSToolsDetectors_cleanup,tlb
;************************************************************************************************
;
compile_opt strictarr
;
end


;************************************************************************************************
pro DCSToolsDetectors_handler,event
;************************************************************************************************
;
compile_opt strictarr
;
widget_control,event.top,get_uvalue=state
;
if (event.id eq state.write) then begin
	filename=dialog_pickfile(title="Select output file name",path=(*!dave_defaults).workDir)
	if (filename eq "") then return
	openw,unit,filename,/get_lun
	printf,unit,'Data sorted by '+state.column_labels[state.sort_column[0]]
	if (state.sort_column[1] eq 9) then $
		printf,unit,'  (secondary sort by '+state.column_labels[9]+')'
	ncols=12
	title=state.column_labels
	maxlength=intarr(ncols)
	format=strarr(ncols)+'('
	for j=0,ncols-1 do begin
		maxlength[j]=max(strlen(state.contents[j,*])) > strlen(title[j])
		format[j]=format[j]+'A'+strcompress(maxlength[j]+1,/remove_all)
	endfor
	format=format+')'
	list=''
	for j=0,ncols-1 do begin
		list=list+string(title[j],format=format[j])
	endfor
	printf,unit,list
	nlines=930
	for k=0,nlines-1 do begin
		list=''
		for j=0,ncols-1 do begin
			list=list+string(state.contents[j,k],format=format[j])
		endfor
		printf,unit,list
	endfor
	close,unit
	free_lun,unit
	res=dialog_message("File "+filename+" has been written.",/information)
endif
;
if (event.id eq state.help) then begin
	res=dialog_message([$
		'Number is the detector ID which runs from 0 to 912.',$
		'Crate, Board, Input, Address, Cable, Rack and Position should be of no interest to the user:',$
		'   Crate, Board and Input specify where the detector is plugged into the data acquisition rack,',$
		'   Address specifies the address bits within the word created when an event occurs in the detector,',$
		'   Cable is the number of the signal cable for the detector,',$
		'   Rack, Bank and Position label the physical location of the detector.',$
		'Bank = -1, 0 or 1 depending whether the detector is in the lower, middle or upper bank.',$
		'"2Theta" is the scattering angle (2theta), >0 (<0) if scattering is to the left (right) of the incident beam.',$
		'Polar is the polar angle to the center of the detector.',$
		'Azim. is the azimuthal angle to the center of the detector.',$
		'','Click on a column label to sort by that column.'],/information)
	return
endif
;
if (event.id eq state.dpt) then begin
	if (event.type eq 4) then begin
		column=event.sel_left
		if ((column ge 0) and (column lt 12)) then begin
			inarr=state.contents[*,0:state.nhedet-1]
			dcs_sort_by,float(inarr),outarr,col=column+1,row=0,error
			state.contents[*,0:state.nhedet-1]=string(outarr)
			state.sort_column=[column,-1]
			if (column ne 0 and column ne 4 and column ne 5 and column lt 9) $
				then begin
				; perform secondary sort by angle [column 9] for degenerate $
				; values in the primary sorting column (skip for columns 0,4,5,9,10,11)
				row1=0
				repeat begin
					value=state.contents[column,row1]
					nrows=n_elements(where(value eq state.contents[column,*]))
					rown=row1+nrows-1
					inarr=state.contents[*,row1:rown]
					dcs_sort_by,float(inarr),outarr,col=10,row=0,error
					state.contents[*,row1:rown]=outarr
					row1=rown+1
				endrep until (row1 ge state.nhedet)
				state.sort_column=[column,9]
			endif
			state.contents[0:8,*]=fix(state.contents[0:8,*])
			state.contents[9,*]=string(state.contents[9,*],format='(f7.2)')
			state.contents[10,*]=string(state.contents[10,*],format='(f7.2)')
			state.contents[11,*]=string(state.contents[11,*],format='(f7.2)')
			state.contents[5:9,state.nhedet:state.ntotal-1]=""
			widget_control,state.dpt,set_value=state.contents
			widget_control,event.top,set_uvalue=state
		endif
	endif
endif
;
if (event.id eq state.done) then begin
	widget_control,event.top,/destroy
	return
endif
;
end


;************************************************************************************************
pro DCSToolsDetectors,$
   ; added following 3 keywords to make this a non-modal widget
	group_leader = group_leader,$
	notify_ids = notify_ids,$
	register_name = register_name

;************************************************************************************************
;
compile_opt strictarr
;
;
;;;;;;;added following 4 lines for non-modal widget action
if n_elements(group_leader) eq 0 then group_leader = 0L
if n_elements(notify_ids) eq 0 then notify_ids = [0L,0L]
if n_elements(register_name) eq 0 then register_name = 'DCSToolsDetectors'
if xregistered(register_name) then return
;
; Lines commented out.
;widget_control,event.top,get_uvalue=statePtr
;davePtr=(*statePtr).davePtr
;dcs_sysvars,davePtr=davePtr
;tvlct,r,g,b,/get
;rgbptr=ptr_new({r:r,g:g,b:b})
;
nhedet=913
;
;inputfile=file_which("dcs_DetPos2.dat",/include_current_dir)
inputfile=!DAVE_AUXILIARY_DIR+'dcs_DetPos2.dat'
openr,unit,inputfile,/get_lun
;
content=strarr(nhedet+1)
readf,unit,content
close,unit
free_lun,unit
;
content[0]=content[0]+' 0.0'
dcs_getangles,nhedet=nhedet,angles,banks,azim_angles
content[1:nhedet]=content[1:nhedet]+$
	strcompress(string(abs(angles),format='(f7.2)'))+$
	strcompress(string(azim_angles,format='(f7.2)'))
;
contents=strarr(12,nhedet)
ntotal=nhedet
column_labels=['Number','Crate','Board','Input','Address',$
	'Cable','Rack','Bank','Position','"2Theta"','Polar','Azim.']
;
for i=0,nhedet-1 do begin
	temp=strsplit(content[i+1]," ",/extract)
	contents[0,i]=temp[0]
	if (fix(temp[1]) lt 14) then contents[1,i]=0 else contents[1,i]=1
	contents[2:11,i]=temp[1:10]
endfor
;
;;; Optional lines.
nhigh=930-nhedet
contentsh=strarr(12,nhigh)
contentsh[0,*]=indgen(nhigh)+nhedet
contentsh[1,*]=1
contentsh[2,*]=indgen(nhigh)+14
contentsh[3,*]=29
contentsh[4,*]=indgen(nhigh)+942
contents=transpose([transpose(contents),transpose(contentsh)])
ntotal=ntotal+nhigh
for i=nhedet,ntotal-1 do contents[*,i]=strcompress(contents[*,i],/remove_all)
;
row_labels=string(indgen(ntotal)+1)
alignment=bytarr(13,ntotal)+1
alignment[9:11,*]=2
;
tlb=widget_base(title='Detector Information',/col,group_leader=group_leader,mbar=bar)
	filemenu=widget_button(bar,/menu,value='File')
		help=widget_button(filemenu,value="Help")
		write=widget_button(filemenu,value='Write data file')
		done=widget_button(filemenu,value="Quit")
	dpt=widget_table(tlb,xsize=13,ysize=ntotal,x_scroll_size=13,y_scroll_size=26,$
		column_widths=[50,50,50,50,50,50,50,50,50,50,50,50,5],column_labels=column_labels,$
		alignment=alignment,row_labels=row_labels,value=contents,/sensitive,/all_events)
centertlb,tlb
widget_control,tlb,/realize
;
state={$
	write:write,$
	help:help,$
	done:done,$
	dpt:dpt,$
	contents:contents,$
	column_labels:column_labels,$
	sort_column:[0,-1],$
	nhedet:nhedet,$
	notify_ids:notify_ids,  $              ; for non-modal widget
	ntotal:ntotal}
widget_control,tlb,set_uvalue=state
;
; added register_name variable to the call to xmanager.
xmanager,register_name,tlb,/no_block,cleanup='DCSToolsDetectors_cleanup',$
	event_handler="DCSToolsDetectors_handler"
;
; Lines commented out.
;dave_makeDavePtr,davePtr=davePtr
;(*statePtr).davePtr=davePtr
;tvlct,(*rgbptr).r,(*rgbptr).g,(*rgbptr).b
;ptr_free,rgbptr
;
end
