; NAME:
;       MABC
;PD Dr. Philip Tregenna-Piggott,
;Laboratory for Neutron Scattering,
;ETHZ and Paul-Scherrer Institute,
;CH-5232 Villigen PSI,
;Switzerland.
;
;Tel. :+41 56 310 54 05
;Fax. :+41 56 310 29 39
;Email:philip.tregenna@psi.ch
;
;
; CATEGORY:
;
;       MARS Tools
;
; CALLING SEQUENCE:
;
;      MarsAnalyserBanksCalibration
;
;
; INPUT FIELDS:
;
;
; EXAMPLES FOR POTENTIALS (must use IDL syntax as shown below):
;
;
; DISCLAIMER
;
;     This software is provided as is without any warranty whatsoever.
;     Permission to use, copy, modify, and distribute modified or
;     unmodified copies is granted, provided this disclaimer
;     is included unchanged.
;
; MODIFICATION HISTORY:
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;get sics functions and procedures
@idlsics
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABC_cleanup,tlb
widget_control,tlb,get_uvalue = pState_mabc
wdelete,(*pState_mabc).winPix_gauss2D
wdelete,(*pState_mabc).winPix_raw
wdelete,(*pState_mabc).winPix_gauss1D
wdelete,(*pState_mabc).winPix_cross
device, decomposed = (*pState_mabc).old_dc
if (*pstate_mabc).demo_mabc eq 0 then begin
sicsclose,(*pstate_mabc).UnitUser_exe
sicsclose,(*pstate_mabc).UnitUser_2
sicsclose,(*pstate_mabc).UnitSpy
sicsclose,(*pstate_mabc).UnitManager
endif
heap_free,pState_mabc
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABC_exit,event
widget_control,event.top,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function GetMARSConstants,filename

if file_test(filename) eq 0 then begin
filefound=0
constants={filefound:filefound}
return,constants
endif else begin
filefound=1
constants={filefound:filefound}
endelse
line=''
Constants_str='Constants'
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
Constants_str=[Constants_str,line]
endwhile
free_lun,lun,/force
Constants_str=Constants_str[1:*]
n=n_elements(Constants_str)
for i = 0,n-1 do begin
ConstantName=strtrim((strsplit(Constants_str[i],'=',/extract))[0],2)
ConstantString=strtrim((strsplit(Constants_str[i],'=',/extract))[1],2)
    if strpos(ConstantString,',') eq -1 then begin
    ConstantValue=double(ConstantString)
    endif else begin
    ConstantString=strtrim((strsplit(ConstantString,',',/extract)),2)
    ConstantValue=double(ConstantString)
    endelse
constants=create_struct(constants,ConstantName,ConstantValue)
endfor
constants=create_struct(constants,name='MARSConstants')
return,constants

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function GetMARSAcceptableTimebins,filename

if file_test(filename) eq 0 then begin
filefound=0
TimeBins={filefound:filefound}
return,TimeBins
endif else begin
filefound=1
TimeBins={filefound:filefound}
endelse

line=''
ATB_str='ATB'
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
ATB_str=[ATB_str,line]
endwhile
free_lun,lun,/force
ATB_str=ATB_str[1:*]
n=n_elements(ATB_str)
for i = 0,n-1 do begin
TimeBinStep=long(strtrim((strsplit(ATB_str[i],/extract))[0],2))
TimeBinNumber=long(strtrim((strsplit(ATB_str[i],/extract))[1],2))
if i eq 0 then begin
TimeBinStep_arr=[TimeBinStep]
TimeBinNumber_arr=[TimeBinNumber]
endif else begin
TimeBinStep_arr=[TimeBinStep_arr,TimeBinStep]
TimeBinNumber_arr=[TimeBinNumber_arr,TimeBinNumber]
endelse
endfor
TimeBins=create_struct(TimeBins,'TimeBinStep_arr',TimeBinStep_arr,'TimeBinNumber_arr',TimeBinNumber_arr)
TimeBins=create_struct(TimeBins,name='MARSTimeBins')
return,TimeBins
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function GetMARSTimeOffsets,filename

if file_test(filename) eq 0 then begin
filefound=0
timeoffsets={filefound:filefound}
return,timeoffsets
endif else begin
filefound=1
timeoffsets={filefound:filefound}
endelse

line=''
timeoffsets_str='timeoffsets'
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
timeoffsets_str=[timeoffsets_str,line]
endwhile
free_lun,lun,/force
timeoffsets_str=timeoffsets_str[1:*]
n=n_elements(timeoffsets_str)
if n ne 7 then begin
filefound=0
timeoffsets={filefound:filefound}
return,timeoffsets
endif
valid_names=['master1_timeoffset', $
         'master2_timeoffset', $
         'master3_timeoffset', $
         'master4_timeoffset', $
         'master5_timeoffset', $
         'master6_timeoffset', $
         'master7_timeoffset']
for i = 0,n-1 do begin
Name=strtrim((strsplit(timeoffsets_str[i],'=',/extract))[0],2)
void=where(strmatch(valid_names,name) eq 1,count)
if count eq 0 then begin
filefound=0
timeoffsets={filefound:filefound}
return,timeoffsets
endif
Value=double(strtrim((strsplit(timeoffsets_str[i],'=',/extract))[1],2))
timeoffsets=create_struct(timeoffsets,Name,Value)
endfor
timeoffsets=create_struct(timeoffsets,name='MARSTimeOffsets')

return,timeoffsets
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function Bragg,dspacing,theta
return, 2.0*dspacing*sin(theta*!DTOR)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function GenerateTimebinIndices_MABC,event,vl,vu,TOF_start,TOF_width,TOF_step,mica,theta
widget_control,event.top,get_uvalue = pState_mabc
constants=(*pState_mabc).constants
lTOFMon=constants.lTOFMon
lTOFPostMon=constants.lTOFPostMon
lDiff=constants.lDiff
lprim=constants.lprim
D=constants.D
mn=constants.mn
conv=constants.meVtoJoules
HP=constants.Histogram_Period
dspace_array=(*pState_mabc).dspace_array
;
;h=constants.h
;these offsets will be applied to the real data
timeoffsets=(*pState_mabc).timeoffsets
offset=0.0
widget_control,(*pState_mabc).Master,get_value =Master
widget_control,(*pState_mabc).view,get_value = view
masterfundamental=fix(Master[0])
if masterfundamental eq 1 then offset=timeoffsets.master1_timeoffset
if masterfundamental eq 2 then offset=timeoffsets.master2_timeoffset
if masterfundamental eq 3 then offset=timeoffsets.master3_timeoffset
if masterfundamental eq 4 then offset=timeoffsets.master4_timeoffset
if masterfundamental eq 5 then offset=timeoffsets.master5_timeoffset
if masterfundamental eq 6 then offset=timeoffsets.master6_timeoffset
if masterfundamental eq 7 then offset=timeoffsets.master7_timeoffset
;print,'offset: ' ,offset

;
;starty=systime(1,/seconds)

n_points=long((TOF_width/TOF_step))
timebin_vec=TOF_start+TOF_step*findgen(n_points)
timebin_vec+=offset


;TOF_end=double(TOF_start+TOF_width)
;timebin_vec=double(TOF_start)
;tb=double(TOF_start)
;TOF_step=double(TOF_step)



;while tb lt TOF_end do begin
;tb+=TOF_step
;timebin_vec=[timebin_vec,tb]
;endwhile
;print,'timebin_vec: ',timebin_vec
;
;endy=systime(1,/seconds)
;duration=endy-starty
;print,'duration: ',duration


time=1e6*lTOFMon/vu
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=index[0]
endelse
;
;
;
time=1e6*lTOFMon/vl
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
;
time=1e6*lTOFPostMon/vu
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
time=1e6*lTOFPostMon/vl
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
time=1e6*ldiff/vu
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
time=1e6*ldiff/vl
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
;
tprim_lower=1e6*lprim/vu
tprim_higher=1e6*lprim/vl

if view eq 1 then begin
endbin=n_points-2 ;just in case
TimeBinIndices=[TimeBinIndices,0,endbin,0,endbin,0,endbin,0,endbin]
print,'TimeBinIndices: ',strtrim(string(TimeBinIndices),2)+','
print,'n_points: ',strtrim(string(n_points),2)
return,TimeBinIndices
endif

TimeBinIndices=[TimeBinIndices,-1,-1,-1,-1,-1,-1,-1,-1]
;
;
case mica of
0:    $  ;002 reflection
begin
dspacing=dspace_array[mica]
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[6]=index[0]
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[7]=index[0]
;
;
end
1:    $  ;004 reflection
begin
dspacing=dspace_array[mica]
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[8]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[8]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[9]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[9]=index[0]
endelse
;
dspacing=dspace_array[0]    ; 002 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[6]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[6]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[7]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[7]=index[0]
endelse
;
end
2:    $  ;006 reflection
begin
dspacing=dspace_array[mica]
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[10]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[10]=index[0]
endelse

;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[11]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[11]=index[0]
endelse
;
dspacing=dspace_array[1] ; 004 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[8]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[8]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[9]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[9]=index[0]
endelse
;
dspacing=dspace_array[0]    ; 002 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[6]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[6]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[7]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[7]=index[0]
endelse
;
end
3:    $  ;008 reflection
begin
dspacing=dspace_array[mica]
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[12]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[12]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[13]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[13]=index[0]
endelse
;
dspacing=dspace_array[2]   ; 006 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[10]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[10]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[11]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[11]=index[0]
endelse
;
;
dspacing=dspace_array[1] ; 004 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[8]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[8]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[9]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[9]=index[0]
endelse
;
dspacing=dspace_array[0]    ; 002 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[6]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[6]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[7]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[7]=index[0]
endelse
end
endcase
print,'TimeBinIndices: ',strtrim(string(TimeBinIndices),2)+','
print,'n_points: ',strtrim(string(n_points),2)
return,TimeBinIndices
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Populate_Triffid_Tables,event
widget_control,event.top,get_uvalue = pState_mabc
Analyser_structure=(*pState_mabc).Analyser_structure

theta_index=widget_info((*pState_mabc).analyser_angle_droplist,/droplist_select)
theta=(*pState_mabc).Calibration_Angles_str[1,theta_index]

Aare_Table=strarr(8,5)
Aare_Table[0,*]=theta_index+1
Aare_Table[1,*]=theta
;
Aare_Table[2,0]=Analyser_structure.Aare_150.AFA150[1,theta_index]
Aare_Table[3,0]=Analyser_structure.Aare_150.ALA150[1,theta_index]
Aare_Table[4,0]=Analyser_structure.Aare_150.ASA150[1,theta_index]
Aare_Table[5,0]=Analyser_structure.Aare_150.DLA150[1,theta_index]
Aare_Table[6,0]=Analyser_structure.Aare_150.DSA150[1,theta_index]
Aare_Table[7,0]=Analyser_structure.Aare_150.DRA150[1,theta_index]
;
Aare_Table[2,1]=Analyser_structure.Aare_120.AFA120[1,theta_index]
Aare_Table[3,1]=Analyser_structure.Aare_120.ALA120[1,theta_index]
Aare_Table[4,1]=Analyser_structure.Aare_120.ASA120[1,theta_index]
Aare_Table[5,1]=Analyser_structure.Aare_120.DLA120[1,theta_index]
Aare_Table[6,1]=Analyser_structure.Aare_120.DSA120[1,theta_index]
Aare_Table[7,1]=Analyser_structure.Aare_120.DRA120[1,theta_index]
;
Aare_Table[2,2]=Analyser_structure.Aare_90.AFA90[1,theta_index]
Aare_Table[3,2]=Analyser_structure.Aare_90.ALA90[1,theta_index]
Aare_Table[4,2]=Analyser_structure.Aare_90.ASA90[1,theta_index]
Aare_Table[5,2]=Analyser_structure.Aare_90.DLA90[1,theta_index]
Aare_Table[6,2]=Analyser_structure.Aare_90.DSA90[1,theta_index]
Aare_Table[7,2]=Analyser_structure.Aare_90.DRA90[1,theta_index]
;
Aare_Table[2,3]=Analyser_structure.Aare_60.AFA60[1,theta_index]
Aare_Table[3,3]=Analyser_structure.Aare_60.ALA60[1,theta_index]
Aare_Table[4,3]=Analyser_structure.Aare_60.ASA60[1,theta_index]
Aare_Table[5,3]=Analyser_structure.Aare_60.DLA60[1,theta_index]
Aare_Table[6,3]=Analyser_structure.Aare_60.DSA60[1,theta_index]
Aare_Table[7,3]=Analyser_structure.Aare_60.DRA60[1,theta_index]
;
Aare_Table[2,4]=Analyser_structure.Aare_30.AFA30[1,theta_index]
Aare_Table[3,4]=Analyser_structure.Aare_30.ALA30[1,theta_index]
Aare_Table[4,4]=Analyser_structure.Aare_30.ASA30[1,theta_index]
Aare_Table[5,4]=Analyser_structure.Aare_30.DLA30[1,theta_index]
Aare_Table[6,4]=Analyser_structure.Aare_30.DSA30[1,theta_index]
Aare_Table[7,4]=Analyser_structure.Aare_30.DRA30[1,theta_index]
;
(*pState_mabc).AareForegroundColors[0,*]=0
(*pState_mabc).AareForegroundColors[1,*]=0
(*pState_mabc).AareForegroundColors[2,*]=255
widget_control,(*pState_mabc).Aare_Triffid_Table,set_value=Aare_Table,foreground_color=(*pState_mabc).AareForegroundColors

;
Berg_Table=strarr(8,5)
Berg_Table[0,*]=theta_index+1
Berg_Table[1,*]=theta
;
Berg_Table[2,0]=Analyser_structure.Berg_30.AFB30[1,theta_index]
Berg_Table[3,0]=Analyser_structure.Berg_30.ALB30[1,theta_index]
Berg_Table[4,0]=Analyser_structure.Berg_30.ASB30[1,theta_index]
Berg_Table[5,0]=Analyser_structure.Berg_30.DLB30[1,theta_index]
Berg_Table[6,0]=Analyser_structure.Berg_30.DSB30[1,theta_index]
Berg_Table[7,0]=Analyser_structure.Berg_30.DRB30[1,theta_index]
;
Berg_Table[2,1]=Analyser_structure.Berg_60.AFB60[1,theta_index]
Berg_Table[3,1]=Analyser_structure.Berg_60.ALB60[1,theta_index]
Berg_Table[4,1]=Analyser_structure.Berg_60.ASB60[1,theta_index]
Berg_Table[5,1]=Analyser_structure.Berg_60.DLB60[1,theta_index]
Berg_Table[6,1]=Analyser_structure.Berg_60.DSB60[1,theta_index]
Berg_Table[7,1]=Analyser_structure.Berg_60.DRB60[1,theta_index]
;
Berg_Table[2,2]=Analyser_structure.Berg_90.AFB90[1,theta_index]
Berg_Table[3,2]=Analyser_structure.Berg_90.ALB90[1,theta_index]
Berg_Table[4,2]=Analyser_structure.Berg_90.ASB90[1,theta_index]
Berg_Table[5,2]=Analyser_structure.Berg_90.DLB90[1,theta_index]
Berg_Table[6,2]=Analyser_structure.Berg_90.DSB90[1,theta_index]
Berg_Table[7,2]=Analyser_structure.Berg_90.DRB90[1,theta_index]
;
Berg_Table[2,3]=Analyser_structure.Berg_120.AFB120[1,theta_index]
Berg_Table[3,3]=Analyser_structure.Berg_120.ALB120[1,theta_index]
Berg_Table[4,3]=Analyser_structure.Berg_120.ASB120[1,theta_index]
Berg_Table[5,3]=Analyser_structure.Berg_120.DLB120[1,theta_index]
Berg_Table[6,3]=Analyser_structure.Berg_120.DSB120[1,theta_index]
Berg_Table[7,3]=Analyser_structure.Berg_120.DRB120[1,theta_index]
;
Berg_Table[2,4]=Analyser_structure.Berg_150.AFB150[1,theta_index]
Berg_Table[3,4]=Analyser_structure.Berg_150.ALB150[1,theta_index]
Berg_Table[4,4]=Analyser_structure.Berg_150.ASB150[1,theta_index]
Berg_Table[5,4]=Analyser_structure.Berg_150.DLB150[1,theta_index]
Berg_Table[6,4]=Analyser_structure.Berg_150.DSB150[1,theta_index]
Berg_Table[7,4]=Analyser_structure.Berg_150.DRB150[1,theta_index]
;
(*pState_mabc).BergForegroundColors[0,*]=0
(*pState_mabc).BergForegroundColors[1,*]=0
(*pState_mabc).BergForegroundColors[2,*]=255

widget_control,(*pstate_mabc).Berg_Triffid_Table,set_value = Berg_Table,foreground_color=(*pState_mabc).BergForegroundColors
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SaveTriffidTable,event
widget_control,event.top,get_uvalue = pState_mabc
workDir=(*pState_mabc).workDir


widget_control,(*pState_mabc).Aare_Triffid_Table,get_value=Aare_Table
widget_control,(*pState_mabc).Berg_Triffid_Table,get_value=Berg_Table
Analyser_structure=(*pState_mabc).Analyser_structure
theta_index=widget_info((*pState_mabc).analyser_angle_droplist,/droplist_select)
;

;
;memorize changes
;
Analyser_structure.Aare_150.AFA150[1,theta_index]=Aare_Table[2,0]
Analyser_structure.Aare_150.ALA150[1,theta_index]=Aare_Table[3,0]
Analyser_structure.Aare_150.ASA150[1,theta_index]=Aare_Table[4,0]
Analyser_structure.Aare_150.DLA150[1,theta_index]=Aare_Table[5,0]
Analyser_structure.Aare_150.DSA150[1,theta_index]=Aare_Table[6,0]
Analyser_structure.Aare_150.DRA150[1,theta_index]=Aare_Table[7,0]
Analyser_structure.Aare_120.AFA120[1,theta_index]=Aare_Table[2,1]
Analyser_structure.Aare_120.ALA120[1,theta_index]=Aare_Table[3,1]
Analyser_structure.Aare_120.ASA120[1,theta_index]=Aare_Table[4,1]
Analyser_structure.Aare_120.DLA120[1,theta_index]=Aare_Table[5,1]
Analyser_structure.Aare_120.DSA120[1,theta_index]=Aare_Table[6,1]
Analyser_structure.Aare_120.DRA120[1,theta_index]=Aare_Table[7,1]
Analyser_structure.Aare_90.AFA90[1,theta_index]=Aare_Table[2,2]
Analyser_structure.Aare_90.ALA90[1,theta_index]=Aare_Table[3,2]
Analyser_structure.Aare_90.ASA90[1,theta_index]=Aare_Table[4,2]
Analyser_structure.Aare_90.DLA90[1,theta_index]=Aare_Table[5,2]
Analyser_structure.Aare_90.DSA90[1,theta_index]=Aare_Table[6,2]
Analyser_structure.Aare_90.DRA90[1,theta_index]=Aare_Table[7,2]
Analyser_structure.Aare_60.AFA60[1,theta_index]=Aare_Table[2,3]
Analyser_structure.Aare_60.ALA60[1,theta_index]=Aare_Table[3,3]
Analyser_structure.Aare_60.ASA60[1,theta_index]=Aare_Table[4,3]
Analyser_structure.Aare_60.DLA60[1,theta_index]=Aare_Table[5,3]
Analyser_structure.Aare_60.DSA60[1,theta_index]=Aare_Table[6,3]
Analyser_structure.Aare_60.DRA60[1,theta_index]=Aare_Table[7,3]
Analyser_structure.Aare_30.AFA30[1,theta_index]=Aare_Table[2,4]
Analyser_structure.Aare_30.ALA30[1,theta_index]=Aare_Table[3,4]
Analyser_structure.Aare_30.ASA30[1,theta_index]=Aare_Table[4,4]
Analyser_structure.Aare_30.DLA30[1,theta_index]=Aare_Table[5,4]
Analyser_structure.Aare_30.DSA30[1,theta_index]=Aare_Table[6,4]
Analyser_structure.Aare_30.DRA30[1,theta_index]=Aare_Table[7,4]
Analyser_structure.Berg_30.AFB30[1,theta_index]=Berg_Table[2,0]
Analyser_structure.Berg_30.ALB30[1,theta_index]=Berg_Table[3,0]
Analyser_structure.Berg_30.ASB30[1,theta_index]=Berg_Table[4,0]
Analyser_structure.Berg_30.DLB30[1,theta_index]=Berg_Table[5,0]
Analyser_structure.Berg_30.DSB30[1,theta_index]=Berg_Table[6,0]
Analyser_structure.Berg_30.DRB30[1,theta_index]=Berg_Table[7,0]
Analyser_structure.Berg_60.AFB60[1,theta_index]=Berg_Table[2,1]
Analyser_structure.Berg_60.ALB60[1,theta_index]=Berg_Table[3,1]
Analyser_structure.Berg_60.ASB60[1,theta_index]=Berg_Table[4,1]
Analyser_structure.Berg_60.DLB60[1,theta_index]=Berg_Table[5,1]
Analyser_structure.Berg_60.DSB60[1,theta_index]=Berg_Table[6,1]
Analyser_structure.Berg_60.DRB60[1,theta_index]=Berg_Table[7,1]
Analyser_structure.Berg_90.AFB90[1,theta_index]=Berg_Table[2,2]
Analyser_structure.Berg_90.ALB90[1,theta_index]=Berg_Table[3,2]
Analyser_structure.Berg_90.ASB90[1,theta_index]=Berg_Table[4,2]
Analyser_structure.Berg_90.DLB90[1,theta_index]=Berg_Table[5,2]
Analyser_structure.Berg_90.DSB90[1,theta_index]=Berg_Table[6,2]
Analyser_structure.Berg_90.DRB90[1,theta_index]=Berg_Table[7,2]
Analyser_structure.Berg_120.AFB120[1,theta_index]=Berg_Table[2,3]
Analyser_structure.Berg_120.ALB120[1,theta_index]=Berg_Table[3,3]
Analyser_structure.Berg_120.ASB120[1,theta_index]=Berg_Table[4,3]
Analyser_structure.Berg_120.DLB120[1,theta_index]=Berg_Table[5,3]
Analyser_structure.Berg_120.DSB120[1,theta_index]=Berg_Table[6,3]
Analyser_structure.Berg_120.DRB120[1,theta_index]=Berg_Table[7,3]
Analyser_structure.Berg_150.AFB150[1,theta_index]=Berg_Table[2,4]
Analyser_structure.Berg_150.ALB150[1,theta_index]=Berg_Table[3,4]
Analyser_structure.Berg_150.ASB150[1,theta_index]=Berg_Table[4,4]
Analyser_structure.Berg_150.DLB150[1,theta_index]=Berg_Table[5,4]
Analyser_structure.Berg_150.DSB150[1,theta_index]=Berg_Table[6,4]
Analyser_structure.Berg_150.DRB150[1,theta_index]=Berg_Table[7,4]
(*pState_mabc).Analyser_structure=Analyser_structure


    filename=dialog_pickfile(path=workDir,$
      file='TriffidData.tfd',/write,filter="*.tfd",/fix_filter)
if n_elements(filename) eq 0 then return
if filename eq '' then return
save, filename=filename, Analyser_structure
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro LoadTriffidTable,event
widget_control,event.top,get_uvalue = pState_mabc
workDir=(*pState_mabc).workDir

    filename=dialog_pickfile(path=workDir,$
      file='TriffidData.tfd',/read,filter="*.tfd",/fix_filter)

if n_elements(filename) eq 0 then return
if filename eq '' then return

restore,filename=filename
(*pState_mabc).Analyser_structure=Analyser_structure

Populate_Triffid_Tables,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro CreateTriffidTableMod,event
widget_control,event.top,get_uvalue = pState_mabc
workDir=(*pState_mabc).workDir
Analyser_structure=(*pState_mabc).Analyser_structure
TimeStamp=systime()
StringParts=strsplit(TimeStamp,/extract)
n=n_elements(StringParts)
TimeStamp=StringParts[0]+'_'
for i = 1, n-2 do begin
TimeStamp+=StringParts[i]+'_'
endfor
TimeStamp+=StringParts[n-1]
StringParts=strsplit(TimeStamp,':',/extract)
n=n_elements(StringParts)
TimeStamp=StringParts[0]+'%'
for i = 1, n-2 do begin
TimeStamp+=StringParts[i]+'%'
endfor
TimeStamp+=StringParts[n-1]
;
filename=workdir+'triffid01'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
coeff=dblarr(10,4)
coeff[0,0]=-0.954313
coeff[0,1]=0.545753
coeff[0,2]=4.97649e-06
coeff[0,3]=3.74336e-08
;
coeff[1,0]=-5.48915
coeff[1,1]=0.544222
coeff[1,2]=5.60351e-07
coeff[1,3]=3.52557e-08
;
coeff[2,0]=-1.06635
coeff[2,1]=0.547831
coeff[2,2]=5.83682e-06
coeff[2,3]=3.76894e-08
;
coeff[3,0]=-1.68375
coeff[3,1]=0.540233
coeff[3,2]=-5.82463e-06
coeff[3,3]=3.38836e-08
;
coeff[4,0]=-5.58537
coeff[4,1]=0.547453
coeff[4,2]=4.0638e-06
coeff[4,3]=3.71792e-08
;
coeff[5,0]=0.233585
coeff[5,1]=0.547703
coeff[5,2]=3.15678e-06
coeff[5,3]=3.65118e-08
;
coeff[6,0]=2.57583
coeff[6,1]=0.541011
coeff[6,2]=-2.23536e-06
coeff[6,3]=3.54894e-08
;
coeff[7,0]=-10.5774
coeff[7,1]=0.545877
coeff[7,2]=3.76127e-06
coeff[7,3]=3.74396e-08
;
coeff[8,0]=0.89549
coeff[8,1]=0.551757
coeff[8,2]=9.38342e-06
coeff[8,3]=3.85157e-08
;
coeff[9,0]=4.29708
coeff[9,1]=0.569492
coeff[9,2]=3.04751e-05
coeff[9,3]=4.49272e-08
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL01'
Co=reform(coeff[0,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Aare_150.DLA150[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Aare_150.ALA150[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.ASA150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.AFA150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL01'
for i = 0,31 do begin
DLS=Analyser_structure.Aare_150.DLA150[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.DSA150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.DRA150[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid02'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;

printf,lun,'# '+'AL02'
Co=reform(coeff[1,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Aare_120.DLA120[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Aare_120.ALA120[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.ASA120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.AFA120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL02'
for i = 0,31 do begin
DLS=Analyser_structure.Aare_120.DLA120[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''

;
printf,lun,'# '+'DS02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.DSA120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.DRA120[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid03'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL03'
Co=reform(coeff[2,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Aare_90.DLA90[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Aare_90.ALA90[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.ASA90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.AFA90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL03'
for i = 0,31 do begin
DLS=Analyser_structure.Aare_90.DLA90[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''
;
;
printf,lun,'# '+'DS03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.DSA90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.DRA90[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid04'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL04'
Co=reform(coeff[3,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Aare_60.DLA60[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Aare_60.ALA60[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.ASA60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.AFA60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL04'
for i = 0,31 do begin
DLS=Analyser_structure.Aare_60.DLA60[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.DSA60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.DRA60[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid05'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL05'
Co=reform(coeff[4,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Aare_30.DLA30[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Aare_30.ALA30[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.ASA30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.AFA30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL05'
for i = 0,31 do begin
DLS=Analyser_structure.Aare_30.DLA30[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.DSA30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.DRA30[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
;
;
;
filename=workdir+'triffid06'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL06'
Co=reform(coeff[5,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Berg_30.DLB30[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Berg_30.ALB30[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''

;
printf,lun,'# '+'AS06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.ASB30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.AFB30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL06'
for i = 0,31 do begin
DLS=Analyser_structure.Berg_30.DLB30[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''
;
;
printf,lun,'# '+'DS06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.DSB30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.DRB30[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid07'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL07'
Co=reform(coeff[6,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Berg_60.DLB60[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Berg_60.ALB60[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.ASB60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.AFB60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL07'
for i = 0,31 do begin
DLS=Analyser_structure.Berg_60.DLB60[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''
;
;
printf,lun,'# '+'DS07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.DSB60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.DRB60[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid08'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL08'
Co=reform(coeff[7,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Berg_90.DLB90[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Berg_90.ALB90[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.ASB90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.AFB90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL08'
for i = 0,31 do begin
DLS=Analyser_structure.Berg_90.DLB90[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.DSB90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.DRB90[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid09'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL09'
Co=reform(coeff[8,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Berg_120.DLB120[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Berg_120.ALB120[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.ASB120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.AFB120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL09'
for i = 0,31 do begin
DLS=Analyser_structure.Berg_120.DLB120[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''
;
;
printf,lun,'# '+'DS09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.DSB120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.DRB120[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid10'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;

printf,lun,'# '+'AL10'
Co=reform(coeff[9,*])
for i = 0,31 do begin
DL=reform(Analyser_structure.Berg_150.DLB150[1,i])
if i ge 18 then DL+=10
AlS=Analyser_structure.Berg_150.ALB150[*,i]
AlS[1]=Co[0]+Co[1]*DL+Co[2]*Dl^2+Co[3]*Dl^3
printf,lun,AlS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.ASB150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.AFB150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL10'
for i = 0,31 do begin
DLS=Analyser_structure.Berg_150.DLB150[*,i]
if i ge 18 then DLS[1]+=10
printf,lun,DLS,format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.DSB150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.DRB150[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro CreateTriffidTable,event
widget_control,event.top,get_uvalue = pState_mabc
workDir=(*pState_mabc).workDir
Analyser_structure=(*pState_mabc).Analyser_structure
TimeStamp=systime()
StringParts=strsplit(TimeStamp,/extract)
n=n_elements(StringParts)
TimeStamp=StringParts[0]+'_'
for i = 1, n-2 do begin
TimeStamp+=StringParts[i]+'_'
endfor
TimeStamp+=StringParts[n-1]
StringParts=strsplit(TimeStamp,':',/extract)
n=n_elements(StringParts)
TimeStamp=StringParts[0]+'%'
for i = 1, n-2 do begin
TimeStamp+=StringParts[i]+'%'
endfor
TimeStamp+=StringParts[n-1]
;
filename=workdir+'triffid01'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.ALA150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.ASA150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.AFA150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.DLA150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.DSA150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR01'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_150.DRA150[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid02'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.ALA120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.ASA120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.AFA120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.DLA120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.DSA120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR02'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_120.DRA120[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid03'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.ALA90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.ASA90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.AFA90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.DLA90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.DSA90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR03'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_90.DRA90[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid04'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.ALA60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.ASA60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.AFA60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.DLA60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.DSA60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR04'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_60.DRA60[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid05'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.ALA30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.ASA30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.AFA30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.DLA30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.DSA30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR05'
for i = 0,31 do begin
printf,lun,Analyser_structure.Aare_30.DRA30[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
;
;
;
filename=workdir+'triffid06'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.ALB30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.ASB30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.AFB30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.DLB30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.DSB30[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR06'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_30.DRB30[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid07'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.ALB60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.ASB60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.AFB60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.DLB60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.DSB60[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR07'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_60.DRB60[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid08'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.ALB90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.ASB90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.AFB90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.DLB90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.DSB90[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR08'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_90.DRB90[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid09'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.ALB120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.ASB120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.AFB120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.DLB120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.DSB120[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR09'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_120.DRB120[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force
;
;
;
filename=workdir+'triffid10'+'_'+TimeStamp+'.dat'
thisformat='(3(F8.2,1x))'
openw,lun,filename,/get_lun
;
printf,lun,'# '+'AL10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.ALB150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AS10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.ASB150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'AF10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.AFB150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DL10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.DLB150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DS10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.DSB150[*,i],format=thisformat
endfor
printf,lun,''
;
printf,lun,'# '+'DR10'
for i = 0,31 do begin
printf,lun,Analyser_structure.Berg_150.DRB150[*,i],format=thisformat
endfor
printf,lun,''
;
free_lun,lun,/force

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mabc_password_widget_event,event
widget_control,event.top,get_uvalue = pstate1
uname=widget_info(event.id,/uname)
case uname of
'pass':    $
begin
        case event.type of
            0: begin            ; Insert Single Character
                (*pstate1).password += string(event.ch)
            end
            1: begin            ; Insert Multiple Characters
                (*pstate1).password += event.str
            end
            2: begin            ; Delete Text
                (*pstate1).password = strmid((*pstate1).password,0,event.offset)
            end
            3:                  ; Text Selection
        endcase
        len = strlen((*pstate1).password)
        if ((len gt 0) && (event.type ne 3)) then $
          widget_control, event.id, set_value=strjoin(replicate('*',len)), set_text_select=[len,0]
    end
'ok':    $
begin
if (*pstate1).password eq 'MARSLNS' then begin
widget_control,event.top,/destroy
endif else begin
widget_control, (*pstate1).password_field,set_value=''
(*pstate1).password=''
endelse
return
end
'cancel':    $
begin
(*pstate1).password=''
widget_control,event.top,/destroy
return
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function mabc_password_widget,group_leader = group_leader
if n_elements(group_leader) eq 0 then begin
  tlb = widget_base(/col,title = 'Password Protected',/tlb_frame_attr)
endif else begin
    tlb = widget_base(group_leader = group_leader, /col,/modal, $
        title = 'Password Protected',/tlb_frame_attr)
endelse
base = widget_base(tlb,/col,XSIZE=170)
password=''
;password_field= cw_field(base,/row,value = password,title = 'Enter Password',/all_events,uname='pass')
password_field = widget_text(base,uname='pass',value='',/editable,/all_events)

CancelButton = widget_button(base,value = 'Cancel',uname='cancel')
OKButton = widget_button(base,value = 'OK',uname='ok')
centertlb,tlb
widget_control,tlb,/realize

state1 = {CancelButton:CancelButton, $
       password_field:password_field, $
       password:password }
pstate1 = ptr_new(state1,/no_copy)
widget_control,tlb,set_uvalue = pstate1
xmanager,'mabc_password_widget',tlb,event_handler = 'mabc_password_widget_event'
password=(*pstate1).password
ptr_free,pState1
return,password
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABCChopperPhases,event
widget_control,event.top,get_uvalue = pState_mabc
common vc_find_share, l14,l15,mn,delt,Em
;get constants
constants=(*pState_mabc).constants
TimeBins=(*pState_mabc).TimeBins
l21=constants.l21
l23=constants.l23
;
l14=constants.l14
l15=constants.l15
l24=constants.l24
l25=constants.l25
HP=constants.Histogram_Period
; note that lDiff,lTOFMon and lprim should correspond to the lengths measured from the Master'
; chopper and not the snail chopper.  These parameters are used in the calculation of the
; time binning
lTOFMon=constants.lTOFMon
lTOFPostMon=constants.lTOFPostMon
lDiff=constants.lDiff
lprim=constants.lprim
PulseWidth=constants.PulseWidth
TimeWinRatio=double(l25/lprim)
D=constants.D
v002=constants.v002
mn=constants.mn
h=constants.h
omega=constants.omega
conv=constants.meVtoJoules
dspace_array=(*pState_mabc).dspace_array
;get input parameters
widget_control,(*pState_mabc).EM,get_value = Em_set
Em_set=float(Em_set[0])
; define limits
widget_control,(*pState_mabc).Master,get_value =Master
Master=float(Master[0])
PulseWidth/=Master
widget_control,(*pState_mabc).Energy_Window_Slider,get_value =Energy_Window_Slider
Energy_Window_Slider=float(Energy_Window_Slider)
widget_control,(*pState_mabc).mica,get_value =mica
mica=fix(mica[0])
dspacing=dspace_array[mica]
;
;
;calculate delt
delt=D/(2.0*v002)
;print,'Energy_Window_Slider =',Energy_Window_Slider
delt*=Energy_Window_Slider*0.001
;delt=1e-10
;PulseWidth=0.0
;print,'delt =',delt


widget_control,(*pState_mabc).Time_Window,get_value = Time_Window

if Time_Window eq 0 then begin
    if mica eq 1 then delt/=3.0 ;004 reflection
    if mica eq 2 then delt/=6.0 ;006 reflection
    if mica eq 3 then delt/=6.0 ;008 reflection
endif
;

delt*=TimeWinRatio ;convert to time window at choppers
;print,'foo =',360.0*50.0*delt
deltmax=omega/(360.0*50.0)
if delt gt deltmax then delt = deltmax

;widget_control,(*pState_mabc).analyser_angle_field,get_value = theta


theta_index=widget_info((*pState_mabc).analyser_angle_droplist,/droplist_select)

theta=(*pState_mabc).Calibration_Angles_str[1,theta_index]

;if theta eq '' then theta='50.03 ' & widget_control,(*pState_mabc).analyser_angle_field,set_value = theta
theta=float(theta[0])
;print, 'theta = ',theta
;if theta lt 50.03 then theta = 50.03 & widget_control,(*pState_mabc).analyser_angle_field,set_value = theta
;if theta gt 87.42 then theta = 87.42 & widget_control,(*pState_mabc).analyser_angle_field,set_value = theta


E_analyser=81.80321/(Bragg(dspacing,theta))^2
;print,'E_analyser = ' ,E_analyser
widget_control,(*pState_mabc).Analyser_Energy_Field,set_value = E_analyser



Em=Em_set+E_analyser
;
;these expressions are not correct; they are needed just for the input to the FX_ROOT function.
; vl and and vu should encompass vc.
;
;
Em*=conv
vm=sqrt((Em*2.0)/mn)
tm=l24/vm
tl=tm+delt
tu=tm-delt
vl=l24/tl
vu=l24/tu
;
;find vc
;first define initial guess
;guess =[lower_limit,middle, upper_limit]
;inital guess is vm
vec=[vl,vm,vu]
vc=FX_ROOT(vec, 'vc_find',/double)
;print,'vc =',vc
; calculate master chopper phase
master_freq=50.0*Master
Master_phase=180.0
ChopperPhasesFine=0
while ChopperPhasesFine eq 0 do begin
MasterTimeDelay=1/(50.0*4*Master)+(Master_phase/(360.0*50.0*Master))
;calculate snail phase
;
SnailTimeDelay=MasterTimeDelay+l21/vc-0.005
while SnailTimeDelay lt 0 do begin
SnailTimeDelay+=0.02
endwhile
Snail_Phase=360.0*(SnailTimeDelay/0.02)
;
RabbitTimeDelay=MasterTimeDelay+l23/vc-0.005
while RabbitTimeDelay lt 0 do begin
RabbitTimeDelay+=0.02
endwhile
while RabbitTimeDelay gt 0.02 do begin
RabbitTimeDelay-=0.02
endwhile
Rabbit_Phase=360.0*(RabbitTimeDelay/0.02)
;
Chopper4TimeDelay=MasterTimeDelay+l24/vc-0.005-((0.02/360.0)*((omega-(360.0*50.0*delt))/2.0))
while Chopper4TimeDelay lt 0 do begin
Chopper4TimeDelay+=0.02
endwhile
while Chopper4TimeDelay gt 0.02 do begin
Chopper4TimeDelay-=0.02
endwhile
chopper4_phase=360.0*(Chopper4TimeDelay/0.02)
;
Chopper4TimeDelay=MasterTimeDelay+l24/vc-0.005-((0.02/360.0)*((omega-(360.0*50.0*delt))/2.0))
while Chopper4TimeDelay lt 0 do begin
Chopper4TimeDelay+=0.02
endwhile
while Chopper4TimeDelay gt 0.02 do begin
Chopper4TimeDelay-=0.02
endwhile
chopper4_phase=360.0*(Chopper4TimeDelay/0.02)
;
Chopper5TimeDelay=MasterTimeDelay+l25/vc-0.005+((0.02/360.0)*((omega-(360.0*50.0*delt))/2.0))
while Chopper5TimeDelay lt 0 do begin
Chopper5TimeDelay+=0.02
endwhile
while Chopper5TimeDelay gt 0.02 do begin
Chopper5TimeDelay-=0.02
endwhile
chopper5_phase=360.0*(Chopper5TimeDelay/0.02)
;
if (Snail_Phase ge 5.0) and (Snail_Phase le 355.0) and $
    (Master_phase ge 5.0) and (Master_phase le 355.0) and $
    (rabbit_phase ge 5.0) and (rabbit_phase le 355.0) and $
    (chopper4_phase ge 5.0) and (chopper4_phase le 355.0) and $
    (chopper5_phase ge 5.0) and (chopper5_phase le 355.0) then begin
    ChopperPhasesFine = 1
endif else begin
Master_phase+=1.0
    if Master_phase eq 180.0 then begin
    msg=strarr(2)
    msg[0]='Unable to find acceptable phases for all five choppers.'
    msg[1]='Please vary the input parameters'
    void = dialog_message(dialog_parent = event.top,/error,msg)
    return
    endif
endelse
endwhile
;
;
;Find lower and higher energy limits
tc24=l24/vc
tc25=l25/vc
;vl=l25/(tc25+(delt/2.0)+PulseWidth)
;vu=l24/(tc24-(delt/2.0)-PulseWidth)
vl=l24/(tc24+(delt/2.0)+PulseWidth)
vu=l25/(tc25-(delt/2.0)-PulseWidth)
El=0.5*mn*vl^2
Eu=0.5*mn*vu^2
El/=conv ;convert to meV
Eu/=conv ;convert to meV
;print,'El =',El
;print,'Eu =',Eu


;
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=D/v_sec
tl_prim=lprim/vl
tu_prim=lprim/vu
tm_prim=lprim/vm
;
;print,'tl_prim: ',tl_prim
;print,'tu_prim: ',tu_prim
;print,'t_sec: ',t_sec
;print,'t_sec: ',1e6*t_sec

tofl=tl_prim+t_sec
tofu=tu_prim+t_sec
tofm=tm_prim+t_sec
;
tofl*=1e6
tofu*=1e6
tofm*=1e6
;
;print,'E_analyser =',E_analyser
;widget_control,(*pState_mabc).E_analyser,set_value=E_analyser

E_lower=El-E_analyser
E_upper=Eu-E_analyser
;print,'E_lower =',E_lower
;print,'E_upper =',E_upper
E_centre=(E_upper+E_lower)/2.0



(*pState_mabc).Ewinl=E_lower
(*pState_mabc).Ewinc=Em_set
(*pState_mabc).Ewinu=E_upper

tofoutput=strarr(3,3)
tofl=float(tofl)
tofu=float(tofu)
tofoutput[0,0]=tofl
tofoutput[0,1]=tofm
tofoutput[0,2]=tofu
;
tofoutput[1,0]=float(E_lower)
tofoutput[1,1]=Em_set
tofoutput[1,2]=float(E_upper)
;
tofoutput[2,0]=float(El)
tofoutput[2,1]=Em/conv
tofoutput[2,2]=float(Eu)

(*pState_mabc).tofoutput=tofoutput
widget_control,(*pState_mabc).tofwindow,set_value=tofoutput
widget_control,(*pState_mabc).Energy_Window_Width,set_value=E_upper-E_lower


;write chopper phases into table
widget_control,(*pState_mabc).chopper_table,get_value =output
output[0,0]=Snail_Phase
output[0,1]=Master_phase
output[0,2]=rabbit_phase
output[0,3]=float(chopper4_phase)
output[0,4]=float(chopper5_phase)
output[1,1]=Master_freq

widget_control,(*pState_mabc).chopper_table,set_value=output



; first neutrons that are detected in TOFMon
tu_TOFMon=1e6*lTOFMon/vu
; last neutrons that are detected in TOFMon
tl_TOFMon=1e6*lTOFMon/vl



; first neutrons that are detected in PostTOFMon
tu_TOFPostMon=1e6*lTOFPostMon/vu
; last neutrons that are detected in TOFMon
tl_TOFPostMon=1e6*lTOFPostMon/vl
;
;last neutrons are from v002 reflection
;
E_micaanalyser=81.80321/(Bragg(dspace_array[mica],theta))^2
v_micasec=sqrt(E_micaanalyser*conv*2.0/mn)
t_micasec=D/v_micasec
;print,'t_002sec: ',t_002sec
last_neutrons=tl_prim+t_micasec
last_neutrons*=1e6
;
widget_control,(*pState_mabc).First_Neutrons_Time,set_value=tu_TOFMon
widget_control,(*pState_mabc).End_Monitor_Time,set_value=tl_TOFMon
widget_control,(*pState_mabc).First_PostMonitor_Time,set_value=tu_TOFPostMon
widget_control,(*pState_mabc).End_PostMonitor_Time,set_value=tl_TOFPostMon
widget_control,(*pState_mabc).Last_Neutrons_Time,set_value=last_neutrons
tof_window=last_neutrons-tu_TOFMon
widget_control,(*pState_mabc).tofwindow_field,set_value=tof_window
;
;TOF_start=tu_TOFMon-(1e6*(tl_prim-tu_prim))
TOF_end=last_neutrons+((1e6*(tl_prim-tu_prim)))
TOF_end=tofm+(HP/2.0)


TOF_start=TOF_end-HP
;
;anticipate the timeoffsets
timeoffsets=(*pState_mabc).timeoffsets
offset=0.0
masterfundamental=fix(Master[0])
if masterfundamental eq 1 then offset=timeoffsets.master1_timeoffset
if masterfundamental eq 2 then offset=timeoffsets.master2_timeoffset
if masterfundamental eq 3 then offset=timeoffsets.master3_timeoffset
if masterfundamental eq 4 then offset=timeoffsets.master4_timeoffset
if masterfundamental eq 5 then offset=timeoffsets.master5_timeoffset
if masterfundamental eq 6 then offset=timeoffsets.master6_timeoffset
if masterfundamental eq 7 then offset=timeoffsets.master7_timeoffset
;
TOF_start-=offset
TOF_end-=offset
;
TOF_start=long(TOF_start)
tof_width=TOF_end-TOF_start
tof_width=long(tof_width)


widget_control,(*pState_mabc).TimeBinNumber,get_value=TimeBinNumber
TimeBinNumber=long(TimeBinNumber[0])
if TimeBinNumber lt 1 then TimeBinNumber = 1
tof_step=(tofl-tofu)/(TimeBinNumber)

;
tof_step*=10
tof_step=long(tof_step)
if TOF_step gt 1000 then TOF_step =  1000

;
if TimeBins.filefound eq 1 then begin
TimeBinStep_arr=TimeBins.TimeBinStep_arr
TimeBinNumber_arr=TimeBins.TimeBinNumber_arr
TOF_step_original=TOF_step
difference=TOF_step-TimeBinStep_arr
mindiff=min(difference,minsubscript,/absolute)
TOF_step=TimeBinStep_arr[minsubscript]
TimeBinNumber_Fanni=TimeBinNumber_arr[minsubscript]
    if TOF_step_original lt TOF_step then begin
       if minsubscript gt 0 then begin
       TOF_step = TimeBinStep_arr[minsubscript-1]
       TimeBinNumber_Fanni=TimeBinNumber_arr[minsubscript-1]
       endif
    endif
endif
;
;
tof_step=float(tof_step/10.0)
TimeBinNumber=((tofl-tofu)/TOF_step)
widget_control,(*pState_mabc).TimeBinNumber,set_value=fix(TimeBinNumber)
;
widget_control,(*pState_mabc).TimeBinStart,set_value=TOF_start
widget_control,(*pState_mabc).TimeBinWidth,set_value=TOF_width
widget_control,(*pState_mabc).TimeBinStep,set_value=TOF_step
widget_control,(*pState_mabc).TotalTimeBinNumber,set_value=long(TOF_width/TOF_step)
;
TimeBinIndices=GenerateTimebinIndices_MABC(event,vl,vu,TOF_start,TOF_width,TOF_step,mica,theta)
;print,'TimeBinIndices: ',TimeBinIndices
(*pState_mabc).TimeBinIndices=TimeBinIndices
widget_control,(*pState_mabc).A1_field,set_value=tofm
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABCCross_Plot,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pstate_mabc).Plot_cross,get_value = Plot_cross
widget_control,(*pstate_mabc).CrossValue_Field,get_value = CrossValue
CrossValue=float(CrossValue[0])
widget_control,(*pState_mabc).display,get_value=display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
GaussCrossY=*(*pState_mabc).GaussCrossY ;fltarr(10,2,2,N_XCoords,N_YCoords)
GaussCrossX=*(*pState_mabc).GaussCrossX ;fltarr(10,2,2,N_XCoords,N_YCoords)
GaussCrossParameters=*(*pState_mabc).GaussCrossParameters; fltarr(10,2,(N_XCoords+N_YCoords),6)

XCoords=*(*pState_mabc).XCoords
YCoords=*(*pState_mabc).YCoords
N_XCoords=n_elements(XCoords)
N_YCoords=n_elements(YCoords)
if display eq 0 then begin
DataArray_z=*(*pState_mabc).DataArray_Zint
ytitle='Intensity of Gauss Peaks'
endif else begin
DataArray_z=*(*pState_mabc). DataArray_ZPeak
ytitle='Gaussian Deviation Factor'
endelse

z=fltarr(N_XCoords,N_YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
k=0
xindex=0
yindex=0
for xindex=0,N_XCoords-1 do begin
    for yindex=0,N_YCoords-1 do begin
    z[xindex,yindex]=DataArray_z[Analyser_Result,k]
    k+=1
    endfor
endfor
;
if Plot_cross eq 0 then begin
index=(where(CrossValue eq XCoords))[0]
;help,crossvalue
;help,XCoords
;PRINT,'XCoords: ',XCoords
;PRINT,'CrossValue: ',CrossValue
;help,z
;help,index
yvar=z[index,*]
xvar=YCoords
xtitle='Ordinate Coordinates'
yfit=GaussCrossY[Analyser_Result,display,Plot_cross,index,*]
xfit=GaussCrossX[Analyser_Result,display,Plot_cross,index,*]
ParameterIndex=index
endif else begin
index=(where(CrossValue eq YCoords))[0]
yvar=z[*,index]
xvar=XCoords
xtitle='Abscissa Coordinates'
yfit=GaussCrossY[Analyser_Result,display,Plot_cross,*,index]
xfit=GaussCrossX[Analyser_Result,display,Plot_cross,*,index]
ParameterIndex=index+N_XCoords
endelse

xfit=reform(xfit)
yfit=reform(yfit)


if (*pState_mabc).autoscale_cross eq 1 then begin
  xlo = min(xvar) & xhi = max(xvar)
  whereneyero=where(yvar ne 0.0,count)
  if count ne 0 then begin
  ylo = min(yvar[whereneyero]) & yhi = max(yvar)
 if max(yfit) gt yhi then yhi = max(yfit)
  endif else begin
    ylo = min(yvar) & yhi = max(yvar)
 endelse
  (*pState_mabc).xrange_cross = [xlo,xhi]
  (*pState_mabc).yrange_cross = [ylo,yhi]
endif



wset,(*pState_mabc).winPix_cross
plot,xvar,yvar,xrange = (*pstate_mabc).xrange_cross,yrange = (*pstate_mabc).yrange_cross, $
     xstyle = 1,ystyle = 1,xtitle = xtitle, $
     ytitle = ytitle, title = 'Cross Section Through Contour Plot',linestyle = 0, $
     thick = 1.0, psym=-4, symsize=1.0,min_value=0.1

;print,'xfit: ',xfit
;print,'yfit: ',yfit

  oplot,xfit,yfit,linestyle = 2, thick = 2.0, psym=0, symsize=1.0,min_value=0.1,color=3


wset,(*pState_mabc).winVis_cross

device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_cross]


coeff=GaussCrossParameters[Analyser_Result,display,ParameterIndex,*]

widget_control,(*pstate_mabc).A0_field_cross,set_value = string(coeff[0])
widget_control,(*pstate_mabc).A1_field_cross,set_value = string(coeff[1])
widget_control,(*pstate_mabc).A2_field_cross,set_value = string(coeff[2])
widget_control,(*pstate_mabc).A3_field_cross,set_value = string(coeff[3])
widget_control,(*pstate_mabc).A4_field_cross,set_value = string(coeff[4])
widget_control,(*pstate_mabc).A5_field_cross,set_value = string(coeff[5])


(*pState_mabc).pix = 2


end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABCGauss1D_Plot,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Gauss1D_Display,get_value=Gauss1D_Display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result

Gaussgauss1dX=*(*pState_mabc).Gaussgauss1dX ;fltarr(10,2,N_XCoords)
Gaussgauss1dY=*(*pState_mabc).Gaussgauss1dY ;fltarr(10,2,N_XCoords)
Gaussgauss1dParameters=*(*pState_mabc).Gaussgauss1dParameters; fltarr(10,2,6)

XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(XCoords)


if Gauss1D_Display eq 0 then begin
DataArray_z=*(*pState_mabc).DataArray_Zint
ytitle='Intensity of Gauss Peaks'
endif else begin
DataArray_z=*(*pState_mabc). DataArray_ZPeak
ytitle='Gaussian Deviation Factor'
endelse

y=fltarr(N_XCoords)
y[*]=DataArray_z[Analyser_Result,*]
x=XCoords
xtitle='Abscissa Coordinates'
;
yfit=Gaussgauss1dY[Analyser_Result,Gauss1D_display,*]
xfit=Gaussgauss1dX[Analyser_Result,Gauss1D_display,*]

xfit=reform(xfit)
yfit=reform(yfit)

if (*pState_mabc).autoscale_Gauss1D eq 1 then begin
  xlo = min(x) & xhi = max(x)
  whereneyero=where(y ne 0.0,count)
  if count ne 0 then begin
  ylo = min(y[whereneyero]) & yhi = max(y)
   if max(yfit) gt yhi then yhi = max(yfit)
  endif else begin
    ylo = min(y) & yhi = max(y)
 endelse
  (*pState_mabc).xrange_Gauss1D = [xlo,xhi]
  (*pState_mabc).yrange_Gauss1D = [ylo,yhi]
endif



wset,(*pState_mabc).winPix_Gauss1D
plot,x,y,xrange = (*pstate_mabc).xrange_Gauss1D,yrange = (*pstate_mabc).yrange_Gauss1D, $
     xstyle = 1,ystyle = 1,xtitle = xtitle, $
     ytitle = ytitle, title = 'Analysis of Fit Parameters',linestyle = 0, $
     thick = 1.0, psym=-4, symsize=1.0,min_value=0.1

oplot,xfit,yfit,linestyle = 2, thick = 2.0, psym=0, symsize=1.0,min_value=0.1,color=3


;print,'xfit: ',xfit
;print,'yfit: ',yfit

wset,(*pState_mabc).winVis_Gauss1D

device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_Gauss1D]


coeff=Gaussgauss1dParameters[Analyser_Result,Gauss1D_display,*]

widget_control,(*pstate_mabc).A0_field_gauss1d,set_value = string(coeff[0])
widget_control,(*pstate_mabc).A1_field_gauss1d,set_value = string(coeff[1])
widget_control,(*pstate_mabc).A2_field_gauss1d,set_value = string(coeff[2])
widget_control,(*pstate_mabc).A3_field_gauss1d,set_value = string(coeff[3])
widget_control,(*pstate_mabc).A4_field_gauss1d,set_value = string(coeff[4])
widget_control,(*pstate_mabc).A5_field_gauss1d,set_value = string(coeff[5])


(*pState_mabc).pix = 4


end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABCPlot_gauss2D,event

widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).display,get_value=display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pState_mabc).ColourGradient,get_value=CG
DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
XCoords=*(*pState_mabc).XCoords
YCoords=*(*pState_mabc).YCoords
N_XCoords=n_elements(XCoords)
N_YCoords=n_elements(YCoords)
if display eq 0 then DataArray_z=*(*pState_mabc).DataArray_Zint
if display eq 1 then DataArray_z=*(*pState_mabc).DataArray_ZPeak
x=XCoords
y=YCoords
z=fltarr(N_XCoords,N_YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
k=0
xindex=0
xindex=0
for xindex=0,N_XCoords-1 do begin
    for yindex=0,N_YCoords-1 do begin
    z[xindex,yindex]=DataArray_z[Analyser_Result,k]
    k+=1
    endfor
endfor


;index=where(z eq max(z),count)
;print,index
;if count eq 0 then return
;xindex=long(index/N_XCoords)
;yindex=index-(xindex*N_XCoords)
;xpos=XCoords[xindex]
;ypos=YCoords[yindex]
;

zstep=(max(z)-min(z))/100.0
zmin=min(z)+zstep*(CG-1)
index=where(z lt zmin,count)

if count ne 0 then z[index] = zmin


;help,zmin

if (*pState_mabc).autoscale_gauss eq 1 then begin
  xlo = min(x) & xhi = max(x)
  ylo = min(y) & yhi = max(y)
  (*pState_mabc).xrange_gauss = [xlo,xhi]
  (*pState_mabc).yrange_gauss = [ylo,yhi]
endif

wset,(*pState_mabc).winPix_gauss2D


c=Indgen(12)+1
contour,z,x,y,xtitle = 'Abscissa', $
     ytitle = 'Ordinate',xrange = (*pState_mabc).xrange_gauss,yrange = (*pState_mabc).yrange_gauss, $
     xstyle = 1,ystyle = 1,c_colors=c,nlevels=12,/fill,min_value=0.1
wset,(*pState_mabc).winVis_gauss

device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_gauss2D]
;print,'woof'
(*pState_mabc).pix = 1


end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABCdraw_gauss2D,event
widget_control,event.top,get_uvalue = pState_mabc

if (*pState_mabc).pix ne 1 then begin
        MABCPlot_gauss2D,event
(*pState_mabc).pix = 1
endif


case event.type of
0:  begin       ; button press
      (*pState_mabc).mouse_gauss = event.press
      if (*pState_mabc).mouse_gauss eq 4 then begin
        (*pState_mabc).autoscale_gauss = 1

        wset,(*pState_mabc).winPix_gauss2D
        MABCPlot_gauss2D,event
        wset,(*pState_mabc).winVis_gauss
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_gauss2D]
      endif
      if (*pState_mabc).mouse_gauss eq 1 then begin
        (*pState_mabc).xbox_gauss[0] = event.x
        (*pState_mabc).ybox_gauss[0] = event.y
        wset,(*pState_mabc).winVis_gauss
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_gauss2D]
        empty
        (*pState_mabc).autoscale_gauss = 0
        widget_control,(*pState_mabc).win_gauss2D,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pState_mabc).mouse_gauss eq 1 then begin
      xll = (*pState_mabc).xbox_gauss[0] < (*pState_mabc).xbox_gauss[1]
      yll = (*pState_mabc).ybox_gauss[0] < (*pState_mabc).ybox_gauss[1]
      w = abs((*pState_mabc).xbox_gauss[1] - (*pState_mabc).xbox_gauss[0])
      h = abs((*pState_mabc).ybox_gauss[1] - (*pState_mabc).ybox_gauss[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      (*pState_mabc).xrange_gauss = [ll[0],ur[0]]
      (*pState_mabc).yrange_gauss = [ll[1],ur[1]]
      wset,(*pState_mabc).winPix_gauss2D
        MABCPlot_gauss2D,event
      wset,(*pState_mabc).winVis_gauss
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_gauss2D]
      (*pState_mabc).mouse_gauss = 0B
      widget_control,(*pState_mabc).win_gauss2D,draw_motion_events = 0
     endif
     if (*pState_mabc).mouse_gauss eq 4 then begin
      wset,(*pState_mabc).winPix_gauss2D
        MABCPlot_gauss2D,event
      wset,(*pState_mabc).winVis_gauss
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_gauss2D]
      (*pState_mabc).mouse_gauss = 0B
      widget_control,(*pState_mabc).win_gauss2D,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse_gauss motion
      if (*pState_mabc).mouse_gauss eq 1 then begin
       (*pState_mabc).xbox_gauss[1] = event.x
       (*pState_mabc).ybox_gauss[1] = event.y
       xc = [(*pState_mabc).xbox_gauss[0],event.x,event.x,$
             (*pState_mabc).xbox_gauss[0],$
             (*pState_mabc).xbox_gauss[0]]
       yc = [(*pState_mabc).ybox_gauss[0],(*pState_mabc).ybox_gauss[0],$
             event.y,event.y,$
             (*pState_mabc).ybox_gauss[0]]
       wset,(*pState_mabc).winVis_gauss
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_gauss2D]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
end


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mabc_Gauss1DParameters,event
widget_control,event.top,get_uvalue = pstate_mabc
;
xrange=(*pstate_mabc).xrange_fitwindowGauss1D
yrange=(*pstate_mabc).yrange_fitwindowGauss1D
;
xmin=xrange[0]
xmax=xrange[1]

;
;
widget_control,(*pState_mabc).Gauss1D_display,get_value=Gauss1D_display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
x=*(*pState_mabc).XCoords
if Gauss1D_display eq 0 then begin
DataArray_z=*(*pState_mabc).DataArray_Zint
endif else begin
DataArray_z=*(*pState_mabc). DataArray_ZPeak
endelse
y=DataArray_z[Analyser_Result,*]
;
whereinxrange=where(x ge xrange[0],count)
if count eq 0 then return
subscriptref=whereinxrange
x_1stcull=x[whereinxrange]
y_1stcull=y[whereinxrange]
;print,'y_1stcull',y_1stcull
whereinxrange=where(x_1stcull lt xrange[1],count)
if count eq 0 then return
subscriptref=subscriptref[0]+whereinxrange
x_2ndcull=x_1stcull[whereinxrange]
y_2ndcull=y_1stcull[whereinxrange]
xwin=x_2ndcull
ywin=y_2ndcull
;print,'xwin = ',xwin
;print,'ywin = ',ywin
A0=max(ywin)
A1=((max(xwin)-min(xwin))/2.0)+min(xwin)
A2=((max(xwin)-min(xwin))/12.0)
widget_control,(*pstate_mabc).xmin_field_Gauss1D,set_value = xmin
widget_control,(*pstate_mabc).xmax_field_Gauss1D,set_value = xmax
widget_control,(*pstate_mabc).A0_field_Gauss1D,set_value = A0
widget_control,(*pstate_mabc).A1_field_Gauss1D,set_value = A1
widget_control,(*pstate_mabc).A2_field_Gauss1D,set_value = A2
widget_control,(*pstate_mabc).A3_field_Gauss1D,set_value = '0'
widget_control,(*pstate_mabc).A4_field_Gauss1D,set_value = '0'
widget_control,(*pstate_mabc).A5_field_Gauss1D,set_value = '0'

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mabc_CrossParameters,event
widget_control,event.top,get_uvalue = pstate_mabc
;
xrange=(*pstate_mabc).xrange_fitwindowCross
yrange=(*pstate_mabc).yrange_fitwindowCross
;
xmin=xrange[0]
xmax=xrange[1]
;

widget_control,(*pstate_mabc).Plot_cross,get_value = Plot_cross
widget_control,(*pstate_mabc).CrossValue_Field,get_value = CrossValue
CrossValue=float(CrossValue[0])
widget_control,(*pState_mabc).display,get_value=display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
XCoords=*(*pState_mabc).XCoords
YCoords=*(*pState_mabc).YCoords
N_XCoords=n_elements(XCoords)
N_YCoords=n_elements(YCoords)
if display eq 0 then begin
DataArray_z=*(*pState_mabc).DataArray_Zint
endif else begin
DataArray_z=*(*pState_mabc). DataArray_ZPeak
endelse

z=fltarr(N_XCoords,N_YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
k=0
xindex=0
xindex=0
for xindex=0,N_XCoords-1 do begin
    for yindex=0,N_YCoords-1 do begin
    z[xindex,yindex]=DataArray_z[Analyser_Result,k]
    k+=1
    endfor
endfor
;
if Plot_cross eq 0 then begin
index=(where(CrossValue eq XCoords))[0]
y=z[index,*]
x=YCoords
endif else begin
index=(where(CrossValue eq YCoords))[0]
y=z[*,index]
x=XCoords
endelse



whereinxrange=where(x ge xrange[0],count)
if count eq 0 then return
subscriptref=whereinxrange
x_1stcull=x[whereinxrange]
y_1stcull=y[whereinxrange]
;print,'y_1stcull',y_1stcull
whereinxrange=where(x_1stcull lt xrange[1],count)
if count eq 0 then return
subscriptref=subscriptref[0]+whereinxrange
x_2ndcull=x_1stcull[whereinxrange]
y_2ndcull=y_1stcull[whereinxrange]
xwin=x_2ndcull
ywin=y_2ndcull
;print,'xwin = ',xwin
;print,'ywin = ',ywin
A0=max(ywin)
A1=((max(xwin)-min(xwin))/2.0)+min(xwin)
A2=((max(xwin)-min(xwin))/12.0)
widget_control,(*pstate_mabc).xmin_field_cross,set_value = xmin
widget_control,(*pstate_mabc).xmax_field_cross,set_value = xmax
widget_control,(*pstate_mabc).A0_field_cross,set_value = A0
widget_control,(*pstate_mabc).A1_field_cross,set_value = A1
widget_control,(*pstate_mabc).A2_field_cross,set_value = A2
widget_control,(*pstate_mabc).A3_field_cross,set_value = '0'
widget_control,(*pstate_mabc).A4_field_cross,set_value = '0'
widget_control,(*pstate_mabc).A5_field_cross,set_value = '0'

end



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mabc_GaussParameters,event
widget_control,event.top,get_uvalue = pstate_mabc
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
DataType=(*pState_mabc).DataType
;
xrange=(*pstate_mabc).xrange_fitwindow
yrange=(*pstate_mabc).yrange_fitwindow
;
xmin=xrange[0]
xmax=xrange[1]
;
widget_control,(*pstate_mabc).raw_SliderValue,get_value = spectrum_number
spectrum_number=fix(spectrum_number[0])
spectrum_number-=1
DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(XCoords)

if DataType eq 0 then begin
n_TotalSpectra=N_XCoords
x=DataArray_x(Analyser_Result,spectrum_number,*)
y=DataArray_y(Analyser_Result,spectrum_number,*)
endif else begin
YCoords=*(*pState_mabc).YCoords
N_YCoords=n_elements(YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
xnum=spectrum_number/N_YCoords
ynum=spectrum_number-xnum*N_YCoords
;
x=DataArray_x(Analyser_Result,xnum,ynum,*)
y=DataArray_y(Analyser_Result,xnum,ynum,*)
;
endelse


whereinxrange=where(x ge xrange[0],count)
if count eq 0 then return
subscriptref=whereinxrange
x_1stcull=x[whereinxrange]
y_1stcull=y[whereinxrange]
;print,'y_1stcull',y_1stcull
whereinxrange=where(x_1stcull lt xrange[1],count)
if count eq 0 then return
subscriptref=subscriptref[0]+whereinxrange
x_2ndcull=x_1stcull[whereinxrange]
y_2ndcull=y_1stcull[whereinxrange]
xwin=x_2ndcull
ywin=y_2ndcull
;print,'xwin = ',xwin
;print,'ywin = ',ywin
A0=max(ywin)
A1=((max(xwin)-min(xwin))/2.0)+min(xwin)
A2=((max(xwin)-min(xwin))/12.0)
widget_control,(*pstate_mabc).xmin_field,set_value = xmin
widget_control,(*pstate_mabc).xmax_field,set_value = xmax
widget_control,(*pstate_mabc).A0_field,set_value = A0
widget_control,(*pstate_mabc).A1_field,set_value = A1
widget_control,(*pstate_mabc).A2_field,set_value = A2
widget_control,(*pstate_mabc).A3_field,set_value = '0'
widget_control,(*pstate_mabc).A4_field,set_value = '0'
widget_control,(*pstate_mabc).A5_field,set_value = '0'

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mabcPlot_raw,event
widget_control,event.top,get_uvalue = pstate_mabc
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pstate_mabc).raw_SliderValue,get_value = spectrum_number
spectrum_number=fix(spectrum_number[0])
spectrum_number-=1
GaussParameters=*(*pState_mabc).GaussParameters  ; fltarr(10,n_TotalSpectra,6)
DataType=(*pState_mabc).DataType

IF DataType EQ 0 THEN BEGIN
DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(XCoords)
n_TotalSpectra=N_XCoords
x=DataArray_x[Analyser_Result,spectrum_number,*]
y=DataArray_y[Analyser_Result,spectrum_number,*]

ENDIF ELSE BEGIN

DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
XCoords=*(*pState_mabc).XCoords
YCoords=*(*pState_mabc).YCoords
N_XCoords=n_elements(XCoords)
N_YCoords=n_elements(YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
;print,n_TotalSpectra

;print,'spectrum_number: ',spectrum_number
xnum=spectrum_number/N_YCoords
ynum=spectrum_number-xnum*N_YCoords
;
;help,DataArray_x
;print,'xnum: ',xnum
;print,'ynum: ',ynum
;print,''

x=DataArray_x[Analyser_Result,xnum,ynum,*]
y=DataArray_y[Analyser_Result,xnum,ynum,*]
ENDELSE


if (*pState_mabc).autoscale_raw eq 1 then begin
  xlo = min(x) & xhi = max(x)
  ylo = min(y) & yhi = max(y)
  (*pstate_mabc).xrange_raw = [xlo,xhi]
  (*pstate_mabc).yrange_raw = [ylo,yhi]
endif
;
wset,(*pState_mabc).winPix_raw
plot,x,y,xrange = (*pstate_mabc).xrange_raw,yrange = (*pstate_mabc).yrange_raw, $
     xstyle = 1,ystyle = 1,xtitle = 'Time / us', $
     ytitle = 'Intensity', title = 'TOF Data',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0,xticks=2

Gaussfits_x=*(*pState_mabc).Gaussfits_x
Gaussfits_y=*(*pState_mabc).Gaussfits_y
xfit=Gaussfits_x[Analyser_Result,spectrum_number,*]
yfit=Gaussfits_y[Analyser_Result,spectrum_number,*]

  oplot,xfit,yfit,linestyle = 2, thick = 2.0, psym=0, symsize=1.0,min_value=0.1,color=6

xlims=!x.crange
ylims=!y.crange
xpos=xlims[0]+(xlims[1]-xlims[0])*0.6

IF DataType EQ 0 THEN BEGIN
;help,XCoords
;print,strtrim(string(XCoords[spectrum_number]),2)
;print, 'xpos: ',xpos
;print,'0.9*ylims[1]: ',0.9*ylims[1]
;xyouts,xpos,0.9*ylims[1],"Abscissa = "+strtrim(string(XCoords[spectrum_number]),2)
xyouts,xpos,0.9*ylims[1],"Abscissa = "+strtrim(string(XCoords[spectrum_number]),2),color=9
ENDIF ELSE BEGIN
xyouts,xpos,0.9*ylims[1],"Abscissa = "+strtrim(string(XCoords[xnum]),2),color=9
xyouts,xpos,0.85*ylims[1],"Ordinate = "+strtrim(string(YCoords[ynum]),2),color=9
ENDELSE

wset,(*pState_mabc).winVis_raw
device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_raw]
(*pState_mabc).pix = 0


coeff=GaussParameters[Analyser_Result,spectrum_number,*]
;
widget_control,(*pstate_mabc).A0_field,set_value = string(coeff[0])
widget_control,(*pstate_mabc).A1_field,set_value = string(coeff[1])
widget_control,(*pstate_mabc).A2_field,set_value = string(coeff[2])
widget_control,(*pstate_mabc).A3_field,set_value = string(coeff[3])
widget_control,(*pstate_mabc).A4_field,set_value = string(coeff[4])
widget_control,(*pstate_mabc).A5_field,set_value = string(coeff[5])

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABCGAUSS1D_DRAW,event
widget_control,event.top,get_uvalue = pstate_mabc


if (*pState_mabc).pix ne 4 then begin
        MABCGauss1D_Plot,event
(*pState_mabc).pix = 4
endif


widget_control,(*pstate_mabc).Mouse_Action_Gauss1D,get_value = val
if val eq 0 then begin
case event.type of
0:  begin       ; button press
      (*pstate_mabc).mouse_Gauss1D = event.press
      if (*pstate_mabc).mouse_Gauss1D eq 4 then begin
        (*pstate_mabc).autoscale_Gauss1D = 1

        wset,(*pstate_mabc).winpix_Gauss1D
        MABCGauss1D_Plot,event
        wset,(*pstate_mabc).winvis_Gauss1D
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
      endif
      if (*pstate_mabc).mouse_Gauss1D eq 1 then begin
        (*pstate_mabc).xbox_Gauss1D[0] = event.x
        (*pstate_mabc).ybox_Gauss1D[0] = event.y
        wset,(*pstate_mabc).winvis_Gauss1D
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
        empty
        (*pstate_mabc).autoscale_Gauss1D = 0
        widget_control,(*pstate_mabc).win_Gauss1D,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pstate_mabc).mouse_Gauss1D eq 1 then begin
      xll = (*pstate_mabc).xbox_Gauss1D[0] < (*pstate_mabc).xbox_Gauss1D[1]
      yll = (*pstate_mabc).ybox_Gauss1D[0] < (*pstate_mabc).ybox_Gauss1D[1]
      w = abs((*pstate_mabc).xbox_Gauss1D[1] - (*pstate_mabc).xbox_Gauss1D[0])
      h = abs((*pstate_mabc).ybox_Gauss1D[1] - (*pstate_mabc).ybox_Gauss1D[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      (*pstate_mabc).xrange_Gauss1D = [ll[0],ur[0]]
      (*pstate_mabc).yrange_Gauss1D= [ll[1],ur[1]]
      wset,(*pstate_mabc).winpix_Gauss1D
        MABCGauss1D_Plot,event
      wset,(*pstate_mabc).winvis_Gauss1D
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
      (*pstate_mabc).mouse_Gauss1D = 0B
      widget_control,(*pstate_mabc).win_Gauss1D,draw_motion_events = 0
     endif
     if (*pstate_mabc).mouse_Gauss1D eq 4 then begin
      wset,(*pstate_mabc).winpix_Gauss1D
        MABCGauss1D_Plot,event
      wset,(*pstate_mabc).winvis_Gauss1D
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
      (*pstate_mabc).mouse_Gauss1D = 0B
      widget_control,(*pstate_mabc).win_Gauss1D,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pstate_mabc).mouse_Gauss1D eq 1 then begin
       (*pstate_mabc).xbox_Gauss1D[1] = event.x
       (*pstate_mabc).ybox_Gauss1D[1] = event.y
       xc = [(*pstate_mabc).xbox_Gauss1D[0],event.x,event.x,$
             (*pstate_mabc).xbox_Gauss1D[0],$
             (*pstate_mabc).xbox_Gauss1D[0]]
       yc = [(*pstate_mabc).ybox_Gauss1D[0],(*pstate_mabc).ybox_Gauss1D[0],$
             event.y,event.y,$
             (*pstate_mabc).ybox_Gauss1D[0]]
       wset,(*pstate_mabc).winvis_Gauss1D
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
return
endif
if val eq 1 then begin
case event.type of
0:  begin       ; button press
      (*pstate_mabc).mouse_Gauss1D = event.press
      if (*pstate_mabc).mouse_Gauss1D eq 4 then begin
        (*pstate_mabc).autoscale_Gauss1D = 1

        wset,(*pstate_mabc).winpix_Gauss1D
        MABCGauss1D_Plot,event
        wset,(*pstate_mabc).winvis_Gauss1D
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
      endif
      if (*pstate_mabc).mouse_Gauss1D eq 1 then begin
        (*pstate_mabc).xbox_Gauss1D[0] = event.x
        (*pstate_mabc).ybox_Gauss1D[0] = event.y
        wset,(*pstate_mabc).winvis_Gauss1D
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
        empty
        (*pstate_mabc).autoscale_Gauss1D = 0
        widget_control,(*pstate_mabc).win_Gauss1D,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pstate_mabc).mouse_Gauss1D eq 1 then begin
      xll = (*pstate_mabc).xbox_Gauss1D[0] < (*pstate_mabc).xbox_Gauss1D[1]
      yll = (*pstate_mabc).ybox_Gauss1D[0] < (*pstate_mabc).ybox_Gauss1D[1]
      w = abs((*pstate_mabc).xbox_Gauss1D[1] - (*pstate_mabc).xbox_Gauss1D[0])
      h = abs((*pstate_mabc).ybox_Gauss1D[1] - (*pstate_mabc).ybox_Gauss1D[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      ;
      ;Here we add some new code
      (*pstate_mabc).xrange_fitwindowGauss1D = [ll[0],ur[0]]
      (*pstate_mabc).yrange_fitwindowGauss1D = [ll[1],ur[1]]
      ;print, 'xrange:',(*pstate_mabc).xrange
      ;print, 'yrange:',(*pstate_mabc).yrange
      ;print,''
      ;print, 'xrange_fitwindow:',(*pstate_mabc).xrange_fitwindow
      ;print, 'yrange_fitwindow:',(*pstate_mabc).yrange_fitwindow
       mabc_Gauss1DParameters,event

    ;  wset,(*pstate_mabc).winpix_Gauss1D
    ;    mabcPlot,event
    ;  wset,(*pstate_mabc).winvis_Gauss1D
    ;  device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
      (*pstate_mabc).mouse_Gauss1D = 0B
      widget_control,(*pstate_mabc).win_Gauss1D,draw_motion_events = 0


     endif
     if (*pstate_mabc).mouse_Gauss1D eq 4 then begin
      wset,(*pstate_mabc).winpix_Gauss1D
        MABCGauss1D_Plot,event
      wset,(*pstate_mabc).winvis_Gauss1D
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
      (*pstate_mabc).mouse_Gauss1D = 0B
      widget_control,(*pstate_mabc).win_Gauss1D,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pstate_mabc).mouse_Gauss1D eq 1 then begin
       (*pstate_mabc).xbox_Gauss1D[1] = event.x
       (*pstate_mabc).ybox_Gauss1D[1] = event.y
       xc = [(*pstate_mabc).xbox_Gauss1D[0],event.x,event.x,$
             (*pstate_mabc).xbox_Gauss1D[0],$
             (*pstate_mabc).xbox_Gauss1D[0]]
       yc = [(*pstate_mabc).ybox_Gauss1D[0],(*pstate_mabc).ybox_Gauss1D[0],$
             event.y,event.y,$
             (*pstate_mabc).ybox_Gauss1D[0]]
       wset,(*pstate_mabc).winvis_Gauss1D
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_Gauss1D]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
return
endif
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABCCross_Draw,event
widget_control,event.top,get_uvalue = pstate_mabc


if (*pState_mabc).pix ne 2 then begin
        MABCCross_Plot,event
(*pState_mabc).pix = 2
endif


widget_control,(*pstate_mabc).Mouse_Action_cross,get_value = val
if val eq 0 then begin
case event.type of
0:  begin       ; button press
      (*pstate_mabc).mouse_cross = event.press
      if (*pstate_mabc).mouse_cross eq 4 then begin
        (*pstate_mabc).autoscale_cross = 1

        wset,(*pstate_mabc).winpix_cross
        MABCCross_Plot,event
        wset,(*pstate_mabc).winvis_cross
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
      endif
      if (*pstate_mabc).mouse_cross eq 1 then begin
        (*pstate_mabc).xbox_cross[0] = event.x
        (*pstate_mabc).ybox_cross[0] = event.y
        wset,(*pstate_mabc).winvis_cross
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
        empty
        (*pstate_mabc).autoscale_cross = 0
        widget_control,(*pstate_mabc).win_cross,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pstate_mabc).mouse_cross eq 1 then begin
      xll = (*pstate_mabc).xbox_cross[0] < (*pstate_mabc).xbox_cross[1]
      yll = (*pstate_mabc).ybox_cross[0] < (*pstate_mabc).ybox_cross[1]
      w = abs((*pstate_mabc).xbox_cross[1] - (*pstate_mabc).xbox_cross[0])
      h = abs((*pstate_mabc).ybox_cross[1] - (*pstate_mabc).ybox_cross[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      (*pstate_mabc).xrange_cross = [ll[0],ur[0]]
      (*pstate_mabc).yrange_cross= [ll[1],ur[1]]
      wset,(*pstate_mabc).winpix_cross
        MABCCross_Plot,event
      wset,(*pstate_mabc).winvis_cross
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
      (*pstate_mabc).mouse_cross = 0B
      widget_control,(*pstate_mabc).win_cross,draw_motion_events = 0
     endif
     if (*pstate_mabc).mouse_cross eq 4 then begin
      wset,(*pstate_mabc).winpix_cross
        MABCCross_Plot,event
      wset,(*pstate_mabc).winvis_cross
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
      (*pstate_mabc).mouse_cross = 0B
      widget_control,(*pstate_mabc).win_cross,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pstate_mabc).mouse_cross eq 1 then begin
       (*pstate_mabc).xbox_cross[1] = event.x
       (*pstate_mabc).ybox_cross[1] = event.y
       xc = [(*pstate_mabc).xbox_cross[0],event.x,event.x,$
             (*pstate_mabc).xbox_cross[0],$
             (*pstate_mabc).xbox_cross[0]]
       yc = [(*pstate_mabc).ybox_cross[0],(*pstate_mabc).ybox_cross[0],$
             event.y,event.y,$
             (*pstate_mabc).ybox_cross[0]]
       wset,(*pstate_mabc).winvis_cross
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
return
endif
if val eq 1 then begin
case event.type of
0:  begin       ; button press
      (*pstate_mabc).mouse_cross = event.press
      if (*pstate_mabc).mouse_cross eq 4 then begin
        (*pstate_mabc).autoscale_cross = 1

        wset,(*pstate_mabc).winpix_cross
        MABCCross_Plot,event
        wset,(*pstate_mabc).winvis_cross
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
      endif
      if (*pstate_mabc).mouse_cross eq 1 then begin
        (*pstate_mabc).xbox_cross[0] = event.x
        (*pstate_mabc).ybox_cross[0] = event.y
        wset,(*pstate_mabc).winvis_cross
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
        empty
        (*pstate_mabc).autoscale_cross = 0
        widget_control,(*pstate_mabc).win_cross,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pstate_mabc).mouse_cross eq 1 then begin
      xll = (*pstate_mabc).xbox_cross[0] < (*pstate_mabc).xbox_cross[1]
      yll = (*pstate_mabc).ybox_cross[0] < (*pstate_mabc).ybox_cross[1]
      w = abs((*pstate_mabc).xbox_cross[1] - (*pstate_mabc).xbox_cross[0])
      h = abs((*pstate_mabc).ybox_cross[1] - (*pstate_mabc).ybox_cross[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      ;
      ;Here we add some new code
      (*pstate_mabc).xrange_fitwindowCross = [ll[0],ur[0]]
      (*pstate_mabc).yrange_fitwindowCross = [ll[1],ur[1]]
      ;print, 'xrange:',(*pstate_mabc).xrange
      ;print, 'yrange:',(*pstate_mabc).yrange
      ;print,''
      ;print, 'xrange_fitwindow:',(*pstate_mabc).xrange_fitwindow
      ;print, 'yrange_fitwindow:',(*pstate_mabc).yrange_fitwindow
       mabc_CrossParameters,event

    ;  wset,(*pstate_mabc).winpix_cross
    ;    mabcPlot,event
    ;  wset,(*pstate_mabc).winvis_cross
    ;  device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
      (*pstate_mabc).mouse_cross = 0B
      widget_control,(*pstate_mabc).win_cross,draw_motion_events = 0


     endif
     if (*pstate_mabc).mouse_cross eq 4 then begin
      wset,(*pstate_mabc).winpix_cross
        MABCCross_Plot,event
      wset,(*pstate_mabc).winvis_cross
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
      (*pstate_mabc).mouse_cross = 0B
      widget_control,(*pstate_mabc).win_cross,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pstate_mabc).mouse_cross eq 1 then begin
       (*pstate_mabc).xbox_cross[1] = event.x
       (*pstate_mabc).ybox_cross[1] = event.y
       xc = [(*pstate_mabc).xbox_cross[0],event.x,event.x,$
             (*pstate_mabc).xbox_cross[0],$
             (*pstate_mabc).xbox_cross[0]]
       yc = [(*pstate_mabc).ybox_cross[0],(*pstate_mabc).ybox_cross[0],$
             event.y,event.y,$
             (*pstate_mabc).ybox_cross[0]]
       wset,(*pstate_mabc).winvis_cross
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_cross]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
return
endif
end


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mabcdraw_raw,event
widget_control,event.top,get_uvalue = pstate_mabc


if (*pState_mabc).pix ne 0 then begin
        mabcPlot_raw,event
(*pState_mabc).pix = 0
endif


widget_control,(*pstate_mabc).Mouse_Action,get_value = val
if val eq 0 then begin
case event.type of
0:  begin       ; button press
      (*pstate_mabc).mouse_raw = event.press
      if (*pstate_mabc).mouse_raw eq 4 then begin
        (*pstate_mabc).autoscale_raw = 1

        wset,(*pstate_mabc).winpix_raw
        mabcPlot_raw,event
        wset,(*pstate_mabc).winvis_raw
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
      endif
      if (*pstate_mabc).mouse_raw eq 1 then begin
        (*pstate_mabc).xbox_raw[0] = event.x
        (*pstate_mabc).ybox_raw[0] = event.y
        wset,(*pstate_mabc).winvis_raw
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
        empty
        (*pstate_mabc).autoscale_raw = 0
        widget_control,(*pstate_mabc).win_raw,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pstate_mabc).mouse_raw eq 1 then begin
      xll = (*pstate_mabc).xbox_raw[0] < (*pstate_mabc).xbox_raw[1]
      yll = (*pstate_mabc).ybox_raw[0] < (*pstate_mabc).ybox_raw[1]
      w = abs((*pstate_mabc).xbox_raw[1] - (*pstate_mabc).xbox_raw[0])
      h = abs((*pstate_mabc).ybox_raw[1] - (*pstate_mabc).ybox_raw[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      (*pstate_mabc).xrange_raw = [ll[0],ur[0]]
      (*pstate_mabc).yrange_raw= [ll[1],ur[1]]
      wset,(*pstate_mabc).winpix_raw
        mabcPlot_raw,event
      wset,(*pstate_mabc).winvis_raw
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
      (*pstate_mabc).mouse_raw = 0B
      widget_control,(*pstate_mabc).win_raw,draw_motion_events = 0
     endif
     if (*pstate_mabc).mouse_raw eq 4 then begin
      wset,(*pstate_mabc).winpix_raw
        mabcPlot_raw,event
      wset,(*pstate_mabc).winvis_raw
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
      (*pstate_mabc).mouse_raw = 0B
      widget_control,(*pstate_mabc).win_raw,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pstate_mabc).mouse_raw eq 1 then begin
       (*pstate_mabc).xbox_raw[1] = event.x
       (*pstate_mabc).ybox_raw[1] = event.y
       xc = [(*pstate_mabc).xbox_raw[0],event.x,event.x,$
             (*pstate_mabc).xbox_raw[0],$
             (*pstate_mabc).xbox_raw[0]]
       yc = [(*pstate_mabc).ybox_raw[0],(*pstate_mabc).ybox_raw[0],$
             event.y,event.y,$
             (*pstate_mabc).ybox_raw[0]]
       wset,(*pstate_mabc).winvis_raw
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
return
endif
if val eq 1 then begin
case event.type of
0:  begin       ; button press
      (*pstate_mabc).mouse_raw = event.press
      if (*pstate_mabc).mouse_raw eq 4 then begin
        (*pstate_mabc).autoscale_raw = 1

        wset,(*pstate_mabc).winpix_raw
        mabcPlot_raw,event
        wset,(*pstate_mabc).winvis_raw
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
      endif
      if (*pstate_mabc).mouse_raw eq 1 then begin
        (*pstate_mabc).xbox_raw[0] = event.x
        (*pstate_mabc).ybox_raw[0] = event.y
        wset,(*pstate_mabc).winvis_raw
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
        empty
        (*pstate_mabc).autoscale_raw = 0
        widget_control,(*pstate_mabc).win_raw,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pstate_mabc).mouse_raw eq 1 then begin
      xll = (*pstate_mabc).xbox_raw[0] < (*pstate_mabc).xbox_raw[1]
      yll = (*pstate_mabc).ybox_raw[0] < (*pstate_mabc).ybox_raw[1]
      w = abs((*pstate_mabc).xbox_raw[1] - (*pstate_mabc).xbox_raw[0])
      h = abs((*pstate_mabc).ybox_raw[1] - (*pstate_mabc).ybox_raw[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      ;
      ;Here we add some new code
      (*pstate_mabc).xrange_fitwindow = [ll[0],ur[0]]
      (*pstate_mabc).yrange_fitwindow = [ll[1],ur[1]]
      ;print, 'xrange:',(*pstate_mabc).xrange
      ;print, 'yrange:',(*pstate_mabc).yrange
      ;print,''
      ;print, 'xrange_fitwindow:',(*pstate_mabc).xrange_fitwindow
      ;print, 'yrange_fitwindow:',(*pstate_mabc).yrange_fitwindow
       mabc_GaussParameters,event

    ;  wset,(*pstate_mabc).winpix_raw
    ;    mabcPlot,event
    ;  wset,(*pstate_mabc).winvis_raw
    ;  device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
      (*pstate_mabc).mouse_raw = 0B
      widget_control,(*pstate_mabc).win_raw,draw_motion_events = 0


     endif
     if (*pstate_mabc).mouse_raw eq 4 then begin
      wset,(*pstate_mabc).winpix_raw
        mabcPlot_raw,event
      wset,(*pstate_mabc).winvis_raw
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
      (*pstate_mabc).mouse_raw = 0B
      widget_control,(*pstate_mabc).win_raw,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pstate_mabc).mouse_raw eq 1 then begin
       (*pstate_mabc).xbox_raw[1] = event.x
       (*pstate_mabc).ybox_raw[1] = event.y
       xc = [(*pstate_mabc).xbox_raw[0],event.x,event.x,$
             (*pstate_mabc).xbox_raw[0],$
             (*pstate_mabc).xbox_raw[0]]
       yc = [(*pstate_mabc).ybox_raw[0],(*pstate_mabc).ybox_raw[0],$
             event.y,event.y,$
             (*pstate_mabc).ybox_raw[0]]
       wset,(*pstate_mabc).winvis_raw
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mabc).winpix_raw]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
return
endif
end


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function vc_find,x
common vc_find_share
return, Em-0.25*mn*((l15/((l15/x)+(delt/2.0)))^2+(l14/((l14/x)-(delt/2.0)))^2)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;pro MABC_GaussFit,event;

;;old routine
;widget_control,event.top,get_uvalue = pState_mabc
;DataArray_x=*(*pState_mabc).DataArray_x
;DataArray_y=*(*pState_mabc).DataArray_y
;XCoords=*(*pState_mabc).XCoords
;YCoords=*(*pState_mabc).YCoords
;N_XCoords=n_elements(XCoords)
;N_YCoords=n_elements(YCoords)
;
;DataArray_Zint=fltarr(10,N_XCoords,N_YCoords)
;DataArray_ZPeak=fltarr(10,N_XCoords,N_YCoords)
;
;widget_control,(*pState_mabc).Em,get_value=PeakPosition
;PeakPosition=float(PeakPosition[0])

;A1=PeakPosition
;A3=0.0
;A4=0.0
;for triffid = 0,9 do begin
;    for i = 0,N_XCoords-1 do begin
;       for j = 0,N_YCoords-1 do begin
;       x=reform(DataArray_x[triffid,i,j,*])
;       y=reform(DataArray_y[triffid,i,j,*])
;if (triffid eq 0) and (i eq 0) and (j eq 0) then begin
;print,x[where(y eq max(y))]
;print, 'x = ',x
;print, 'y = ',y
;endif
;A0=max(y)
;A1=((max(x)-min(x))/2.0)+min(x)
;A1=x[where(y eq A0)]
;A2=((max(x)-min(x))/12.0)
;estimates=[A0,A1,A2,A3,A4]
;yfit=gaussfit(x,y,coeff,estimates=estimates,nterms=5)
;DataArray_Zint[triffid,i,j]=coeff[0]
;deviation=abs(PeakPosition-coeff[1])
;xwin=max(x)-min(x)
;intfactor=1-(deviation/xwin)
;print,'intfactor = ',intfactor
;DataArray_ZPeak[triffid,i,j]=intfactor
;       endfor
;    endfor
;endfor
;*(*pState_mabc).DataArray_Zint=DataArray_Zint
;*(*pState_mabc).DataArray_ZPeak=DataArray_ZPeak
;
;
;end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function MABC_CheckParameters, event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Scan_Type_Select,get_value = Scan_Type_Select
widget_control,(*pState_mabc).Scan_Table,get_value=Scan_Input
theta_index=widget_info((*pState_mabc).analyser_angle_droplist,/droplist_select)
; get analyser table data
Analyser_structure=(*pState_mabc).Analyser_structure
;Analyser_structure.Aare_30.AFA30[1,theta_index]
loadtest=min(Analyser_structure.Aare_30.ALA30[*,31])
if loadtest eq 0.0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'Please Load Analyser Tables First.')
return,0
endif
Xvariable=Scan_Input[0,0]
Valid_Variables=['AF','AL','AS','DL','DS','DR']
valid=where(strmatch(Valid_Variables,Xvariable) eq 1)
if valid[0] eq -1 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    Xvariable+' is not a valid variable.')
return,0
endif
Xmidpoint=float(Scan_Input[0,1])
Xrange=float(Scan_Input[0,2])
Xlow=Xmidpoint-(Xrange/2.0)
Xhigh=Xmidpoint+(Xrange/2.0)
case Xvariable of
'AF':     $
begin
lower_limit_array=Analyser_structure.Aare_30.AFA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.AFA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.AFA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.AFA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.AFA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.AFB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.AFB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.AFB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.AFB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.AFB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.AFA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.AFA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.AFA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.AFA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.AFA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.AFB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.AFB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.AFB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.AFB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.AFB150[2,theta_index]]
end
'AL':     $
begin
lower_limit_array=Analyser_structure.Aare_30.ALA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.ALA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.ALA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.ALA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.ALA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.ALB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.ALB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.ALB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.ALB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.ALB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.ALA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.ALA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.ALA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.ALA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.ALA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.ALB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.ALB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.ALB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.ALB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.ALB150[2,theta_index]]
end
'AS':     $
begin
lower_limit_array=Analyser_structure.Aare_30.ASA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.ASA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.ASA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.ASA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.ASA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.ASB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.ASB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.ASB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.ASB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.ASB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.ASA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.ASA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.ASA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.ASA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.ASA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.ASB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.ASB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.ASB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.ASB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.ASB150[2,theta_index]]
end
'DL':     $
begin
lower_limit_array=Analyser_structure.Aare_30.DLA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.DLA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.DLA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.DLA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.DLA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.DLB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.DLB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.DLB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.DLB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.DLB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.DLA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.DLA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.DLA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.DLA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.DLA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.DLB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.DLB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.DLB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.DLB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.DLB150[2,theta_index]]
end
'DS':     $
begin
lower_limit_array=Analyser_structure.Aare_30.DSA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.DSA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.DSA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.DSA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.DSA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.DSB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.DSB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.DSB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.DSB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.DSB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.DSA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.DSA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.DSA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.DSA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.DSA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.DSB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.DSB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.DSB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.DSB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.DSB150[2,theta_index]]
end
'DR':     $
begin
lower_limit_array=Analyser_structure.Aare_30.DRA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.DRA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.DRA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.DRA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.DRA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.DRB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.DRB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.DRB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.DRB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.DRB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.DRA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.DRA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.DRA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.DRA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.DRA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.DRB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.DRB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.DRB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.DRB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.DRB150[2,theta_index]]
end
else:   $
return,0
endcase
minlimit=min(lower_limit_array)
wheremin=where(lower_limit_array eq minlimit)
minindex=wheremin[0]
;
if (Xlow lt minlimit) then begin
motor=Xvariable
    if minindex eq 0 then motor+='A30'
    if minindex eq 1 then motor+='A60'
    if minindex eq 2 then motor+='A90'
    if minindex eq 3 then motor+='A120'
    if minindex eq 4 then motor+='A150'
    if minindex eq 5 then motor+='B30'
    if minindex eq 6 then motor+='B60'
    if minindex eq 7 then motor+='B90'
    if minindex eq 8 then motor+='B120'
    if minindex eq 9 then motor+='B150'
;
    void=dialog_message(dialog_parent=event.top,/error, $
    'The scan is specified to begin at '+strtrim(string(Xlow),2)+' but the lower limit of motor '+ $
    motor+' is '+strtrim(string(minlimit),2)+'.  Please redefine the scan parameters')
return,0
endif
;
maxlimit=max(upper_limit_array)
wheremax=where(upper_limit_array eq maxlimit)
maxindex=wheremax[0]
;
if (Xhigh gt maxlimit) then begin
motor=Xvariable
    if maxindex eq 0 then motor+='A30'
    if maxindex eq 1 then motor+='A60'
    if maxindex eq 2 then motor+='A90'
    if maxindex eq 3 then motor+='A120'
    if maxindex eq 4 then motor+='A150'
    if maxindex eq 5 then motor+='B30'
    if maxindex eq 6 then motor+='B60'
    if maxindex eq 7 then motor+='B90'
    if maxindex eq 8 then motor+='B120'
    if maxindex eq 9 then motor+='B150'
;
    void=dialog_message(dialog_parent=event.top,/error, $
    'The scan is specified to end at '+strtrim(string(Xhigh),2)+' but the upper limit of motor '+ $
    motor+' is '+strtrim(string(maxlimit),2)+'.  Please redefine the scan parameters')
return,0
endif
IF Scan_Type_Select eq 1 THEN BEGIN ;2D run
Yvariable=Scan_Input[1,0]
valid=where(strmatch(Valid_Variables,Yvariable) eq 1)
if valid[0] eq -1 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    Yvariable+' is not a valid variable.')
return,0
endif
Ymidpoint=float(Scan_Input[1,1])
Yrange=float(Scan_Input[1,2])
Ylow=Ymidpoint-(Yrange/2.0)
Yhigh=Ymidpoint+(Yrange/2.0)
case Yvariable of
'AF':     $
begin
lower_limit_array=Analyser_structure.Aare_30.AFA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.AFA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.AFA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.AFA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.AFA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.AFB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.AFB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.AFB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.AFB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.AFB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.AFA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.AFA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.AFA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.AFA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.AFA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.AFB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.AFB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.AFB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.AFB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.AFB150[2,theta_index]]
end
'AL':     $
begin
lower_limit_array=Analyser_structure.Aare_30.ALA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.ALA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.ALA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.ALA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.ALA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.ALB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.ALB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.ALB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.ALB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.ALB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.ALA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.ALA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.ALA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.ALA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.ALA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.ALB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.ALB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.ALB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.ALB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.ALB150[2,theta_index]]
end
'AS':     $
begin
lower_limit_array=Analyser_structure.Aare_30.ASA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.ASA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.ASA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.ASA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.ASA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.ASB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.ASB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.ASB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.ASB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.ASB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.ASA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.ASA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.ASA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.ASA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.ASA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.ASB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.ASB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.ASB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.ASB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.ASB150[2,theta_index]]
end
'DL':     $
begin
lower_limit_array=Analyser_structure.Aare_30.DLA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.DLA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.DLA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.DLA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.DLA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.DLB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.DLB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.DLB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.DLB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.DLB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.DLA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.DLA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.DLA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.DLA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.DLA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.DLB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.DLB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.DLB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.DLB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.DLB150[2,theta_index]]
end
'DS':     $
begin
lower_limit_array=Analyser_structure.Aare_30.DSA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.DSA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.DSA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.DSA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.DSA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.DSB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.DSB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.DSB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.DSB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.DSB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.DSA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.DSA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.DSA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.DSA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.DSA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.DSB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.DSB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.DSB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.DSB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.DSB150[2,theta_index]]
end
'DR':     $
begin
lower_limit_array=Analyser_structure.Aare_30.DRA30[0,theta_index]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_60.DRA60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_90.DRA90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_120.DRA120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Aare_150.DRA150[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_30.DRB30[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_60.DRB60[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_90.DRB90[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_120.DRB120[0,theta_index]]
lower_limit_array=[lower_limit_array,Analyser_structure.Berg_150.DRB150[0,theta_index]]
;
upper_limit_array=Analyser_structure.Aare_30.DRA30[2,theta_index]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_60.DRA60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_90.DRA90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_120.DRA120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Aare_150.DRA150[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_30.DRB30[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_60.DRB60[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_90.DRB90[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_120.DRB120[2,theta_index]]
upper_limit_array=[upper_limit_array,Analyser_structure.Berg_150.DRB150[2,theta_index]]
end
else:   $
return,0
endcase
minlimit=min(lower_limit_array)
wheremin=where(lower_limit_array eq minlimit)
minindex=wheremin[0]
;
if (Ylow lt minlimit) then begin
motor=Yvariable
    if minindex eq 0 then motor+='A30'
    if minindex eq 1 then motor+='A60'
    if minindex eq 2 then motor+='A90'
    if minindex eq 3 then motor+='A120'
    if minindex eq 4 then motor+='A150'
    if minindex eq 5 then motor+='B30'
    if minindex eq 6 then motor+='B60'
    if minindex eq 7 then motor+='B90'
    if minindex eq 8 then motor+='B120'
    if minindex eq 9 then motor+='B150'
;
    void=dialog_message(dialog_parent=event.top,/error, $
    'The scan is specified to begin at '+strtrim(string(Ylow),2)+' but the lower limit of motor '+ $
    motor+' is '+strtrim(string(minlimit),2)+'.  Please redefine the scan parameters')
return,0
endif
;
maxlimit=max(upper_limit_array)
wheremax=where(upper_limit_array eq maxlimit)
maxindex=wheremax[0]
;
if (Yhigh gt maxlimit) then begin
motor=Yvariable
    if maxindex eq 0 then motor+='A30'
    if maxindex eq 1 then motor+='A60'
    if maxindex eq 2 then motor+='A90'
    if maxindex eq 3 then motor+='A120'
    if maxindex eq 4 then motor+='A150'
    if maxindex eq 5 then motor+='B30'
    if maxindex eq 6 then motor+='B60'
    if maxindex eq 7 then motor+='B90'
    if maxindex eq 8 then motor+='B120'
    if maxindex eq 9 then motor+='B150'
;
    void=dialog_message(dialog_parent=event.top,/error, $
    'The scan is specified to end at '+strtrim(string(Yhigh),2)+' but the upper limit of motor '+ $
    motor+' is '+strtrim(string(maxlimit),2)+'.  Please redefine the scan parameters')
return,0
endif
ENDIF
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function generatecoords, event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Scan_Type_Select,get_value = Scan_Type_Select
widget_control,(*pState_mabc).Scan_Table,get_value=Scan_Input
Xvariable=Scan_Input[0,0]
Xmidpoint=float(Scan_Input[0,1])
Xrange=float(Scan_Input[0,2])
XPoints=fix(Scan_Input[0,3])
if Xpoints gt 1 then begin
step=Xrange/(Xpoints-1.0)
endif else begin
step=0.0
endelse
Xlow=Xmidpoint-(Xrange/2.0)
Xcoords=Xlow+step*findgen(XPoints)
IF Scan_Type_Select eq 0 THEN BEGIN ;1D
Ycoords=fltarr(XPoints)
ENDIF ELSE BEGIN
Yvariable=Scan_Input[1,0]
Ymidpoint=float(Scan_Input[1,1])
Yrange=float(Scan_Input[1,2])
YPoints=fix(Scan_Input[1,3])
if Ypoints gt 1 then begin
step=Yrange/(Ypoints-1.0)
endif else begin
step=0.0
endelse
Ylow=Ymidpoint-(Yrange/2.0)
Ycoords=Ylow+step*findgen(YPoints)
ENDELSE
Coords={Xcoords:Xcoords,Ycoords:Ycoords}
return,Coords
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function GenerateMotorCommands, event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Scan_Type_Select,get_value = Scan_Type_Select
widget_control,(*pState_mabc).Scan_Table,get_value=Scan_Input
XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(XCoords)
motor_commandsX=strarr(10,N_XCoords)
MTX=strtrim(Scan_Input[0,0],2) ;MotorType
motor_arrayX=[MTX+'A30',MTX+'A60',MTX+'A90',MTX+'A120',MTX+'A150', $
          MTX+'B30',MTX+'B60',MTX+'B90',MTX+'B120',MTX+'B150']
for i = 0, N_XCoords-1 do begin
motor_commandsX[*,i]='drive '+motor_arrayX+' '+strtrim(string(XCoords[i]),2)
endfor
IF Scan_Type_Select eq 0 THEN BEGIN ;1D
motor_commandsY=strarr(10,N_XCoords) ;we shall make no use of this
ENDIF ELSE BEGIN
YCoords=*(*pState_mabc).YCoords
N_YCoords=n_elements(YCoords)
motor_commandsY=strarr(10,N_YCoords)
MTY=strtrim(Scan_Input[1,0],2) ;MotorTypeY
motor_arrayY=[MTY+'A30',MTY+'A60',MTY+'A90',MTY+'A120',MTY+'A150', $
          MTY+'B30',MTY+'B60',MTY+'B90',MTY+'B120',MTY+'B150']
for i = 0, N_YCoords-1 do begin
    motor_commandsY[*,i]='drive '+motor_arrayY+' '+strtrim(string(YCoords[i]),2)
endfor
ENDELSE
motor_commands={motor_commandsX:motor_commandsX,motor_commandsY:motor_commandsY}
return,motor_commands
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calibration_Create_Events,event
widget_control,event.top,get_uvalue = pState1_mabc
main_event=(*pState1_mabc).main_event
widget_control,main_event.top,get_uvalue = pState_mabc
UnitUser_2=(*pState_mabc).UnitUser_2
uname=widget_info(event.id,/uname)
case uname of
'Interrupt_nicely':    $
begin
widget_control,(*pState1_mabc).Interrupt_nicely,sensitive = 0
(*pState_mabc).terminate=1
print,'(*pState_mabc).terminate = ',(*pState_mabc).terminate
end
'Interrupt_now':    $
begin
widget_control,(*pState1_mabc).Interrupt_now,sensitive = 0
EndRunCommand='INT1712 3'
tstart=systime(/seconds)
response=sicsinterrupt(main_event,UnitUser_2,EndRunCommand)
telapsed=systime(/seconds)-tstart
print,'Time to terminate run = ',telapsed
print,'response = ',response
print,''
(*pState_mabc).terminate=1
print,'(*pState_mabc).terminate = ',(*pState_mabc).terminate
;widget_control,(*pState1_mabc).Interrupt_now,sensitive = 1
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calibration_Destroy,tlb
widget_control,tlb,get_uvalue = pState1_mabc
wdelete,(*pState1_mabc).winpix_koennecke
ptr_free,pState1_mabc
widget_control,tlb,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calibration_Create,event,tlb
widget_control,event.top,get_uvalue = pState_mabc
image=(*pState_mabc).koennecke_pic
main_event=event
;
; Centre it.
geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50


tlb = widget_base(title='Acquiring data',/col,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3)
Baseupper=widget_base(tlb,/row)
Baselower=widget_base(tlb,/col,/align_center)

    s = size(image)
    sx = s[2] & sy = s[3]
aspect = 1.0*sy/sx              ; find the aspect ratio of the image...

picxsize = 75 & picysize = fix(aspect*picxsize)

picbase = widget_base(Baseupper,xsize = picxsize,ysize = picysize)

picwin = widget_draw(picbase,xsize = picxsize,ysize = picysize)
    dispimage = image

base2=widget_base(Baseupper,/col)
total_runs=cw_field(Base2,/col,title='Total Number of Runs',value='',xsize=10,/noedit)
current_run=cw_field(Base2,/col,title='Current Run',value='',xsize=10,/noedit)

base3=widget_base(Baseupper,/col)

current_abscissa=cw_field(Base3,/col,title='Current Value of Abscissa',value='',xsize=10,/noedit)
current_ordinate=cw_field(Base3,/col,title='Current Value of Ordinate',value='',xsize=10,/noedit)



base4=widget_base(Baseupper,/col)
StartTime=systime()
void=cw_field(Base4,/col,title='Calibration Run Commenced at:',value=StartTime,xsize=15,/noedit)
Completion_Time=cw_field(Base4,/col,title='Estimated Time of Completion:',value='',xsize=15,/noedit)

;base5=widget_base(Baselower,/col)

Interrupt_nicely = widget_button(Baselower,value = 'Interrupt after completion of current run', $
    uname='Interrupt_nicely')
Interrupt_now = widget_button(Baselower,value = 'Interrupt immediately', $
    uname='Interrupt_now')


widget_control,tlb,/realize

widget_control,picwin,get_value = picVis


window,/free,/pixmap,xsize = picxsize,ysize = picysize
winpix_koennecke = !d.window

wset,winpix_koennecke
tvimage,dispImage
wset,picVis

device,copy = [0,0,!d.x_size,!d.y_size,0,0,winpix_koennecke]

state1={winpix_koennecke:winpix_koennecke, $
       main_event:main_event, $
       total_runs:total_runs, $
       current_run:current_run, $
       current_abscissa:current_abscissa, $
       current_ordinate:current_ordinate, $
       Completion_Time:Completion_Time, $
       Interrupt_nicely:Interrupt_nicely, $
       Interrupt_now:Interrupt_now}

pState1_mabc = ptr_new(state1,/no_copy)
widget_control,tlb,set_uvalue = pState1_mabc
xmanager, 'Calibration_Create',tlb,event_handler = 'Calibration_Create_Events' ;register with the xmanager
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function MABC_InitialiseRun,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Scan_Type_Select,get_value = Scan_Type_Select
widget_control,(*pState_mabc).Scan_Table,get_value=Scan_Input
UnitUser_exe=(*pState_mabc).UnitUser_exe
;   CATCH, Error_status
;if Error_status ne 0 then begin
;catch, /cancel
;    void=dialog_message(dialog_parent=event.top,/error, $
;    !ERROR_STATE.MSG)
;return
;endif
result=MABC_CheckParameters(event)
if result eq 0 then return,0
      daveDeSensitizeButtons,event
Calibration_Create,event,tlb
widget_control,tlb,get_uvalue = pState1_mabc
(*pState_mabc).Calibration_Create_tlb=tlb
Coords=generatecoords(event)
(*pState_mabc).start_time=systime(1,/seconds)
IF Scan_Type_Select eq 0 THEN BEGIN ;1D run
(*pState_mabc).datatype=0
Xcoords=Coords.Xcoords
*(*pState_mabc).XCoords=XCoords
(*pState_mabc).Xvariable=Scan_Input[0,0]
N_XCoords=n_elements(Xcoords)
motor_commands=GenerateMotorCommands(event)
motor_commandsX=motor_commands.motor_commandsX
*(*pState_mabc).motor_commandsX=motor_commandsX
;
totalruns=N_XCoords
(*pState_mabc).current_j=0
ENDIF ELSE BEGIN
(*pState_mabc).datatype=1
Xcoords=Coords.Xcoords
Ycoords=Coords.Ycoords
*(*pState_mabc).XCoords=XCoords
*(*pState_mabc).YCoords=YCoords
N_XCoords=n_elements(Xcoords)
N_YCoords=n_elements(Ycoords)
(*pState_mabc).Xvariable=Scan_Input[0,0]
(*pState_mabc).Yvariable=Scan_Input[1,0]
motor_commands=GenerateMotorCommands(event)
motor_commandsX=motor_commands.motor_commandsX
motor_commandsY=motor_commands.motor_commandsY
*(*pState_mabc).motor_commandsX=motor_commandsX
*(*pState_mabc).motor_commandsY=motor_commandsY
;print,'Xcoords: ',Xcoords
;print,'Ycoords: ',Ycoords
totalruns=N_XCoords*N_YCoords
(*pState_mabc).current_j=0
(*pState_mabc).current_k=0
(*pState_mabc).current_l=0
ENDELSE
widget_control,(*pState1_mabc).total_runs,set_value = strtrim(string(totalruns),2)
(*pState_mabc).terminate=0
(*pState_mabc).totalruns=totalruns
widget_control,(*pstate_mabc).raw_SliderValue,set_value = 1

samplename='sample TriffidCal_'+systime()
response=sicsexecute(event,UnitUser_exe,samplename)
print,'response = ',response
print,''

return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function MABC_ProbeRunstatus,event
widget_control,event.top,get_uvalue = pState_mabc
UnitSpy=(*pState_mabc).UnitSpy
UnitUser_exe=(*pState_mabc).UnitUser_exe
command='status'
response_info=sicscommand(event,UnitSpy,command,datatype='string',/no_message)
print,'Status = ',response_info
print,''
if strpos(response_info,'Eager') ne -1 then begin
response=sicstranscomplete(event,UnitUser_exe); complete the transact command
return,1
endif else begin
return,0
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ExecuteRun,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Calibration_Create_tlb,get_uvalue = pState1_mabc
datatype=(*pState_mabc).datatype
UnitUser_exe=(*pState_mabc).UnitUser_exe
widget_control,(*pState_mabc).Monitor_counts,get_value=Monitor_counts
Monitor_counts=strtrim(Monitor_counts,2)
motor_commandsX=*(*pState_mabc).motor_commandsX
j=(*pState_mabc).current_j
XCoords=*(*pState_mabc).XCoords
;   CATCH, Error_status
;if Error_status ne 0 then begin
;catch, /cancel
;    void=dialog_message(dialog_parent=event.top,/error, $
;    !ERROR_STATE.MSG)
;return
;endif

IF datatype eq 0 THEN BEGIN ;1D run
widget_control,(*pState1_mabc).current_run,set_value = strtrim(string(j+1),2)
widget_control,(*pState1_mabc).current_abscissa,set_value = strtrim(string(XCoords[j]),2)
if j ge 1 then begin ; number of runs completed = j
current_time=systime(1,/seconds)
time_elapsed=current_time-(*pState_mabc).start_time
time_remaining=((*pState_mabc).totalruns-j)*(time_elapsed/j)
print,'j: ',j
print,'time_elapsed: ',time_elapsed
print,'time_remaining: ',time_remaining
print,'totalruns: ',(*pState_mabc).totalruns
;
Predicted_EndTime=current_time+time_remaining
Predicted_EndTime_String=systime(0,Predicted_EndTime)
widget_control,(*pState1_mabc).Completion_Time,set_value = Predicted_EndTime_String
endif
;drive the motors to their positions
    for i = 0,9 do begin
response=sicsexecute(event,UnitUser_exe,motor_commandsX[i,j])
print,'response = ',response
print,''
    endfor
;now start the run
response=sicsexecute(event,UnitUser_exe,'scancount monitor '+Monitor_counts,/nowait)
print,'response = ',response
print,''
ENDIF ELSE BEGIN
motor_commandsY=*(*pState_mabc).motor_commandsY
k=(*pState_mabc).current_k
l=(*pState_mabc).current_l
YCoords=*(*pState_mabc).YCoords
widget_control,(*pState1_mabc).current_run,set_value = strtrim(string(l+1),2)
widget_control,(*pState1_mabc).current_abscissa,set_value = strtrim(string(XCoords[j]),2)
widget_control,(*pState1_mabc).current_ordinate,set_value = strtrim(string(YCoords[k]),2)
if l ge 1 then begin ; number of runs completed = l
current_time=systime(1,/seconds)
time_elapsed=current_time-(*pState_mabc).start_time
time_remaining=((*pState_mabc).totalruns-l)*(time_elapsed/l)
;print,'time_remaining = ',time_remaining
Predicted_EndTime=current_time+time_remaining
Predicted_EndTime_String=systime(0,Predicted_EndTime)
widget_control,(*pState1_mabc).Completion_Time,set_value = Predicted_EndTime_String
endif
print,'spectrum mumber = ',l+1
;drive the motors to their positions
    for i = 0,9 do begin
response=sicsexecute(event,UnitUser_exe,motor_commandsX[i,j])
print,'response = ',response
print,''
response=sicsexecute(event,UnitUser_exe,motor_commandsY[i,k])
print,'response = ',response
print,''
    endfor
;now start the run
response=sicsexecute(event,UnitUser_exe,'scancount monitor '+Monitor_counts,/nowait)
print,'response = ',response
print,''
ENDELSE
WIDGET_CONTROL, event.TOP, TIMER=10
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro StoreData,event
widget_control,event.top,get_uvalue = pState_mabc
datatype=(*pState_mabc).datatype
UnitSpy=(*pState_mabc).UnitSpy
XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(Xcoords)

IF datatype eq 0 THEN BEGIN ;1D run
j=(*pState_mabc).current_j
SICSErrorlog=''
    MarsUpdate_structure=SicsMarsUpdate(event,UnitSpy,'marsupdateinfo',SICSErrorLog)
    ;    print,'n_tags(MarsUpdate_structure): ',n_tags(MarsUpdate_structure)
        print,'SICSErrorLog: ',SICSErrorLog

       if n_tags(MarsUpdate_structure) eq 2 then begin ;error
       wait,2 ; wait for sics to get its act together
       MarsUpdate_structure=SicsMarsUpdate(event,UnitSpy,'marsupdateinfo',SICSErrorLog) ;simply try again
         if n_tags(MarsUpdate_structure) eq 2 then begin ;error
         wait,2 ; wait for sics to get its act together
         MarsUpdate_structure=SicsMarsUpdate(event,UnitSpy,'marsupdateinfo',SICSErrorLog) ;last try if this fails the program will crash
         endif
       endif
           if j eq 0 then begin ; define array dimensions
           DataPoints=MarsUpdate_structure.notimebin
           (*pState_mabc).DataPoints=DataPoints
           timebin=MarsUpdate_structure.timebin
           timebin/=10.0


      ;
    Choppers_Info=MarsUpdate_structure.Choppers_Info
    for i = 0,4 do Choppers_Info[1,i]/=60.0 ; convert to Hz
    timeoffsets=(*pState_mabc).timeoffsets
offset=0.0
masterfundamental=fix(round(Choppers_Info[1,1]/50.0))
if masterfundamental eq 1 then offset=timeoffsets.master1_timeoffset
if masterfundamental eq 2 then offset=timeoffsets.master2_timeoffset
if masterfundamental eq 3 then offset=timeoffsets.master3_timeoffset
if masterfundamental eq 4 then offset=timeoffsets.master4_timeoffset
if masterfundamental eq 5 then offset=timeoffsets.master5_timeoffset
if masterfundamental eq 6 then offset=timeoffsets.master6_timeoffset
if masterfundamental eq 7 then offset=timeoffsets.master7_timeoffset
;print,'masterfundamental: ' ,masterfundamental
;print,'offset: ' ,offset
timebin+=offset
;



           data=MarsUpdate_structure.data
           target_reflection=MarsUpdate_structure.target_reflection
           dp=DataPoints*12
           DataArray_x=fltarr(10,1,DataPoints)
           DataArray_y=fltarr(10,1,DataPoints)
           for triffid = 0,9 do begin
           DataArray_x[triffid,0,*]=timebin
           DataArray_y[triffid,0,*]=data[dp:dp+DataPoints-1]
           dp+=DataPoints
           endfor
         *(*pState_mabc).DataArray_x=DataArray_x
         *(*pState_mabc).DataArray_y=DataArray_y
           endif else begin; the j = 0 endif
    data=MarsUpdate_structure.data
    DataPoints=MarsUpdate_structure.notimebin
    timebin=MarsUpdate_structure.timebin
    timebin/=10.0
;
    Choppers_Info=MarsUpdate_structure.Choppers_Info
    for i = 0,4 do Choppers_Info[1,i]/=60.0 ; convert to Hz
    timeoffsets=(*pState_mabc).timeoffsets
offset=0.0
masterfundamental=fix(round(Choppers_Info[1,1]/50.0))
if masterfundamental eq 1 then offset=timeoffsets.master1_timeoffset
if masterfundamental eq 2 then offset=timeoffsets.master2_timeoffset
if masterfundamental eq 3 then offset=timeoffsets.master3_timeoffset
if masterfundamental eq 4 then offset=timeoffsets.master4_timeoffset
if masterfundamental eq 5 then offset=timeoffsets.master5_timeoffset
if masterfundamental eq 6 then offset=timeoffsets.master6_timeoffset
if masterfundamental eq 7 then offset=timeoffsets.master7_timeoffset
;print,'masterfundamental: ' ,masterfundamental
;print,'offset: ' ,offset
timebin+=offset
;

    tempx_array=fltarr(10,j+1,DataPoints)
    tempy_array=fltarr(10,j+1,DataPoints)
    tempx_array[*,0:j-1,*]=*(*pState_mabc).DataArray_x
    tempy_array[*,0:j-1,*]=*(*pState_mabc).DataArray_y
    dp=DataPoints*12
    for triffid = 0,9 do begin
    tempx_array[triffid,j,*]=timebin
    tempy_array[triffid,j,*]=data[dp:dp+DataPoints-1]
    dp+=DataPoints
    endfor
    DataArray_x=tempx_array
    DataArray_y=tempy_array
    *(*pState_mabc).DataArray_x=DataArray_x
    *(*pState_mabc).DataArray_y=DataArray_y
    endelse
;print,'spectrum mumber = ',j+1
j+=1
if j eq N_XCoords then (*pState_mabc).terminate=1
(*pState_mabc).current_j=j



ENDIF ELSE BEGIN
j=(*pState_mabc).current_j
k=(*pState_mabc).current_k
l=(*pState_mabc).current_l
YCoords=*(*pState_mabc).YCoords
N_YCoords=n_elements(Ycoords)
SICSErrorlog=''
    MarsUpdate_structure=SicsMarsUpdate(event,UnitSpy,'marsupdateinfo',SICSErrorLog)
    ;    print,'n_tags(MarsUpdate_structure): ',n_tags(MarsUpdate_structure)
        print,'SICSErrorLog: ',SICSErrorLog

       if n_tags(MarsUpdate_structure) eq 2 then begin ;error
       wait,2 ; wait for sics to get its act together
       MarsUpdate_structure=SicsMarsUpdate(event,UnitSpy,'marsupdateinfo',SICSErrorLog) ;simply try again
         if n_tags(MarsUpdate_structure) eq 2 then begin ;error
         wait,2 ; wait for sics to get its act together
         MarsUpdate_structure=SicsMarsUpdate(event,UnitSpy,'marsupdateinfo',SICSErrorLog) ;last try if this fails the program will crash
         endif
       endif
           if l eq 0 then begin ; define array dimensions
           DataPoints=MarsUpdate_structure.notimebin
           (*pState_mabc).DataPoints=DataPoints
           timebin=MarsUpdate_structure.timebin
           timebin/=10.0

;
    Choppers_Info=MarsUpdate_structure.Choppers_Info
    for i = 0,4 do Choppers_Info[1,i]/=60.0 ; convert to Hz
    timeoffsets=(*pState_mabc).timeoffsets
offset=0.0
masterfundamental=fix(round(Choppers_Info[1,1]/50.0))
if masterfundamental eq 1 then offset=timeoffsets.master1_timeoffset
if masterfundamental eq 2 then offset=timeoffsets.master2_timeoffset
if masterfundamental eq 3 then offset=timeoffsets.master3_timeoffset
if masterfundamental eq 4 then offset=timeoffsets.master4_timeoffset
if masterfundamental eq 5 then offset=timeoffsets.master5_timeoffset
if masterfundamental eq 6 then offset=timeoffsets.master6_timeoffset
if masterfundamental eq 7 then offset=timeoffsets.master7_timeoffset
;print,'masterfundamental: ' ,masterfundamental
;print,'offset: ' ,offset
timebin+=offset
;


           data=MarsUpdate_structure.data
           target_reflection=MarsUpdate_structure.target_reflection
           dp=DataPoints*12
           DataArray_x=fltarr(10,1,DataPoints)
           DataArray_y=fltarr(10,1,DataPoints)
           for triffid = 0,9 do begin
           DataArray_x[triffid,0,*]=timebin
           DataArray_y[triffid,0,*]=data[dp:dp+DataPoints-1]
           dp+=DataPoints
           endfor
         tempx_array=DataArray_x
         tempy_array=DataArray_y
           endif else begin; the l = 0 endif
    data=MarsUpdate_structure.data
    DataPoints=MarsUpdate_structure.notimebin
    timebin=MarsUpdate_structure.timebin
    timebin/=10.0



;
    Choppers_Info=MarsUpdate_structure.Choppers_Info
    for i = 0,4 do Choppers_Info[1,i]/=60.0 ; convert to Hz
    timeoffsets=(*pState_mabc).timeoffsets
offset=0.0
masterfundamental=fix(round(Choppers_Info[1,1]/50.0))
if masterfundamental eq 1 then offset=timeoffsets.master1_timeoffset
if masterfundamental eq 2 then offset=timeoffsets.master2_timeoffset
if masterfundamental eq 3 then offset=timeoffsets.master3_timeoffset
if masterfundamental eq 4 then offset=timeoffsets.master4_timeoffset
if masterfundamental eq 5 then offset=timeoffsets.master5_timeoffset
if masterfundamental eq 6 then offset=timeoffsets.master6_timeoffset
if masterfundamental eq 7 then offset=timeoffsets.master7_timeoffset
;print,'masterfundamental: ' ,masterfundamental
;print,'offset: ' ,offset
timebin+=offset

    tempx_array=fltarr(10,l+1,DataPoints)
    tempy_array=fltarr(10,l+1,DataPoints)
    tempx_array[*,0:l-1,*]=*(*pState_mabc).DataArray_x
    tempy_array[*,0:l-1,*]=*(*pState_mabc).DataArray_y
    dp=DataPoints*12
    for triffid = 0,9 do begin
    tempx_array[triffid,l,*]=timebin
    tempy_array[triffid,l,*]=data[dp:dp+DataPoints-1]
    dp+=DataPoints
    endfor
    DataArray_x=tempx_array
    DataArray_y=tempy_array
    endelse
l+=1
k+=1
if k eq N_YCoords then begin
k=0
j+=1
if j eq N_XCoords then (*pState_mabc).terminate=1
endif


    *(*pState_mabc).DataArray_x=DataArray_x
    *(*pState_mabc).DataArray_y=DataArray_y
;
(*pState_mabc).current_j=j
(*pState_mabc).current_k=k
(*pState_mabc).current_l=l
ENDELSE

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABC_TimeBinCull,event
widget_control,event.top,get_uvalue = pState_mabc
datatype=(*pState_mabc).datatype
XCoords=*(*pState_mabc).XCoords

IF datatype eq 0 THEN BEGIN ;1D run
j=(*pState_mabc).current_j
(*pState_mabc).totalruns=j
TimeBinIndices=(*pState_mabc).TimeBinIndices
;print,'TimeBinIndices = ',TimeBinIndices
widget_control,(*pState_mabc).mica,get_value =mica
mica=fix(mica[0])
case mica of
0:  $   ;Target_Reflection='002'
begin
StartBin=TimeBinIndices[6]
EndBin=TimeBinIndices[7]
end
1:  $   ;Target_Reflection='004'
begin
StartBin=TimeBinIndices[8]
EndBin=TimeBinIndices[9]
end
2:  $   ;Target_Reflection='006'
begin
StartBin=TimeBinIndices[10]
EndBin=TimeBinIndices[11]
end
3:  $   ;Target_Reflection='008'
begin
StartBin=TimeBinIndices[12]
EndBin=TimeBinIndices[13]
end
else:
endcase
;help,DataArray_x
print,'StartBin: ',StartBin
print,'EndBin: ',EndBin
woof=*(*pState_mabc).DataArray_x
help,woof
DataArray_x=(*(*pState_mabc).DataArray_x)[*,*,StartBin:EndBin]
DataArray_y=(*(*pState_mabc).DataArray_y)[*,*,StartBin:EndBin]
*(*pState_mabc).DataArray_x=DataArray_x
*(*pState_mabc).DataArray_y=DataArray_y
*(*pState_mabc).XCoords=XCoords[0:j-1]

ENDIF ELSE BEGIN  ;2D a little complicated gael !

tempx_array=*(*pState_mabc).DataArray_x
tempy_array=*(*pState_mabc).DataArray_y
DataPoints=(*pState_mabc).DataPoints
l=(*pState_mabc).current_l
YCoords=*(*pState_mabc).YCoords
N_YCoords=n_elements(Ycoords)

;Now sort out the data.  If the scan was not interrupted then
;the data should be sorted into a 2d array, but this is not neccessarily so.
;
N_XScans=fix(l/N_YCoords)
;print,'N_XScans: ',N_XScans
case N_XScans of
0:  $   terminated before the second x value could be incremented
begin
DataArray_x=fltarr(10,1,l,datapoints)
DataArray_y=fltarr(10,1,l,datapoints)
DataArray_x[*,0,*,*]=tempx_array[*,*,*]
DataArray_y[*,0,*,*]=tempy_array[*,*,*]
*(*pState_mabc).XCoords=XCoords[0]
*(*pState_mabc).YCoords=YCoords[0:l-1]
(*pState_mabc).totalruns=n_elements(*(*pState_mabc).YCoords)
end
;
1:  $ ; we have to omit the remainder in order to maintain a regularly-spaced grid
begin
DataArray_x=fltarr(10,1,N_YCoords,datapoints)
DataArray_y=fltarr(10,1,N_YCoords,datapoints)
DataArray_x[*,0,*,*]=tempx_array[*,0:N_YCoords-1,*]
DataArray_y[*,0,*,*]=tempy_array[*,0:N_YCoords-1,*]
*(*pState_mabc).XCoords=XCoords[0]
*(*pState_mabc).YCoords=YCoords
(*pState_mabc).totalruns=n_elements(*(*pState_mabc).YCoords)
end
else:   $
begin
;print,'N_XScans :',N_XScans
;print,'N_YCoords :',N_YCoords
DataArray_x=fltarr(10,N_XScans,N_YCoords,datapoints)
DataArray_y=fltarr(10,N_XScans,N_YCoords,datapoints)
for i = 0, N_XScans-1 do begin
DataArray_x[*,i,0:N_YCoords-1,*]=tempx_array[*,i*N_YCoords:i*N_YCoords+N_YCoords-1,*]
DataArray_y[*,i,0:N_YCoords-1,*]=tempy_array[*,i*N_YCoords:i*N_YCoords+N_YCoords-1,*]
endfor
*(*pState_mabc).XCoords=XCoords[0:N_XScans-1]
*(*pState_mabc).YCoords=YCoords
(*pState_mabc).totalruns=n_elements(*(*pState_mabc).YCoords)*n_elements(*(*pState_mabc).XCoords)
end
endcase


TimeBinIndices=(*pState_mabc).TimeBinIndices
widget_control,(*pState_mabc).mica,get_value =mica
mica=fix(mica[0])
case mica of
0:  $   ;Target_Reflection='002'
begin
StartBin=TimeBinIndices[6]
EndBin=TimeBinIndices[7]
end
1:  $   ;Target_Reflection='004'
begin
StartBin=TimeBinIndices[8]
EndBin=TimeBinIndices[9]
end
2:  $   ;Target_Reflection='006'
begin
StartBin=TimeBinIndices[10]
EndBin=TimeBinIndices[11]
end
3:  $   ;Target_Reflection='008'
begin
StartBin=TimeBinIndices[12]
EndBin=TimeBinIndices[13]
end
else:
endcase
;woof=*(*pState_mabc).DataArray_x
;help,woof
;print,'StartBin: ',StartBin
;print,'EndBin: ',EndBin

DataArray_x=DataArray_x[*,*,*,StartBin:EndBin]
DataArray_y=DataArray_y[*,*,*,StartBin:EndBin]
*(*pState_mabc).DataArray_x=DataArray_x
*(*pState_mabc).DataArray_y=DataArray_y



;
;help,DataArray_x
;help,DataArray_y
;woofx=*(*pState_mabc).XCoords
;help,woofx
;woofy=*(*pState_mabc).YCoords
;help,woofy


ENDELSE
tlb=(*pState_mabc).Calibration_Create_tlb
Calibration_Destroy,tlb
daveSensitizeButtons,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABC_Demo_Data,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Scan_Type_Select,get_value = Scan_Type_Select
widget_control,(*pState_mabc).Scan_Table,get_value=Scan_Input

workDir=(*pState_mabc).workDir
delim=path_sep()
;restore,filename=workDir+'FakeData'
restore,!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'FakeData'
FakeDataArray_X=FakeData_structure.FakeDataArray_X
FakeDataArray_Y=FakeData_structure.FakeDataArray_Y

if Scan_Type_Select eq 0 then begin ;1D run

N_XCoords=n_elements(FakeDataArray_X[*,0,0])
DataPoints=n_elements(FakeDataArray_X[0,0,*])

DataArray_x=fltarr(10,N_XCoords,DataPoints)
DataArray_y=fltarr(10,N_XCoords,DataPoints)

for triffid=0,9 do begin
    for i=0,N_XCoords-1 do begin
DataArray_x[triffid,i,*]=reform(FakeDataArray_X[i,0,*])
DataArray_y[triffid,i,*]=reform(FakeDataArray_Y[i,0,*])
    endfor
endfor

*(*pState_mabc).DataArray_x=DataArray_x
*(*pState_mabc).DataArray_y=DataArray_y
XCoords=findgen(N_XCoords)+1
*(*pState_mabc).XCoords=XCoords

DataType=0
(*pState_mabc).Xvariable=Scan_Input[0,0]
(*pState_mabc).totalruns=N_XCoords
endif else begin
N_XCoords=n_elements(FakeDataArray_X[*,0,0])
N_YCoords=n_elements(FakeDataArray_X[0,*,0])
DataPoints=n_elements(FakeDataArray_X[0,0,*])
;
DataArray_x=fltarr(10,N_XCoords,N_YCoords,DataPoints)
DataArray_y=fltarr(10,N_XCoords,N_YCoords,DataPoints)
;
for triffid=0,9 do begin
    for i=0,N_XCoords-1 do begin
       for j=0,N_YCoords-1 do begin
DataArray_x[triffid,i,j,*]=FakeDataArray_X[i,j,*]
DataArray_y[triffid,i,j,*]=FakeDataArray_Y[i,j,*]
       endfor
    endfor
endfor
;
;
*(*pState_mabc).DataArray_x=DataArray_x
*(*pState_mabc).DataArray_y=DataArray_y
XCoords=findgen(N_XCoords)+1
YCoords=findgen(N_YCoords)+1
*(*pState_mabc).XCoords=XCoords
*(*pState_mabc).YCoords=YCoords

DataType=1
(*pState_mabc).Xvariable=Scan_Input[0,0]
(*pState_mabc).Yvariable=Scan_Input[1,0]
(*pState_mabc).totalruns=N_XCoords*N_YCoords
endelse
(*pState_mabc).DataType=DataType
(*pState_mabc).DataPoints=DataPoints
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABC_Define_Arrays,event
widget_control,event.top,get_uvalue = pState_mabc
workDir=(*pState_mabc).workDir
DataType=(*pState_mabc).DataType
DataPoints=(*pState_mabc).DataPoints
;
;   CATCH, Error_status
;if Error_status ne 0 then begin
;catch, /cancel
;    void=dialog_message(dialog_parent=event.top,/error, $
;    !ERROR_STATE.MSG)
;return
;endif

;everything from here on is common to real and demo modes
XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(XCoords)
totalruns=(*pState_mabc).totalruns

print,'totalruns: ',totalruns
print,'DataPoints: ',DataPoints
if DataType eq 0 then begin
;totalruns=N_XCoords
widget_control,(*pState_mabc).base_gauss2DContour,sensitive = 0
widget_control,(*pState_mabc).base_gauss2DCross,sensitive = 0
widget_control,(*pState_mabc).base_gauss1D,sensitive = 1
widget_control,(*pState_mabc).base_gauss2D,SET_TAB_CURRENT = 0
;
*(*pState_mabc).Gaussfits_x=fltarr(10,totalruns,DataPoints)
*(*pState_mabc).Gaussfits_y=fltarr(10,totalruns,DataPoints)
*(*pState_mabc).GaussParameters=fltarr(10,totalruns,6)
DataArray_Zint=fltarr(10,totalruns)
DataArray_ZPeak=fltarr(10,totalruns)
*(*pState_mabc).DataArray_Zint=DataArray_Zint
*(*pState_mabc).DataArray_ZPeak=DataArray_ZPeak
*(*pState_mabc).GaussGauss1DX=fltarr(10,2,N_XCoords)
*(*pState_mabc).GaussGauss1DY=fltarr(10,2,N_XCoords)
*(*pState_mabc).GaussGauss1DParameters=fltarr(10,2,6)
endif else begin
YCoords=*(*pState_mabc).YCoords
N_YCoords=n_elements(YCoords)
;totalruns=N_XCoords*N_YCoords ;who cares if the run was terminated early
widget_control,(*pState_mabc).base_gauss1D,sensitive = 0
widget_control,(*pState_mabc).base_gauss2DContour,sensitive = 1
widget_control,(*pState_mabc).base_gauss2DCross,sensitive = 1
widget_control,(*pState_mabc).base_gauss2D,SET_TAB_CURRENT = 1
;
*(*pState_mabc).Gaussfits_x=fltarr(10,totalruns,DataPoints)
*(*pState_mabc).Gaussfits_y=fltarr(10,totalruns,DataPoints)
*(*pState_mabc).GaussParameters=fltarr(10,totalruns,6)
DataArray_Zint=fltarr(10,totalruns)
DataArray_ZPeak=fltarr(10,totalruns)
*(*pState_mabc).DataArray_Zint=DataArray_Zint
*(*pState_mabc).DataArray_ZPeak=DataArray_ZPeak
*(*pState_mabc).GaussCrossX=fltarr(10,2,2,N_XCoords,N_YCoords)
*(*pState_mabc).GaussCrossY=fltarr(10,2,2,N_XCoords,N_YCoords)
*(*pState_mabc).GaussCrossParameters=fltarr(10,2,(N_XCoords+N_YCoords),6)
widget_control,(*pstate_mabc).CrossValue_Field,set_value = XCoords[0]
endelse

mabcPlot_raw,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro LoadAnalyserTable,event
widget_control,event.top,get_uvalue = pState_mabc
workDir=(*pState_mabc).workDir
Analyser_structure=(*pState_mabc).Analyser_structure
widget_control,(*pstate_mabc).Load_Analyser_Button,sensitive = 0
;
motor_Array=fltarr(3,32)
;
filename=workdir+'triffid01.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL01','AS01','DL01','DS01','DR01','AF01']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Aare_150.ALA150=motor_Array
if wherematch eq 1 then Analyser_structure.Aare_150.ASA150=motor_Array
if wherematch eq 2 then Analyser_structure.Aare_150.DLA150=motor_Array
if wherematch eq 3 then Analyser_structure.Aare_150.DSA150=motor_Array
if wherematch eq 4 then Analyser_structure.Aare_150.DRA150=motor_Array
if wherematch eq 5 then Analyser_structure.Aare_150.AFA150=motor_Array
endif
endwhile
free_lun,lun,/force
;
filename=workdir+'triffid02.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL02','AS02','DL02','DS02','DR02','AF02']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Aare_120.ALA120=motor_Array
if wherematch eq 1 then Analyser_structure.Aare_120.ASA120=motor_Array
if wherematch eq 2 then Analyser_structure.Aare_120.DLA120=motor_Array
if wherematch eq 3 then Analyser_structure.Aare_120.DSA120=motor_Array
if wherematch eq 4 then Analyser_structure.Aare_120.DRA120=motor_Array
if wherematch eq 5 then Analyser_structure.Aare_120.AFA120=motor_Array
endif
endwhile
free_lun,lun,/force
;
filename=workdir+'triffid03.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL03','AS03','DL03','DS03','DR03','AF03']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Aare_90.ALA90=motor_Array
if wherematch eq 1 then Analyser_structure.Aare_90.ASA90=motor_Array
if wherematch eq 2 then Analyser_structure.Aare_90.DLA90=motor_Array
if wherematch eq 3 then Analyser_structure.Aare_90.DSA90=motor_Array
if wherematch eq 4 then Analyser_structure.Aare_90.DRA90=motor_Array
if wherematch eq 5 then Analyser_structure.Aare_90.AFA90=motor_Array
endif
endwhile
free_lun,lun,/force
;
filename=workdir+'triffid04.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL04','AS04','DL04','DS04','DR04','AF04']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Aare_60.ALA60=motor_Array
if wherematch eq 1 then Analyser_structure.Aare_60.ASA60=motor_Array
if wherematch eq 2 then Analyser_structure.Aare_60.DLA60=motor_Array
if wherematch eq 3 then Analyser_structure.Aare_60.DSA60=motor_Array
if wherematch eq 4 then Analyser_structure.Aare_60.DRA60=motor_Array
if wherematch eq 5 then Analyser_structure.Aare_60.AFA60=motor_Array
endif
endwhile
free_lun,lun,/force
;
filename=workdir+'triffid05.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL05','AS05','DL05','DS05','DR05','AF05']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Aare_30.ALA30=motor_Array
if wherematch eq 1 then Analyser_structure.Aare_30.ASA30=motor_Array
if wherematch eq 2 then Analyser_structure.Aare_30.DLA30=motor_Array
if wherematch eq 3 then Analyser_structure.Aare_30.DSA30=motor_Array
if wherematch eq 4 then Analyser_structure.Aare_30.DRA30=motor_Array
if wherematch eq 5 then Analyser_structure.Aare_30.AFA30=motor_Array
endif
endwhile
free_lun,lun,/force
;
;
;
;
;
filename=workdir+'triffid06.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL06','AS06','DL06','DS06','DR06','AF06']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Berg_30.ALB30=motor_Array
if wherematch eq 1 then Analyser_structure.Berg_30.ASB30=motor_Array
if wherematch eq 2 then Analyser_structure.Berg_30.DLB30=motor_Array
if wherematch eq 3 then Analyser_structure.Berg_30.DSB30=motor_Array
if wherematch eq 4 then Analyser_structure.Berg_30.DRB30=motor_Array
if wherematch eq 5 then Analyser_structure.Berg_30.AFB30=motor_Array
endif
endwhile
free_lun,lun,/force
;
filename=workdir+'triffid07.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL07','AS07','DL07','DS07','DR07','AF07']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Berg_60.ALB60=motor_Array
if wherematch eq 1 then Analyser_structure.Berg_60.ASB60=motor_Array
if wherematch eq 2 then Analyser_structure.Berg_60.DLB60=motor_Array
if wherematch eq 3 then Analyser_structure.Berg_60.DSB60=motor_Array
if wherematch eq 4 then Analyser_structure.Berg_60.DRB60=motor_Array
if wherematch eq 5 then Analyser_structure.Berg_60.AFB60=motor_Array
endif
endwhile
free_lun,lun,/force
;
filename=workdir+'triffid08.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL08','AS08','DL08','DS08','DR08','AF08']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Berg_90.ALB90=motor_Array
if wherematch eq 1 then Analyser_structure.Berg_90.ASB90=motor_Array
if wherematch eq 2 then Analyser_structure.Berg_90.DLB90=motor_Array
if wherematch eq 3 then Analyser_structure.Berg_90.DSB90=motor_Array
if wherematch eq 4 then Analyser_structure.Berg_90.DRB90=motor_Array
if wherematch eq 5 then Analyser_structure.Berg_90.AFB90=motor_Array
endif
endwhile
free_lun,lun,/force
;
filename=workdir+'triffid09.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL09','AS09','DL09','DS09','DR09','AF09']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Berg_120.ALB120=motor_Array
if wherematch eq 1 then Analyser_structure.Berg_120.ASB120=motor_Array
if wherematch eq 2 then Analyser_structure.Berg_120.DLB120=motor_Array
if wherematch eq 3 then Analyser_structure.Berg_120.DSB120=motor_Array
if wherematch eq 4 then Analyser_structure.Berg_120.DRB120=motor_Array
if wherematch eq 5 then Analyser_structure.Berg_120.AFB120=motor_Array
endif
endwhile
free_lun,lun,/force
;
filename=workdir+'triffid10.dat'
line=''
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
if strpos(line,'#') ne -1 then begin
motor_name=strtrim((strsplit(line,'#',/extract))[0],2)
for i = 0,31 do begin
readf,lun,line
motor_Array[*,i]=strtrim((strsplit(line,/extract)),2)
endfor
fields=['AL10','AS10','DL10','DS10','DR10','AF10']
wherematch=where(fields eq motor_name)
if wherematch eq 0 then Analyser_structure.Berg_150.ALB150=motor_Array
if wherematch eq 1 then Analyser_structure.Berg_150.ASB150=motor_Array
if wherematch eq 2 then Analyser_structure.Berg_150.DLB150=motor_Array
if wherematch eq 3 then Analyser_structure.Berg_150.DSB150=motor_Array
if wherematch eq 4 then Analyser_structure.Berg_150.DRB150=motor_Array
if wherematch eq 5 then Analyser_structure.Berg_150.AFB150=motor_Array
endif
endwhile
free_lun,lun,/force
;
(*pState_mabc).Analyser_structure=Analyser_structure
;
;
;
;populate tables
;
Populate_Triffid_Tables,event


;


;for i = 0, 19 do begin
;(*pState_mabc).AareForegroundColors[*,i]=[0,0,255]
;(*pState_mabc).BergForegroundColors[*,i]=[0,0,255]
;endfor
;Aare_Table=Findgen(4,5)+1
;Berg_Table=Findgen(4,5)+2

;widget_control,(*pState_mabc).Aare_Triffid_Table,set_value=Aare_Table,foreground_color=(*pState_mabc).AareForegroundColors
;widget_control,(*pState_mabc).Berg_Triffid_Table,set_value=Berg_Table,foreground_color=(*pState_mabc).BergForegroundColors
widget_control,(*pstate_mabc).Load_Analyser_Button,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro UpdateAnalyserTable,event,type
widget_control,event.top,get_uvalue = pState_mabc
widget_control, (*pState_mabc).Scan_Table,get_value=Scan_Input
widget_control,(*pState_mabc).Analyser_Result,get_value=AR
widget_control,(*pState_mabc).Aare_Triffid_Table,get_value=Aare_Table
widget_control,(*pState_mabc).Berg_Triffid_Table,get_value=Berg_Table
Analyser_structure=(*pState_mabc).Analyser_structure
theta_index=widget_info((*pState_mabc).analyser_angle_droplist,/droplist_select)
DataType=(*pState_mabc).DataType
Xvariable=(*pState_mabc).Xvariable
Yvariable=(*pState_mabc).Yvariable
xcol=0
ycol=0
;
;
case type of
0:    $ ; from Gauss1d
begin
widget_control,(*pstate_mabc).A1_field_gauss1d,get_value = xpos
xpos=float(xpos[0])
end
1:    $ ; from contour plot
begin
widget_control,(*pState_mabc).Result_Abscissa,get_value=xpos
widget_control,(*pState_mabc).Result_Ordinate,get_value=ypos
end
2:    $;  from cross section
begin
widget_control,(*pstate_mabc).Plot_cross,get_value = Plot_cross
widget_control,(*pstate_mabc).CrossValue_Field,get_value = CrossValue
CrossValue=float(CrossValue[0])
;
if Plot_cross eq 0 then begin
xpos=CrossValue
widget_control,(*pstate_mabc).A1_field_cross,get_value = ypos
ypos=float(ypos[0])
endif else begin
ypos=CrossValue
widget_control,(*pstate_mabc).A1_field_cross,get_value = xpos
xpos=float(xpos[0])
endelse
end
endcase
;
;print,'Xvariable: ',Xvariable
;print,'Yvariable: ',Yvariable
if Xvariable eq 'AF' then xcol=2
if Xvariable eq 'AL' then xcol=3
if Xvariable eq 'AS' then xcol=4
if Xvariable eq 'DL' then xcol=5
if Xvariable eq 'DS' then xcol=6
if Xvariable eq 'DR' then xcol=7
if Yvariable eq 'AF' then ycol=2
if Yvariable eq 'AL' then ycol=3
if Yvariable eq 'AS' then ycol=4
if Yvariable eq 'DL' then ycol=5
if Yvariable eq 'DS' then ycol=6
if Yvariable eq 'DR' then ycol=7

if (xcol eq 0) and  (ycol eq 0) then return

;print, 'AR = ',AR
if AR le 4 then begin ; Aare
;print, 'xpos = ',xpos
Aare_Table[xcol,AR]=xpos
(*pState_mabc).AareForegroundColors[*,8*Ar+xcol]=[255,0,0]
if (Yvariable ne '') AND (type ne 0) then begin
Aare_Table[ycol,AR]=ypos
(*pState_mabc).AareForegroundColors[*,8*Ar+ycol]=[255,0,0]
endif
widget_control,(*pState_mabc).Aare_Triffid_Table,set_value=Aare_Table,foreground_color=(*pState_mabc).AareForegroundColors
endif else begin ; Berg
Berg_Table[xcol,AR-5]=xpos
(*pState_mabc).BergForegroundColors[*,8*(Ar-5)+xcol]=[255,0,0]
if (Yvariable ne '') AND (type ne 0) then begin
Berg_Table[ycol,AR-5]=ypos
(*pState_mabc).BergForegroundColors[*,8*(Ar-5)+ycol]=[255,0,0]
endif
widget_control,(*pState_mabc).Berg_Triffid_Table,set_value=Berg_Table,foreground_color=(*pState_mabc).BergForegroundColors
endelse
;
;memorize changes
;
case AR of
0:    $
begin
Analyser_structure.Aare_150.AFA150[1,theta_index]=Aare_Table[2,0]
Analyser_structure.Aare_150.ALA150[1,theta_index]=Aare_Table[3,0]
Analyser_structure.Aare_150.ASA150[1,theta_index]=Aare_Table[4,0]
Analyser_structure.Aare_150.DLA150[1,theta_index]=Aare_Table[5,0]
Analyser_structure.Aare_150.DSA150[1,theta_index]=Aare_Table[6,0]
Analyser_structure.Aare_150.DRA150[1,theta_index]=Aare_Table[7,0]
end
1:    $
begin
Analyser_structure.Aare_120.AFA120[1,theta_index]=Aare_Table[2,1]
Analyser_structure.Aare_120.ALA120[1,theta_index]=Aare_Table[3,1]
Analyser_structure.Aare_120.ASA120[1,theta_index]=Aare_Table[4,1]
Analyser_structure.Aare_120.DLA120[1,theta_index]=Aare_Table[5,1]
Analyser_structure.Aare_120.DSA120[1,theta_index]=Aare_Table[6,1]
Analyser_structure.Aare_120.DRA120[1,theta_index]=Aare_Table[7,1]
end
2:    $
begin
Analyser_structure.Aare_90.AFA90[1,theta_index]=Aare_Table[2,2]
Analyser_structure.Aare_90.ALA90[1,theta_index]=Aare_Table[3,2]
Analyser_structure.Aare_90.ASA90[1,theta_index]=Aare_Table[4,2]
Analyser_structure.Aare_90.DLA90[1,theta_index]=Aare_Table[5,2]
Analyser_structure.Aare_90.DSA90[1,theta_index]=Aare_Table[6,2]
Analyser_structure.Aare_90.DRA90[1,theta_index]=Aare_Table[7,2]
end
3:    $
begin
Analyser_structure.Aare_60.AFA60[1,theta_index]=Aare_Table[2,3]
Analyser_structure.Aare_60.ALA60[1,theta_index]=Aare_Table[3,3]
Analyser_structure.Aare_60.ASA60[1,theta_index]=Aare_Table[4,3]
Analyser_structure.Aare_60.DLA60[1,theta_index]=Aare_Table[5,3]
Analyser_structure.Aare_60.DSA60[1,theta_index]=Aare_Table[6,3]
Analyser_structure.Aare_60.DRA60[1,theta_index]=Aare_Table[7,3]
end
4:    $
begin
Analyser_structure.Aare_30.AFA30[1,theta_index]=Aare_Table[2,4]
Analyser_structure.Aare_30.ALA30[1,theta_index]=Aare_Table[3,4]
Analyser_structure.Aare_30.ASA30[1,theta_index]=Aare_Table[4,4]
Analyser_structure.Aare_30.DLA30[1,theta_index]=Aare_Table[5,4]
Analyser_structure.Aare_30.DSA30[1,theta_index]=Aare_Table[6,4]
Analyser_structure.Aare_30.DRA30[1,theta_index]=Aare_Table[7,4]
end
5:    $
begin
Analyser_structure.Berg_30.AFB30[1,theta_index]=Berg_Table[2,0]
Analyser_structure.Berg_30.ALB30[1,theta_index]=Berg_Table[3,0]
Analyser_structure.Berg_30.ASB30[1,theta_index]=Berg_Table[4,0]
Analyser_structure.Berg_30.DLB30[1,theta_index]=Berg_Table[5,0]
Analyser_structure.Berg_30.DSB30[1,theta_index]=Berg_Table[6,0]
Analyser_structure.Berg_30.DRB30[1,theta_index]=Berg_Table[7,0]
end
6:    $
begin
Analyser_structure.Berg_60.AFB60[1,theta_index]=Berg_Table[2,1]
Analyser_structure.Berg_60.ALB60[1,theta_index]=Berg_Table[3,1]
Analyser_structure.Berg_60.ASB60[1,theta_index]=Berg_Table[4,1]
Analyser_structure.Berg_60.DLB60[1,theta_index]=Berg_Table[5,1]
Analyser_structure.Berg_60.DSB60[1,theta_index]=Berg_Table[6,1]
Analyser_structure.Berg_60.DRB60[1,theta_index]=Berg_Table[7,1]
end
7:    $
begin
Analyser_structure.Berg_90.AFB90[1,theta_index]=Berg_Table[2,2]
Analyser_structure.Berg_90.ALB90[1,theta_index]=Berg_Table[3,2]
Analyser_structure.Berg_90.ASB90[1,theta_index]=Berg_Table[4,2]
Analyser_structure.Berg_90.DLB90[1,theta_index]=Berg_Table[5,2]
Analyser_structure.Berg_90.DSB90[1,theta_index]=Berg_Table[6,2]
Analyser_structure.Berg_90.DRB90[1,theta_index]=Berg_Table[7,2]
end
8:    $
begin
Analyser_structure.Berg_120.AFB120[1,theta_index]=Berg_Table[2,3]
Analyser_structure.Berg_120.ALB120[1,theta_index]=Berg_Table[3,3]
Analyser_structure.Berg_120.ASB120[1,theta_index]=Berg_Table[4,3]
Analyser_structure.Berg_120.DLB120[1,theta_index]=Berg_Table[5,3]
Analyser_structure.Berg_120.DSB120[1,theta_index]=Berg_Table[6,3]
Analyser_structure.Berg_120.DRB120[1,theta_index]=Berg_Table[7,3]
end
9:    $
begin
Analyser_structure.Berg_150.AFB150[1,theta_index]=Berg_Table[2,4]
Analyser_structure.Berg_150.ALB150[1,theta_index]=Berg_Table[3,4]
Analyser_structure.Berg_150.ASB150[1,theta_index]=Berg_Table[4,4]
Analyser_structure.Berg_150.DLB150[1,theta_index]=Berg_Table[5,4]
Analyser_structure.Berg_150.DSB150[1,theta_index]=Berg_Table[6,4]
Analyser_structure.Berg_150.DRB150[1,theta_index]=Berg_Table[7,4]
end
else:
endcase
(*pState_mabc).Analyser_structure=Analyser_structure
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABC_ContourDisplay,event,no_fit=no_fit

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    !ERROR_STATE.MSG)
widget_control,(*pState_mabc).Contour_Fit_types,set_value=0
return
endif


widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Contour_Fit_types,get_value=Contour_Fit_types
widget_control,(*pState_mabc).display,get_value=display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pState_mabc).ColourGradient,get_value=CG
DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
XCoords=*(*pState_mabc).XCoords
YCoords=*(*pState_mabc).YCoords
N_XCoords=n_elements(XCoords)
N_YCoords=n_elements(YCoords)
if display eq 0 then DataArray_z=*(*pState_mabc).DataArray_Zint
if display eq 1 then DataArray_z=*(*pState_mabc).DataArray_ZPeak
;help,DataArray_z
;print,'DataArray_z[0,*]: ',DataArray_z[0,*]
x=XCoords
y=YCoords



; before :z=DataArray_z[Analyser_Result,*,*]
;z=reform(z)


z=fltarr(N_XCoords,N_YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
k=0
xindex=0
yindex=0
for xindex=0,N_XCoords-1 do begin
    for yindex=0,N_YCoords-1 do begin
    z[xindex,yindex]=DataArray_z[Analyser_Result,k]
    k+=1
    endfor
endfor
;
IF n_elements(no_fit) eq 0 THEN BEGIN
if Contour_Fit_types eq 0 then begin
;index=where(z eq max(z),count)
;print,'index: ',index
;index=index[0]
;if count eq 0 then return
;xindex=long(index/N_XCoords)
;yindex=index-(xindex*N_XCoords)
;yindex=long(index/N_YCoords)
;xindex=index-(yindex*N_YCoords)
;print,'xindex: ',xindex
;print,'yindex: ',yindex

maxz=max(z)

xindexmax=0
yindexmax=0
for xindex=0,N_XCoords-1 do begin
    for yindex=0,N_YCoords-1 do begin
        if z[xindex,yindex] eq maxz then begin
        xindexmax=xindex
        yindexmax=yindex
       endif
    endfor
endfor

xpos=XCoords[xindexmax]
ypos=YCoords[yindexmax]
;
widget_control,(*pState_mabc).Result_Abscissa,set_value=xpos
widget_control,(*pState_mabc).Result_Ordinate,set_value=ypos
endif else begin

result=Gauss2DFit(Z,A,X,Y)
widget_control,(*pState_mabc).Result_Abscissa,set_value=A[4]
widget_control,(*pState_mabc).Result_Ordinate,set_value=A[5]
endelse
ENDIF


zstep=(max(z)-min(z))/100.0
zmin=min(z)+zstep*(CG-1)
index=where(z lt zmin,count)
if count ne 0 then z[index] = zmin


;help,zmin

c=Indgen(12)+1


xlo=min(x)
xhi=max(x)
ylo=min(y)
yhi=max(y)
(*pState_mabc).xbox_gauss=[xlo,xhi]
(*pState_mabc).ybox_gauss=[ylo,yhi]
(*pState_mabc).xrange_gauss=[xlo,xhi]
(*pState_mabc).yrange_gauss=[ylo,yhi]
;widget_control,(*pState_mabc).ColourGradient,set_value=1;

wset,(*pState_mabc).winPix_gauss2D
;

;print,'z: ',z
;print,''
;print,'x: ',x
;print,''
;print,'y: ',y
;print,''
contour,z,x,y,xtitle = 'Abscissa', $
     ytitle = 'Ordinate',xrange=(*pState_mabc).xrange_gauss,min_value=0.1, $
     xstyle = 1,ystyle = 1,yrange=(*pState_mabc).yrange_gauss,c_colors=c,nlevels=12,/fill
wset,(*pState_mabc).winVis_gauss

device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState_mabc).winPix_gauss2D]

widget_control,(*pState_mabc).SaveImageButton,sensitive=1

;icontour,z,x,y,xtitle = 'Abscissa', $
;     ytitle = 'Ordinate',xrange=(*pState_mabc).xrange_gauss,min_value=0.1, $
;     yrange=(*pState_mabc).yrange_gauss,c_color=c,nlevels=12,/fill,c_value=0

;device, decomposed = 1
;image24 = tvrd(True=1)
;write_JPEG,'C:/image.jpg',image24,Quality=75, True=1
;device, decomposed = 0


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Connect_mabc,event
widget_control,event.top,get_uvalue = pstate_mabc
widget_control,(*pstate_mabc).connectbutton,sensitive = 0
;print,' woof'
;filename='C:\Documents and Settings\tregenna\My Documents\NIST\DAVE\cvs_nist\dave\programs\auxiliary\PSI\MARS\MarsSICSInfo.txt'
delim=(*pstate_mabc).delim
get_lun,UnitUser_exe
(*pstate_mabc).UnitUser_exe=UnitUser_exe
get_lun,UnitUser_2
(*pstate_mabc).UnitUser_2=UnitUser_2
get_lun,UnitSpy
(*pstate_mabc).UnitSpy=UnitSpy
get_lun,UnitManager
(*pstate_mabc).UnitManager=UnitManager



;filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MarsSICSInfo_User.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsSICSInfo_User.txt'
hoststring=''
portstring=''
userstring=''
passwordstring=''
openr,lun,filename,/get_lun
readf,lun,hoststring
readf,lun,portstring
readf,lun,userstring
readf,lun,passwordstring
free_lun,lun,/force
;
equalsign=strpos(hoststring,'=')
host=strmid(hoststring,equalsign+1)
equalsign=strpos(portstring,'=')
port=strmid(portstring,equalsign+1)
port=long(port)
equalsign=strpos(userstring,'=')
user=strmid(userstring,equalsign+1)
equalsign=strpos(passwordstring,'=')
password=strmid(passwordstring,equalsign+1)
;
;
response=sicsconnect(UnitUser_exe,host,port,error=error)
;print,'response = ',response
;print,'error = ',error
;help,response
    IF response eq 0 then begin
; the program is not running in democnstration mode
print,'Connection Successful'
(*pstate_mabc).demo_mabc=0
logon=sicslogon(UnitUser_exe,user,password)
;print,'woofb'
;print,logon
if logon eq 0 then begin
void = dialog_message(dialog_parent = event.top, $
'SICS User login is incorrect. Please inspect and edit the file ' +  $
'in the Dave auxillary directory.  The program will now exit.')
mabc_exit,event
return
endif
    ENDIF ELSE BEGIN
    void = dialog_message(dialog_parent = event.top, $
    'Connection to MARS not found.  The program shall run in demonstration mode.')
(*pstate_mabc).demo_mabc=1
    ENDELSE
;
response=sicsconnect(UnitUser_2,host,port,error=error)
;print,'response = ',response
;print,'error = ',error
;help,response
    IF response eq 0 then begin
; the program is not running in democnstration mode
print,'Connection Successful'
(*pstate_mabc).demo_mabc=0
logon=sicslogon(UnitUser_2,user,password)
;print,'woofb'
;print,logon
if logon eq 0 then begin
void = dialog_message(dialog_parent = event.top, $
'SICS User login is incorrect. Please inspect and edit the file ' +  $
'in the Dave auxillary directory.  The program will now exit.')
mabc_exit,event
return
endif
    ENDIF ELSE BEGIN
    void = dialog_message(dialog_parent = event.top, $
    'Connection to MARS not found.  The program shall run in demonstration mode.')
(*pstate_mabc).demo_mabc=1
    ENDELSE

;filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MarsSICSInfo_Spy.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsSICSInfo_Spy.txt'
hoststring=''
portstring=''
userstring=''
passwordstring=''
openr,lun,filename,/get_lun
readf,lun,hoststring
readf,lun,portstring
readf,lun,userstring
readf,lun,passwordstring
free_lun,lun,/force
;
equalsign=strpos(hoststring,'=')
host=strmid(hoststring,equalsign+1)
equalsign=strpos(portstring,'=')
port=strmid(portstring,equalsign+1)
port=long(port)
equalsign=strpos(userstring,'=')
user=strmid(userstring,equalsign+1)
equalsign=strpos(passwordstring,'=')
password=strmid(passwordstring,equalsign+1)


response=sicsconnect(UnitSpy,host,port,error=error)
;print,'response = ',response
;print,'error = ',error
;help,response
    IF response eq 0 then begin
; the program is not running in demonstration mode
print,'Connection Successful'
(*pstate_mabc).demo_mabc=0
logon=sicslogon(UnitSpy,user,password)
;print,'woofb'
;print,logon
if logon eq 0 then begin
void = dialog_message(dialog_parent = event.top, $
'SICS Spy login is incorrect. Please inspect and edit the file ' +  $
'in the Dave auxillary directory.  The program will now exit.')
mabc_exit,event
return
endif
    ENDIF ELSE BEGIN
    void = dialog_message(dialog_parent = event.top, $
    'Connection to MARS not found.  The program shall run in demonstration mode.')
(*pstate_mabc).demo_mabc=1
    ENDELSE

;filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MarsSICSInfo_Manager.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsSICSInfo_Manager.txt'
hoststring=''
portstring=''
userstring=''
passwordstring=''
openr,lun,filename,/get_lun
readf,lun,hoststring
readf,lun,portstring
readf,lun,userstring
readf,lun,passwordstring
free_lun,lun,/force
;
equalsign=strpos(hoststring,'=')
host=strmid(hoststring,equalsign+1)
equalsign=strpos(portstring,'=')
port=strmid(portstring,equalsign+1)
port=long(port)
equalsign=strpos(userstring,'=')
user=strmid(userstring,equalsign+1)
equalsign=strpos(passwordstring,'=')
password=strmid(passwordstring,equalsign+1)


response=sicsconnect(UnitManager,host,port,error=error)
;print,'response = ',response
;print,'error = ',error
;help,response
    IF response eq 0 then begin
; the program is not running in democnstration mode
print,'Connection Successful'
(*pstate_mabc).demo_mabc=0
logon=sicslogon(UnitManager,user,password)
;print,'woofb'
;print,logon
if logon eq 0 then begin
void = dialog_message(dialog_parent = event.top, $
'SICS Manager login is incorrect. Please inspect and edit the file ' +  $
'in the Dave auxillary directory.  The program will now exit.')
mabc_exit,event
return
endif
    ENDIF ELSE BEGIN
    void = dialog_message(dialog_parent = event.top, $
    'Connection to MARS not found.  The program shall run in demonstration mode.')
(*pstate_mabc).demo_mabc=1
    ENDELSE


widget_control,(*pstate_mabc).connectbutton,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SendParameters,event
widget_control,event.top,get_uvalue = pstate_mabc

if (*pstate_mabc).demo_mabc eq 1 then return
widget_control,(*pstate_mabc).ParameterButton,sensitive = 0

widget_control,(*pstate_mabc).Chopper_Table,get_value=Chopper_Table
;
;help,chopper_table
;print,chopper_table
chopper_info=fltarr(2,5)
reads,Chopper_Table,chopper_info
;help,chopper_info
chopper_info[1,*]*=60.0 ; convert to rpm
Chopper_Table=string(chopper_info)

;help,chopper_table
UnitUser_exe=(*pstate_mabc).UnitUser_exe
UnitManager=(*pstate_mabc).UnitManager

;choppers
ChopperCommand_array=strarr(6)
ChopperCommand_array[0]='run snailphase '
ChopperCommand_array[1]='run masterphase '
ChopperCommand_array[2]='run rabbitphase '
ChopperCommand_array[3]='run fourphase '
ChopperCommand_array[4]='run fivephase '
ChopperCommand_array[5]='run masterspeed '
;
;
for i = 0,5 do begin
if i le 4 then begin
ChopperCommand_array[i]+=strtrim(Chopper_Table[0,i],2)
endif else begin
ChopperCommand_array[i]+=strtrim(Chopper_Table[1,1],2)
endelse
print,ChopperCommand_array[i]
endfor

for i = 0,5 do begin
response=sicsexecute(event,UnitUser_exe,ChopperCommand_array[i])
print,'response = ',i,response
print,''
endfor

response=sicsexecute(event,UnitUser_exe,'success')
print,'response = ',response
print,''

widget_control,(*pState_mabc).TimeBinStart,get_value=TOF_start
TOF_start=long(TOF_start*10.0)
widget_control,(*pState_mabc).TotalTimeBinNumber,get_value=notimebin
widget_control,(*pState_mabc).TimeBinStep,get_value=TOF_step
TOF_step=fix(TOF_step*10.0)
TOF_start=strtrim(string(TOF_start[0]),2)
notimebin=strtrim(string(notimebin[0]),2)
TOF_step=strtrim(string(TOF_step[0]),2)


;HM genbin start step n
;Generates a new equally spaced time binning array.
;Number n time bins will be generated starting from start with a stepwidth of step (example: HM genbin 10 1 5).


command='hm genbin '+TOF_start+' '+TOF_step+' '+notimebin

print,'hm command = ',command

response=sicsexecute(event,UnitManager,command)
print,'response = ',response
response=sicsexecute(event,UnitManager,'hm init')
print,'response = ',response

TimeBinIndices=(*pState_mabc).TimeBinIndices
str=strtrim(string(TimeBinIndices[0]),2)+','
for i = 1,12 do begin
str+=strtrim(string(TimeBinIndices[i]),2)+','
endfor
str+=strtrim(string(TimeBinIndices[13]),2)
command='TimeBinIndices '+str
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response
;
widget_control,(*pState_mabc).mica,get_value =mica
mica=fix(mica[0])
;
if mica eq 0 then Target_Reflection='002'
if mica eq 1 then Target_Reflection='004'
if mica eq 2 then Target_Reflection='006'
if mica eq 3 then Target_Reflection='008'

command='TargetReflection '+Target_Reflection
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response

widget_control,(*pState_mabc).Aare_Triffid_Table,get_value=Aare_Table
widget_control,(*pState_mabc).Berg_Triffid_Table,get_value=Berg_Table

whereblank=where(Aare_Table eq '',count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'At least one of the cells of the Aare Table is invalid')
widget_control,(*pstate_mabc).parameterbutton,sensitive = 1
return
endif
;
whereblank=where(Berg_Table eq '',count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'At least one of the cells of the Berg Table is invalid')
widget_control,(*pstate_mabc).parameterbutton,sensitive = 1
return
endif

for i = 0, 4 do begin    ; row
if i eq 0 then analyser='A30'
if i eq 1 then analyser='A60'
if i eq 2 then analyser='A90'
if i eq 3 then analyser='A120'
if i eq 4 then analyser='A150'

    for j = 2, 7 do begin   ;column
;
if j eq 2 then motor='AF'
if j eq 3 then motor='AL'
if j eq 4 then motor='AS'
if j eq 5 then motor='DL'
if j eq 6 then motor='DS'
if j eq 7 then motor='DR'

motorname=strtrim((motor+analyser),2)
value=strtrim(string(Aare_Table[j,i]),2)
command='drive '+motorname+' '+value
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response
    endfor
endfor
;
for i = 0, 4 do begin    ; row
if i eq 0 then analyser='B30'
if i eq 1 then analyser='B60'
if i eq 2 then analyser='B90'
if i eq 3 then analyser='B120'
if i eq 4 then analyser='B150'

    for j = 2, 7 do begin   ;column
;
if j eq 2 then motor='AF'
if j eq 3 then motor='AL'
if j eq 4 then motor='AS'
if j eq 5 then motor='DL'
if j eq 6 then motor='DS'
if j eq 7 then motor='DR'

motorname=strtrim((motor+analyser),2)
value=strtrim(string(Berg_Table[j,i]),2)
command='drive '+motorname+' '+value
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response
    endfor
endfor


widget_control,(*pstate_mabc).parameterbutton,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SendHistogramParameters,event
widget_control,event.top,get_uvalue = pstate_mabc
UnitManager=(*pstate_mabc).UnitManager
UnitUser_exe=(*pstate_mabc).UnitUser_exe

if (*pstate_mabc).demo_mabc eq 1 then return
widget_control,(*pstate_mabc).ParameterHistogramButton,sensitive = 0

widget_control,(*pState_mabc).TimeBinStart,get_value=TOF_start
TOF_start=long(TOF_start*10.0)
widget_control,(*pState_mabc).TotalTimeBinNumber,get_value=notimebin
widget_control,(*pState_mabc).TimeBinStep,get_value=TOF_step
TOF_step=fix(TOF_step*10.0)
TOF_start=strtrim(string(TOF_start[0]),2)
notimebin=strtrim(string(notimebin[0]),2)
TOF_step=strtrim(string(TOF_step[0]),2)


;HM genbin start step n
;Generates a new equally spaced time binning array.
;Number n time bins will be generated starting from start with a stepwidth of step (example: HM genbin 10 1 5).


command='hm genbin '+TOF_start+' '+TOF_step+' '+notimebin

print,'hm command = ',command

response=sicsexecute(event,UnitManager,command)
print,'response = ',response
response=sicsexecute(event,UnitManager,'hm init')
print,'response = ',response

TimeBinIndices=(*pState_mabc).TimeBinIndices
str=strtrim(string(TimeBinIndices[0]),2)+','
for i = 1,12 do begin
str+=strtrim(string(TimeBinIndices[i]),2)+','
endfor
str+=strtrim(string(TimeBinIndices[13]),2)
command='TimeBinIndices '+str
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response
;
widget_control,(*pState_mabc).mica,get_value =mica
mica=fix(mica[0])
;
if mica eq 0 then Target_Reflection='002'
if mica eq 1 then Target_Reflection='004'
if mica eq 2 then Target_Reflection='006'
if mica eq 3 then Target_Reflection='008'

command='TargetReflection '+Target_Reflection
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response

widget_control,(*pstate_mabc).parameterhistogrambutton,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SendTriffidParameters,event
widget_control,event.top,get_uvalue = pstate_mabc
UnitUser_exe=(*pstate_mabc).UnitUser_exe

if (*pstate_mabc).demo_mabc eq 1 then return
widget_control,(*pstate_mabc).ParameterTriffidButton,sensitive = 0


widget_control,(*pState_mabc).Aare_Triffid_Table,get_value=Aare_Table
widget_control,(*pState_mabc).Berg_Triffid_Table,get_value=Berg_Table

whereblank=where(Aare_Table eq '',count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'At least one of the cells of the Aare Table is invalid')
widget_control,(*pstate_mabc).ParameterTriffidButton,sensitive = 1
return
endif
;
whereblank=where(Berg_Table eq '',count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'At least one of the cells of the Berg Table is invalid')
widget_control,(*pstate_mabc).ParameterTriffidButton,sensitive = 1
return
endif


for i = 0, 4 do begin    ; row
if i eq 0 then analyser='A30'
if i eq 1 then analyser='A60'
if i eq 2 then analyser='A90'
if i eq 3 then analyser='A120'
if i eq 4 then analyser='A150'

    for j = 2, 7 do begin   ;column
;
if j eq 2 then motor='AF'
if j eq 3 then motor='AL'
if j eq 4 then motor='AS'
if j eq 5 then motor='DL'
if j eq 6 then motor='DS'
if j eq 7 then motor='DR'

motorname=strtrim((motor+analyser),2)
value=strtrim(string(Aare_Table[j,i]),2)
command='drive '+motorname+' '+value
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response
    endfor
endfor
;
for i = 0, 4 do begin    ; row
if i eq 0 then analyser='B30'
if i eq 1 then analyser='B60'
if i eq 2 then analyser='B90'
if i eq 3 then analyser='B120'
if i eq 4 then analyser='B150'

    for j = 2, 7 do begin   ;column
;
if j eq 2 then motor='AF'
if j eq 3 then motor='AL'
if j eq 4 then motor='AS'
if j eq 5 then motor='DL'
if j eq 6 then motor='DS'
if j eq 7 then motor='DR'

motorname=strtrim((motor+analyser),2)
value=strtrim(string(Berg_Table[j,i]),2)
command='drive '+motorname+' '+value
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response
    endfor
endfor


widget_control,(*pstate_mabc).ParameterTriffidButton,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SendAareTriffidParameters,event
widget_control,event.top,get_uvalue = pstate_mabc
UnitUser_exe=(*pstate_mabc).UnitUser_exe

if (*pstate_mabc).demo_mabc eq 1 then return
widget_control,(*pstate_mabc).ParameterAareTriffidButton,sensitive = 0


widget_control,(*pState_mabc).Aare_Triffid_Table,get_value=Aare_Table

whereblank=where(Aare_Table eq '',count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'At least one of the cells of the Aare Table is invalid')
widget_control,(*pstate_mabc).ParameterAareTriffidButton,sensitive = 1
return
endif
;

for i = 0, 4 do begin    ; row
if i eq 0 then analyser='A30'
if i eq 1 then analyser='A60'
if i eq 2 then analyser='A90'
if i eq 3 then analyser='A120'
if i eq 4 then analyser='A150'

    for j = 2, 7 do begin   ;column
;
if j eq 2 then motor='AF'
if j eq 3 then motor='AL'
if j eq 4 then motor='AS'
if j eq 5 then motor='DL'
if j eq 6 then motor='DS'
if j eq 7 then motor='DR'

motorname=strtrim((motor+analyser),2)
value=strtrim(string(Aare_Table[j,i]),2)
command='drive '+motorname+' '+value
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response
    endfor
endfor

widget_control,(*pstate_mabc).ParameterAareTriffidButton,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SendBergTriffidParameters,event
widget_control,event.top,get_uvalue = pstate_mabc
UnitUser_exe=(*pstate_mabc).UnitUser_exe

if (*pstate_mabc).demo_mabc eq 1 then return
widget_control,(*pstate_mabc).ParameterBergTriffidButton,sensitive = 0
widget_control,(*pState_mabc).Berg_Triffid_Table,get_value=Berg_Table
;
whereblank=where(Berg_Table eq '',count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'At least one of the cells of the Berg Table is invalid')
widget_control,(*pstate_mabc).ParameterBergTriffidButton,sensitive = 1
return
endif


for i = 0, 4 do begin    ; row
if i eq 0 then analyser='B30'
if i eq 1 then analyser='B60'
if i eq 2 then analyser='B90'
if i eq 3 then analyser='B120'
if i eq 4 then analyser='B150'

    for j = 2, 7 do begin   ;column
;
if j eq 2 then motor='AF'
if j eq 3 then motor='AL'
if j eq 4 then motor='AS'
if j eq 5 then motor='DL'
if j eq 6 then motor='DS'
if j eq 7 then motor='DR'

motorname=strtrim((motor+analyser),2)
value=strtrim(string(Berg_Table[j,i]),2)
command='drive '+motorname+' '+value
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response
    endfor
endfor


widget_control,(*pstate_mabc).ParameterBergTriffidButton,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SendChopperParameters,event
widget_control,event.top,get_uvalue = pstate_mabc

if (*pstate_mabc).demo_mabc eq 1 then return
widget_control,(*pstate_mabc).ParameterChopperButton,sensitive = 0

widget_control,(*pstate_mabc).Chopper_Table,get_value=Chopper_Table
;
;help,chopper_table
;print,chopper_table
chopper_info=fltarr(2,5)
reads,Chopper_Table,chopper_info
;help,chopper_info
chopper_info[1,*]*=60.0 ; convert to rpm
Chopper_Table=string(chopper_info)

;help,chopper_table
UnitUser_exe=(*pstate_mabc).UnitUser_exe

;choppers
ChopperCommand_array=strarr(6)
ChopperCommand_array[0]='run snailphase '
ChopperCommand_array[1]='run masterphase '
ChopperCommand_array[2]='run rabbitphase '
ChopperCommand_array[3]='run fourphase '
ChopperCommand_array[4]='run fivephase '
ChopperCommand_array[5]='run masterspeed '
;
;
for i = 0,5 do begin
if i le 4 then begin
ChopperCommand_array[i]+=strtrim(Chopper_Table[0,i],2)
endif else begin
ChopperCommand_array[i]+=strtrim(Chopper_Table[1,1],2)
endelse
print,ChopperCommand_array[i]
endfor

for i = 0,5 do begin
response=sicsexecute(event,UnitUser_exe,ChopperCommand_array[i])
print,'response = ',i,response
print,''
endfor

response=sicsexecute(event,UnitUser_exe,'success')
print,'response = ',response
print,''

widget_control,(*pState_mabc).mica,get_value =mica
mica=fix(mica[0])
;
if mica eq 0 then Target_Reflection='002'
if mica eq 1 then Target_Reflection='004'
if mica eq 2 then Target_Reflection='006'
if mica eq 3 then Target_Reflection='008'

command='TargetReflection '+Target_Reflection
response=sicsexecute(event,UnitUser_exe,command)
print,'response = ',response


widget_control,(*pstate_mabc).parameterchopperbutton,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro AnalyserAngle,event
Populate_Triffid_Tables,event
MABCChopperPhases,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ScanType,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control, (*pState_mabc).Scan_Table,get_value=Scan_Input
widget_control, (*pState_mabc).Scan_Type_Select,get_value=ST
if ST eq 0 then begin
Scan_Input[1,*]='-' ; 1d
endif ;else begin
;Scan_Input[1,*]='' ; 2d
;endelse
widget_control, (*pState_mabc).Scan_Table,set_value=Scan_Input
(*pState_mabc).Scan_Input=Scan_Input
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Fit_All,event,sumcount=sumcount

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    !ERROR_STATE.MSG)
return
endif

widget_control,event.top,get_uvalue = pState_mabc
DataType=(*pState_mabc).DataType
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pState_mabc).Fit_Modes,get_value=FitMode
widget_control,(*pState_mabc).nterms_raw,get_value=nterms
GaussParameters=*(*pState_mabc).GaussParameters  ; fltarr(10,n_TotalSpectra,6)
Gaussfits_x=*(*pState_mabc).Gaussfits_x
Gaussfits_y=*(*pState_mabc).Gaussfits_y
peakposition=(*pState_mabc).tofoutput[0,1]
peakposition=float(peakposition)
if ((*pstate_mabc).demo_mabc eq 1) and ((*pstate_mabc).loaded_mabc eq 0) then peakposition = 32.3610
Gaussfits_x[Analyser_Result,*,*]=0.0
Gaussfits_y[Analyser_Result,*,*]=0.0
DataArray_Zint=*(*pState_mabc).DataArray_Zint ; fltarr(10,n_TotalSpectra)
DataArray_ZPeak=*(*pState_mabc).DataArray_ZPeak ; fltarr(10,n_TotalSpectra)
DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(XCoords)
;get gauss fit parameters
widget_control,(*pstate_mabc).A0_field,get_value = A0
A0=float(A0[0])
widget_control,(*pstate_mabc).A1_field,get_value = A1
A1=float(A1[0])
widget_control,(*pstate_mabc).A2_field,get_value = A2
A2=float(A2[0])
widget_control,(*pstate_mabc).A3_field,get_value = A3
A3=float(A3[0])
widget_control,(*pstate_mabc).A4_field,get_value = A4
A4=float(A4[0])
widget_control,(*pstate_mabc).A5_field,get_value = A5
A5=float(A5[0])
widget_control,(*pstate_mabc).xmin_field,get_value = xmin
xmin=float(xmin[0])
widget_control,(*pstate_mabc).xmax_field,get_value = xmax
xmax=float(xmax[0])
estimates=[A0,A1,A2,A3,A4,A5]
;
IF DataType EQ 0 THEN BEGIN
n_TotalSpectra=N_XCoords
ENDIF ELSE BEGIN
YCoords=*(*pState_mabc).YCoords
N_YCoords=n_elements(YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
ENDELSE
for j = 1, n_TotalSpectra do begin
spectrum_number=j
print,'spectrum_number = ', spectrum_number
spectrum_number-=1

IF DataType EQ 0 THEN BEGIN
x=DataArray_x(Analyser_Result,spectrum_number,*)
y=DataArray_y(Analyser_Result,spectrum_number,*)
ENDIF ELSE BEGIN
xnum=spectrum_number/N_YCoords
ynum=spectrum_number-xnum*N_YCoords
x=DataArray_x(Analyser_Result,xnum,ynum,*)
y=DataArray_y(Analyser_Result,xnum,ynum,*)
ENDELSE
x=reform(x)
y=reform(y)
if FitMode eq 0 then begin
A0=max(y)
A1=(x[where(y eq A0)])[0]
A2=((max(x)-min(x))/12.0)
A3=0.0
A4=0.0
A5=0.0
endif else begin
wheregt=where(x gt xmin,count)
if count ne 0 then begin
x=x[wheregt]
y=y[wheregt]
endif
wherelt=where(x lt xmax,count)
if count ne 0 then begin
x=x[wherelt]
y=y[wherelt]
endif
endelse
wherenezero=where(y ne 0.0,count)
if count ne 0 then begin
y=y[wherenezero]
x=x[wherenezero]
endif

;
;let us do the fit
totaly=total(y)
if n_elements(sumcount) eq 0 then begin
    if total(y) gt 10.0 then begin
        if nterms eq 6 then estimates=[A0,A1,A2,A3,A4,A5]
        if nterms eq 5 then estimates=[A0,A1,A2,A3,A4]
        if nterms eq 4 then estimates=[A0,A1,A2,A3]
        if nterms eq 3 then estimates=[A0,A1,A2]
        yfit=gaussfit(x,y,coeff,estimates=estimates,nterms=nterms)
        if nterms eq 5 then coeff=[coeff,0.0]
        if nterms eq 4 then coeff=[coeff,0.0,0.0]
        if nterms eq 3 then coeff=[coeff,0.0,0.0,0.0]
        m=n_elements(yfit)
        ;n=n_elements(x)
        Gaussfits_x[Analyser_Result,j-1,0:m-1]=x
        Gaussfits_y[Analyser_Result,j-1,0:m-1]=yfit
        GaussParameters[Analyser_Result,j-1,*]=coeff
        DataArray_Zint[Analyser_Result,j-1]=coeff[0]
        deviation=abs(PeakPosition-coeff[1])
       ;print,'deviation: ',deviation
        maxdeviation=abs(PeakPosition-0.0)
       ;print,'maxdeviation: ',maxdeviation
        intfactor=1-(deviation/maxdeviation)
       ;print,'intfactor: ',intfactor
        DataArray_ZPeak[Analyser_Result,j-1]=intfactor
       ;print,''
    endif
endif else begin
DataArray_Zint[Analyser_Result,j-1]=totaly
endelse



    ;else begin
;if nterms eq 6 then coeff=[0.0,0.0,0.0,0.0,0.0,0.0]
;if nterms eq 5 then coeff=[0.0,0.0,0.0,0.0,0.0]
;if nterms eq 4 then coeff=[0.0,0.0,0.0,0.0]
;if nterms eq 3 then coeff=[0.0,0.0,0.0]
;help,Gaussfits_x
;help,x
;help,Analyser_Result
;help,j
;help,m
;Gaussfits_x[Analyser_Result,j-1,0:m-1]=x
;Gaussfits_y[Analyser_Result,j-1,0:m-1]=fltarr(n_elements(x))
;GaussParameters[Analyser_Result,j-1,*]=coeff
;DataArray_Zint[Analyser_Result,j-1]=coeff[0]
;deviation=abs(PeakPosition-coeff[1])
;;print,'deviation: ',deviation
;maxdeviation=abs(PeakPosition-0.0)
;;print,'maxdeviation: ',maxdeviation
;intfactor=1-(deviation/maxdeviation)
;;print,'intfactor: ',intfactor
;DataArray_ZPeak[Analyser_Result,j-1]=intfactor

;endelse


endfor

*(*pState_mabc).Gaussfits_x=Gaussfits_x
*(*pState_mabc).Gaussfits_y=Gaussfits_y
*(*pState_mabc).GaussParameters=GaussParameters
*(*pState_mabc).DataArray_Zint=DataArray_Zint
*(*pState_mabc).DataArray_ZPeak=DataArray_ZPeak

mabcPlot_raw,event
IF DataType EQ 0 THEN BEGIN
MABCGauss1D_Plot,event
ENDIF ELSE BEGIN
MABC_ContourDisplay,event
MABCCross_Plot,event
ENDELSE
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Delete_All,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
DataType=(*pState_mabc).DataType
Gaussfits_x=*(*pState_mabc).Gaussfits_x
Gaussfits_y=*(*pState_mabc).Gaussfits_y
GaussParameters=*(*pState_mabc).GaussParameters
DataArray_Zint=*(*pState_mabc).DataArray_Zint
DataArray_ZPeak=*(*pState_mabc).DataArray_ZPeak
Gaussfits_x[Analyser_Result,*,*]=0.0
Gaussfits_y[Analyser_Result,*,*]=0.0
GaussParameters[Analyser_Result,*,*]=0.0
DataArray_Zint[Analyser_Result,*]=0.0
DataArray_ZPeak[Analyser_Result,*]=0.0
*(*pState_mabc).Gaussfits_x=Gaussfits_x
*(*pState_mabc).Gaussfits_y=Gaussfits_y
*(*pState_mabc).GaussParameters=GaussParameters
*(*pState_mabc).DataArray_Zint=DataArray_Zint
*(*pState_mabc).DataArray_ZPeak=DataArray_ZPeak
mabcPlot_raw,event
IF DataType EQ 0 THEN BEGIN
MABCGauss1D_Plot,event
ENDIF ELSE BEGIN
MABC_ContourDisplay,event
MABCCross_Plot,event
ENDELSE
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Delete_Current,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pstate_mabc).raw_SliderValue,get_value = spectrum_number
spectrum_number=fix(spectrum_number[0])
spectrum_number-=1
DataType=(*pState_mabc).DataType
Gaussfits_x=*(*pState_mabc).Gaussfits_x
Gaussfits_y=*(*pState_mabc).Gaussfits_y
GaussParameters=*(*pState_mabc).GaussParameters
DataArray_Zint=*(*pState_mabc).DataArray_Zint
DataArray_ZPeak=*(*pState_mabc).DataArray_ZPeak
Gaussfits_x[Analyser_Result,spectrum_number,*]=0.0
Gaussfits_y[Analyser_Result,spectrum_number,*]=0.0
GaussParameters[Analyser_Result,spectrum_number,*]=0.0
DataArray_Zint[Analyser_Result,spectrum_number]=0.0
DataArray_ZPeak[Analyser_Result,spectrum_number]=0.0
*(*pState_mabc).Gaussfits_x=Gaussfits_x
*(*pState_mabc).Gaussfits_y=Gaussfits_y
*(*pState_mabc).GaussParameters=GaussParameters
*(*pState_mabc).DataArray_Zint=DataArray_Zint
*(*pState_mabc).DataArray_ZPeak=DataArray_ZPeak
mabcPlot_raw,event
IF DataType EQ 0 THEN BEGIN
MABCGauss1D_Plot,event
ENDIF ELSE BEGIN
MABC_ContourDisplay,event
MABCCross_Plot,event
ENDELSE
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Fit_Current,event,sumcount=sumcount

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    !ERROR_STATE.MSG)
return
endif


widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Fit_Modes,get_value=FitMode
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pState_mabc).nterms_raw,get_value=nterms
DataType=(*pState_mabc).DataType
Gaussfits_x=*(*pState_mabc).Gaussfits_x
Gaussfits_y=*(*pState_mabc).Gaussfits_y
GaussParameters=*(*pState_mabc).GaussParameters  ; fltarr(10,n_TotalSpectra,6)
DataArray_Zint=*(*pState_mabc).DataArray_Zint ; fltarr(10,n_TotalSpectra)
DataArray_ZPeak=*(*pState_mabc).DataArray_ZPeak ; fltarr(10,n_TotalSpectra)
peakposition=(*pState_mabc).tofoutput[0,1]
peakposition=float(peakposition)
if ((*pstate_mabc).demo_mabc eq 1) and ((*pstate_mabc).loaded_mabc eq 0) then peakposition = 32.3610
XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(XCoords)
DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
widget_control,(*pstate_mabc).raw_SliderValue,get_value = spectrum_number
spectrum_number=fix(spectrum_number[0])
spectrum_number-=1
;get gauss fit parameters
widget_control,(*pstate_mabc).A0_field,get_value = A0
A0=float(A0[0])
widget_control,(*pstate_mabc).A1_field,get_value = A1
A1=float(A1[0])
widget_control,(*pstate_mabc).A2_field,get_value = A2
A2=float(A2[0])
widget_control,(*pstate_mabc).A3_field,get_value = A3
A3=float(A3[0])
widget_control,(*pstate_mabc).A4_field,get_value = A4
A4=float(A4[0])
widget_control,(*pstate_mabc).A5_field,get_value = A5
A5=float(A5[0])
;
widget_control,(*pstate_mabc).xmin_field,get_value = xmin
xmin=float(xmin[0])
widget_control,(*pstate_mabc).xmax_field,get_value = xmax
xmax=float(xmax[0])
;
IF DataType EQ 0 THEN BEGIN
n_TotalSpectra=N_XCoords
x=DataArray_x[Analyser_Result,spectrum_number,*]
y=DataArray_y[Analyser_Result,spectrum_number,*]

ENDIF ELSE BEGIN
YCoords=*(*pState_mabc).YCoords
N_YCoords=n_elements(YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
xnum=spectrum_number/N_YCoords
ynum=spectrum_number-xnum*N_YCoords
;
x=DataArray_x[Analyser_Result,xnum,ynum,*]
y=DataArray_y[Analyser_Result,xnum,ynum,*]

ENDELSE
x=reform(x)
y=reform(y)
;print, 'FitMode: ', FitMode
;let us do the fit
;
;help,y
y=float(y)
;help,y
;print,'y: ',y
if FitMode eq 0 then begin
A0=max(y)
A0=float(A0)
A1=(x[where(y eq A0)])[0]
A2=((max(x)-min(x))/12.0)
A3=0.0
A4=0.0
A5=0.0
endif else begin
wheregt=where(x gt xmin,count)
if count ne 0 then begin
x=x[wheregt]
y=y[wheregt]
endif
wherelt=where(x lt xmax,count)
if count ne 0 then begin
x=x[wherelt]
y=y[wherelt]
endif
endelse
wherenezero=where(y ne 0.0,count)
if count ne 0 then begin
y=y[wherenezero]
x=x[wherenezero]
endif


totaly=total(y)
if n_elements(sumcount) eq 0 then begin
    if total(y) gt 10.0 then begin
       if nterms eq 6 then estimates=[A0,A1,A2,A3,A4,A5]
       if nterms eq 5 then estimates=[A0,A1,A2,A3,A4]
       if nterms eq 4 then estimates=[A0,A1,A2,A3]
       if nterms eq 3 then estimates=[A0,A1,A2]
       yfit=gaussfit(x,y,coeff,estimates=estimates,nterms=nterms)
       if nterms eq 5 then coeff=[coeff,0.0]
       if nterms eq 4 then coeff=[coeff,0.0,0.0]
       if nterms eq 3 then coeff=[coeff,0.0,0.0,0.0]


       ;print,coeff
       ;help,coeff
       ;print,'x: ',x
       ;print,'yfit: ',yfit
       ;help,Analyser_Result
       ;help,spectrum_number

       m=n_elements(yfit)
       n=n_elements(x)
       Gaussfits_x[Analyser_Result,spectrum_number,*]=0.0
       Gaussfits_y[Analyser_Result,spectrum_number,*]=0.0
       Gaussfits_x[Analyser_Result,spectrum_number,0:m-1]=x
       Gaussfits_y[Analyser_Result,spectrum_number,0:m-1]=yfit

       DataArray_Zint[Analyser_Result,spectrum_number]=coeff[0]

       deviation=abs(PeakPosition-coeff[1])
       maxdeviation=abs(PeakPosition-0.0)
       intfactor=1-(deviation/maxdeviation)
       DataArray_ZPeak[Analyser_Result,spectrum_number]=intfactor

       GaussParameters[Analyser_Result,spectrum_number,*]=coeff
       widget_control,(*pstate_mabc).A0_field,set_value = string(coeff[0])
       widget_control,(*pstate_mabc).A1_field,set_value = string(coeff[1])
       widget_control,(*pstate_mabc).A2_field,set_value = string(coeff[2])
       widget_control,(*pstate_mabc).A3_field,set_value = string(coeff[3])
       widget_control,(*pstate_mabc).A4_field,set_value = string(coeff[4])
       widget_control,(*pstate_mabc).A5_field,set_value = string(coeff[5])

    endif
endif else begin
DataArray_Zint[Analyser_Result,spectrum_number]=totaly
endelse

;
*(*pState_mabc).Gaussfits_x=Gaussfits_x
*(*pState_mabc).Gaussfits_y=Gaussfits_y
*(*pState_mabc).GaussParameters=GaussParameters
*(*pState_mabc).DataArray_Zint=DataArray_Zint
*(*pState_mabc).DataArray_ZPeak=DataArray_ZPeak

 ; oplot,x,yfit,linestyle = 2, thick = 2.0, psym=0, symsize=1.0,color=6
 mabcPlot_raw,event
IF DataType EQ 0 THEN BEGIN
MABCGauss1D_Plot,event
ENDIF ELSE BEGIN
MABC_ContourDisplay,event
MABCCross_Plot,event
ENDELSE
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Fit_Mode,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Fit_Modes,get_value=FitMode
if FitMode eq 0 then begin
widget_control,(*pstate_mabc).base_raw_la,sensitive = 0
widget_control,(*pstate_mabc).base_raw_lb,sensitive = 0
endif else begin
widget_control,(*pstate_mabc).base_raw_la,sensitive = 1
widget_control,(*pstate_mabc).base_raw_lb,sensitive = 1
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro CrossFit_Mode,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).CrossFit_Modes,get_value=Cross
if Cross eq 0 then begin
widget_control,(*pstate_mabc).base_cross_la,sensitive = 0
widget_control,(*pstate_mabc).base_cross_lb,sensitive = 0
endif else begin
widget_control,(*pstate_mabc).base_cross_la,sensitive = 1
widget_control,(*pstate_mabc).base_cross_lb,sensitive = 1
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Gauss1DFit_Mode,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Gauss1DFit_Modes,get_value=Gauss1D
if Gauss1D eq 0 then begin
widget_control,(*pstate_mabc).base_Gauss1D_la,sensitive = 0
widget_control,(*pstate_mabc).base_Gauss1D_lb,sensitive = 0
endif else begin
widget_control,(*pstate_mabc).base_Gauss1D_la,sensitive = 1
widget_control,(*pstate_mabc).base_Gauss1D_lb,sensitive = 1
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro AnalyserResult,event
widget_control,event.top,get_uvalue = pState_mabc
DataType=(*pState_mabc).DataType
 mabcPlot_raw,event
IF DataType EQ 0 THEN BEGIN
MABCGauss1D_Plot,event
ENDIF ELSE BEGIN
MABC_ContourDisplay,event
MABCCross_Plot,event
ENDELSE
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Cross_Clear,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pstate_mabc).Plot_cross,get_value = Plot_cross
widget_control,(*pstate_mabc).CrossValue_Field,get_value = CrossValue
CrossValue=float(CrossValue[0])
widget_control,(*pState_mabc).display,get_value=display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pState_mabc).CrossFit_Modes,get_value=CrossFit_Modes
GaussCrossY=*(*pState_mabc).GaussCrossY ;fltarr(10,2,2,N_XCoords,N_YCoords)
GaussCrossX=*(*pState_mabc).GaussCrossX ;fltarr(10,2,2,N_XCoords,N_YCoords)
GaussCrossParameters=*(*pState_mabc).GaussCrossParameters; fltarr(10,2,(N_XCoords+N_YCoords),6)
XCoords=*(*pState_mabc).XCoords
YCoords=*(*pState_mabc).YCoords
N_XCoords=n_elements(XCoords)
N_YCoords=n_elements(YCoords)
;
if Plot_cross eq 0 then begin
index=(where(CrossValue eq XCoords))[0]
GaussCrossY[Analyser_Result,display,Plot_cross,index,*]=0.0
GaussCrossX[Analyser_Result,display,Plot_cross,index,*]=0.0
GaussCrossParameters[Analyser_Result,display,index,*]=0.0
endif else begin
index=(where(CrossValue eq YCoords))[0]
GaussCrossY[Analyser_Result,display,Plot_cross,*,index]=0.0
GaussCrossX[Analyser_Result,display,Plot_cross,*,index]=0.0
GaussCrossParameters[Analyser_Result,display,index+N_XCoords,*]=0.0
endelse

*(*pState_mabc).GaussCrossParameters=GaussCrossParameters
*(*pState_mabc).GaussCrossX=GaussCrossX
*(*pState_mabc).GaussCrossY=GaussCrossY
MABCCross_Plot,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Cross_Fit,event

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    !ERROR_STATE.MSG)
return
endif


widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pstate_mabc).Plot_cross,get_value = Plot_cross
widget_control,(*pstate_mabc).CrossValue_Field,get_value = CrossValue
CrossValue=float(CrossValue[0])
widget_control,(*pState_mabc).display,get_value=display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pState_mabc).CrossFit_Modes,get_value=CrossFit_Modes
widget_control,(*pState_mabc).nterms_cross,get_value=nterms

GaussCrossY=*(*pState_mabc).GaussCrossY ;fltarr(10,2,2,N_XCoords,N_YCoords)
GaussCrossX=*(*pState_mabc).GaussCrossX ;fltarr(10,2,2,N_XCoords,N_YCoords)
GaussCrossParameters=*(*pState_mabc).GaussCrossParameters; fltarr(10,2,(N_XCoords+N_YCoords),6)

XCoords=*(*pState_mabc).XCoords
YCoords=*(*pState_mabc).YCoords
N_XCoords=n_elements(XCoords)
N_YCoords=n_elements(YCoords)
if display eq 0 then begin
DataArray_z=*(*pState_mabc).DataArray_Zint
endif else begin
DataArray_z=*(*pState_mabc). DataArray_ZPeak
endelse

z=fltarr(N_XCoords,N_YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
k=0
xindex=0
xindex=0
for xindex=0,N_XCoords-1 do begin
    for yindex=0,N_YCoords-1 do begin
    z[xindex,yindex]=DataArray_z[Analyser_Result,k]
    k+=1
    endfor
endfor
;
if Plot_cross eq 0 then begin
index=(where(CrossValue eq XCoords))[0]
y=z[index,*]
x=YCoords
endif else begin
index=(where(CrossValue eq YCoords))[0]
y=z[*,index]
x=XCoords
endelse



;get gauss fit parameters

widget_control,(*pstate_mabc).A0_field_cross,get_value = A0
A0=float(A0[0])
widget_control,(*pstate_mabc).A1_field_cross,get_value = A1
A1=float(A1[0])
widget_control,(*pstate_mabc).A2_field_cross,get_value = A2
A2=float(A2[0])
widget_control,(*pstate_mabc).A3_field_cross,get_value = A3
A3=float(A3[0])
widget_control,(*pstate_mabc).A4_field_cross,get_value = A4
A4=float(A4[0])
widget_control,(*pstate_mabc).A5_field_cross,get_value = A5
A5=float(A5[0])
;
widget_control,(*pstate_mabc).xmin_field_cross,get_value = xmin
xmin=float(xmin[0])
widget_control,(*pstate_mabc).xmax_field_cross,get_value = xmax
xmax=float(xmax[0])

;print, 'FitMode: ', FitMode
;let us do the fit
;
;help,y
y=float(y)
;help,y
;print,'y: ',y
if CrossFit_Modes eq 0 then begin
A0=max(y)
A0=float(A0)
A1=(x[where(y eq A0)])[0]
A2=((max(x)-min(x))/12.0)
A3=0.0
A4=0.0
A5=0.0
endif else begin
wheregt=where(x gt xmin,count)
if count ne 0 then begin
x=x[wheregt]
y=y[wheregt]
endif
wherelt=where(x lt xmax,count)
if count ne 0 then begin
x=x[wherelt]
y=y[wherelt]
endif
endelse
wherenezero=where(y ne 0.0,count)
if count ne 0 then begin
y=y[wherenezero]
x=x[wherenezero]
endif


if nterms eq 6 then estimates=[A0,A1,A2,A3,A4,A5]
if nterms eq 5 then estimates=[A0,A1,A2,A3,A4]
if nterms eq 4 then estimates=[A0,A1,A2,A3]
if nterms eq 3 then estimates=[A0,A1,A2]
yfit=gaussfit(x,y,coeff,estimates=estimates,nterms=nterms)
if nterms eq 5 then coeff=[coeff,0.0]
if nterms eq 4 then coeff=[coeff,0.0,0.0]
if nterms eq 3 then coeff=[coeff,0.0,0.0,0.0]

;print,'yfit_from function: ',yfit
if Plot_cross eq 0 then begin
;print,'01GaussCrossY[0,0,0,0,*]: ',reform(GaussCrossY[0,0,0,0,*])
GaussCrossY[Analyser_Result,display,Plot_cross,index,0:((n_elements(yfit)-1))]=yfit
GaussCrossX[Analyser_Result,display,Plot_cross,index,0:((n_elements(x)-1))]=x
ParameterIndex=index
endif else begin
GaussCrossY[Analyser_Result,display,Plot_cross,0:((n_elements(yfit)-1)),index]=yfit
GaussCrossX[Analyser_Result,display,Plot_cross,0:((n_elements(x)-1)),index]=x
ParameterIndex=index+N_XCoords
endelse
GaussCrossParameters[Analyser_Result,display,ParameterIndex,*]=coeff

widget_control,(*pstate_mabc).A0_field_cross,set_value = string(coeff[0])
widget_control,(*pstate_mabc).A1_field_cross,set_value = string(coeff[1])
widget_control,(*pstate_mabc).A2_field_cross,set_value = string(coeff[2])
widget_control,(*pstate_mabc).A3_field_cross,set_value = string(coeff[3])
widget_control,(*pstate_mabc).A4_field_cross,set_value = string(coeff[4])
widget_control,(*pstate_mabc).A5_field_cross,set_value = string(coeff[5])

*(*pState_mabc).GaussCrossParameters=GaussCrossParameters

*(*pState_mabc).GaussCrossX=GaussCrossX

*(*pState_mabc).GaussCrossY=GaussCrossY

MABCCross_Plot,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro CrossSliderValue,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pstate_mabc).CrossSlider,get_value = slider
widget_control,(*pstate_mabc).Plot_cross,get_value = Plot_cross

XCoords=*(*pState_mabc).XCoords
YCoords=*(*pState_mabc).YCoords
nx=n_elements(XCoords)
ny=n_elements(YCoords)

IF Plot_cross eq 0 then begin
range=XCoords[nx-1]-XCoords[0]
step=range/99.0
barvalue=XCoords[0]+step*(slider-1)
difference=abs(XCoords-barvalue)
mindiff=min(difference)
wheremindiff=where(mindiff eq difference,count)
if count eq 0 then begin
widget_control,(*pstate_mabc).CrossSlider,set_value = 1
return
endif
closestvalue=XCoords[wheremindiff[0]]
ENDIF ELSE BEGIN
range=YCoords[ny-1]-YCoords[0]
step=range/99.0
barvalue=YCoords[0]+step*(slider-1)
difference=abs(YCoords-barvalue)
mindiff=min(difference)
wheremindiff=where(mindiff eq difference,count)
if count eq 0 then begin
widget_control,(*pstate_mabc).CrossSlider,set_value = 1
return
endif
closestvalue=YCoords[wheremindiff[0]]
ENDELSE
widget_control,(*pstate_mabc).CrossValue_Field,set_value = closestvalue
MABCCross_Plot,event
end;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro RawSliderValue,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pstate_mabc).win_raw_Slider,get_value = slider
DataType=(*pState_mabc).DataType

XCoords=*(*pState_mabc).XCoords
nx=n_elements(XCoords)
IF DATATYPE EQ 0 THEN BEGIN
ntotal=nx
ENDIF ELSE BEGIN
YCoords=*(*pState_mabc).YCoords
ny=n_elements(YCoords)
ntotal=nx*ny
ENDELSE
step=ntotal/999.0
barvalue=1+step*(slider-1)
values=indgen(ntotal)+1
difference=abs(values-barvalue)
mindiff=min(difference)
wheremindiff=where(mindiff eq difference,count)
if count eq 0 then begin
widget_control,(*pstate_mabc).win_raw_Slider,set_value = 1
widget_control,(*pstate_mabc).raw_SliderValue,set_value = 1
return
endif
closestvalue=values[wheremindiff[0]]

widget_control,(*pstate_mabc).raw_SliderValue,set_value = closestvalue
mabcPlot_raw,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TabSet,event
widget_control,event.top,get_uvalue = pState_mabc
current=widget_info((*pState_mabc).base_gauss2D,/TAB_CURRENT)
;print,current
DataType=(*pState_mabc).DataType


if (DataType eq 0) and (current ne 0) then begin
widget_control,(*pState_mabc).base_gauss2D,SET_TAB_CURRENT = 0
endif

if (DataType eq 1) and (current eq 0) then begin
widget_control,(*pState_mabc).base_gauss2D,SET_TAB_CURRENT = 1
endif



end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Gauss1D_Fit,event

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    !ERROR_STATE.MSG)
return
endif

widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).nterms_gauss1d,get_value=nterms
widget_control,(*pState_mabc).gauss1d_display,get_value=gauss1d_display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pState_mabc).gauss1dFit_Modes,get_value=gauss1dFit_Modes

Gaussgauss1dX=*(*pState_mabc).Gaussgauss1dX ;fltarr(10,2,N_XCoords)
Gaussgauss1dY=*(*pState_mabc).Gaussgauss1dY ;fltarr(10,2,N_XCoords)
Gaussgauss1dParameters=*(*pState_mabc).Gaussgauss1dParameters; fltarr(10,2,6)

x=*(*pState_mabc).XCoords
if Gauss1D_display eq 0 then begin
DataArray_z=*(*pState_mabc).DataArray_Zint
endif else begin
DataArray_z=*(*pState_mabc). DataArray_ZPeak
endelse
y=DataArray_z[Analyser_Result,*]
;



;get gauss fit parameters

widget_control,(*pstate_mabc).A0_field_gauss1d,get_value = A0
A0=float(A0[0])
widget_control,(*pstate_mabc).A1_field_gauss1d,get_value = A1
A1=float(A1[0])
widget_control,(*pstate_mabc).A2_field_gauss1d,get_value = A2
A2=float(A2[0])
widget_control,(*pstate_mabc).A3_field_gauss1d,get_value = A3
A3=float(A3[0])
widget_control,(*pstate_mabc).A4_field_gauss1d,get_value = A4
A4=float(A4[0])
widget_control,(*pstate_mabc).A5_field_gauss1d,get_value = A5
A5=float(A5[0])
;
widget_control,(*pstate_mabc).xmin_field_gauss1d,get_value = xmin
xmin=float(xmin[0])
widget_control,(*pstate_mabc).xmax_field_gauss1d,get_value = xmax
xmax=float(xmax[0])

;print, 'FitMode: ', FitMode
;let us do the fit
;
;help,y
y=float(y)
;help,y
;print,'y: ',y
if gauss1dFit_Modes eq 0 then begin
A0=max(y)
A0=float(A0)
A1=(x[where(y eq A0)])[0]
A2=((max(x)-min(x))/12.0)
A3=0.0
A4=0.0
A5=0.0
endif else begin
wheregt=where(x gt xmin,count)
if count ne 0 then begin
x=x[wheregt]
y=y[wheregt]
endif
wherelt=where(x lt xmax,count)
if count ne 0 then begin
x=x[wherelt]
y=y[wherelt]
endif
endelse
wherenezero=where(y ne 0.0,count)
if count ne 0 then begin
y=y[wherenezero]
x=x[wherenezero]
endif


if nterms eq 6 then estimates=[A0,A1,A2,A3,A4,A5]
if nterms eq 5 then estimates=[A0,A1,A2,A3,A4]
if nterms eq 4 then estimates=[A0,A1,A2,A3]
if nterms eq 3 then estimates=[A0,A1,A2]
yfit=gaussfit(x,y,coeff,estimates=estimates,nterms=nterms)
if nterms eq 5 then coeff=[coeff,0.0]
if nterms eq 4 then coeff=[coeff,0.0,0.0]
if nterms eq 3 then coeff=[coeff,0.0,0.0,0.0]


Gaussgauss1dY[Analyser_Result,gauss1d_display,0:((n_elements(yfit)-1))]=yfit
Gaussgauss1dX[Analyser_Result,gauss1d_display,0:((n_elements(x)-1))]=x

Gaussgauss1dParameters[Analyser_Result,gauss1d_display,*]=coeff

widget_control,(*pstate_mabc).A0_field_gauss1d,set_value = string(coeff[0])
widget_control,(*pstate_mabc).A1_field_gauss1d,set_value = string(coeff[1])
widget_control,(*pstate_mabc).A2_field_gauss1d,set_value = string(coeff[2])
widget_control,(*pstate_mabc).A3_field_gauss1d,set_value = string(coeff[3])
widget_control,(*pstate_mabc).A4_field_gauss1d,set_value = string(coeff[4])
widget_control,(*pstate_mabc).A5_field_gauss1d,set_value = string(coeff[5])

*(*pState_mabc).Gaussgauss1dParameters=Gaussgauss1dParameters

*(*pState_mabc).Gaussgauss1dX=Gaussgauss1dX
*(*pState_mabc).Gaussgauss1dY=Gaussgauss1dY

MABCgauss1d_Plot,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Gauss1D_Clear,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Gauss1D_display,get_value=Gauss1D_display
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pState_mabc).gauss1dFit_Modes,get_value=gauss1dFit_Modes
Gaussgauss1dY=*(*pState_mabc).Gaussgauss1dY ;fltarr(10,2,N_XCoords)
Gaussgauss1dX=*(*pState_mabc).Gaussgauss1dX ;fltarr(10,2,N_XCoords)
Gaussgauss1dParameters=*(*pState_mabc).Gaussgauss1dParameters; fltarr(10,2,6)
XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(XCoords)
;
Gaussgauss1dY[Analyser_Result,Gauss1D_display,*]=0.0
Gaussgauss1dX[Analyser_Result,Gauss1D_display,*]=0.0
Gaussgauss1dParameters[Analyser_Result,Gauss1D_display,*]=0.0

*(*pState_mabc).Gaussgauss1dParameters=Gaussgauss1dParameters
*(*pState_mabc).Gaussgauss1dX=Gaussgauss1dX
*(*pState_mabc).Gaussgauss1dY=Gaussgauss1dY
MABCgauss1d_Plot,event


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Save_Contour_Image,event
widget_control,event.top,get_uvalue = pState_mabc
workDir=(*pState_mabc).workDir

MABC_ContourDisplay,event


device, decomposed = 1
image24 = tvrd(True=1)
device, decomposed = 0

;image24=reverse(image24,3)
    ok = dialog_write_image(image24, path = workDir,type='jpeg',/fix_type,dialog_parent=event.top)

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Save_Raw_Data,event,automatic=automatic
widget_control,event.top,get_uvalue = pState_mabc
XCoords=*(*pState_mabc).XCoords
totalruns=(*pState_mabc).totalruns
DataType=(*pState_mabc).DataType
DataPoints=(*pState_mabc).DataPoints
DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
Scan_Input=(*pState_mabc).Scan_Input
TimeBinIndices=(*pState_mabc).TimeBinIndices
widget_control,(*pState_mabc).mica,get_value =mica
widget_control, (*pState_mabc).Monitor_counts,get_value=Monitor_counts
widget_control, (*pState_mabc).Scan_Type_Select,get_value=Scan_Type_Select
widget_control, (*pState_mabc).Em,get_value=Em
widget_control, (*pState_mabc).TimeBinNumber,get_value=TimeBinNumber
widget_control, (*pState_mabc).win_raw_Slider,get_value=win_raw_Slider
widget_control, (*pState_mabc).View,get_value=View
widget_control, (*pState_mabc).Time_Window,get_value=Time_Window
widget_control, (*pState_mabc).Master,get_value=Master
widget_control, (*pState_mabc).Energy_Window_Slider,get_value=Energy_Window_Slider
theta_index=widget_info((*pState_mabc).analyser_angle_droplist,/droplist_select)


;
if DataType eq 1 then begin
YCoords=*(*pState_mabc).YCoords
endif else begin
YCoords=0.0
endelse
SaveParametersArray={XCoords:XCoords, $
               totalruns:totalruns, $
               DataType:DataType, $
               DataPoints:DataPoints, $
               DataArray_x:DataArray_x, $
               DataArray_y:DataArray_y, $
               Scan_Input:Scan_Input, $
               Monitor_counts:Monitor_counts, $
               TimeBinIndices:TimeBinIndices, $
               mica:mica, $
               Scan_Type_Select:Scan_Type_Select, $
               Em:Em, $
               TimeBinNumber:TimeBinNumber, $
               win_raw_Slider:win_raw_Slider, $
               View:View, $
               Time_Window:Time_Window, $
               Master:Master, $
               theta_index:theta_index, $
               Energy_Window_Slider:Energy_Window_Slider, $
               YCoords:YCoords}




workDir=(*pState_mabc).workDir

TimeStamp=systime()
StringParts=strsplit(TimeStamp,/extract)
n=n_elements(StringParts)
TimeStamp=StringParts[0]+'_'
for i = 1, n-2 do begin
TimeStamp+=StringParts[i]+'_'
endfor
TimeStamp+=StringParts[n-1]
StringParts=strsplit(TimeStamp,':',/extract)
n=n_elements(StringParts)
TimeStamp=StringParts[0]+'%'
for i = 1, n-2 do begin
TimeStamp+=StringParts[i]+'%'
endfor
TimeStamp+=StringParts[n-1]
;

file_name='Triffid_rawdata'+'_'+TimeStamp+'.dat'
help,automatic
if n_elements(automatic) eq 0 then begin
    filename=dialog_pickfile(path=workDir,$
      file=file_name,/write,filter="*.dat",/fix_filter)
endif else begin
filename=workDir+file_name
endelse

if n_elements(filename) eq 0 then return
if filename eq '' then return


save, filename=filename, SaveParametersArray

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Load_Raw_Data,event
widget_control,event.top,get_uvalue = pState_mabc
;
workDir=(*pState_mabc).workDir
    filename=dialog_pickfile(path=workDir,$
      file='Triffid_rawdata.data',/read,filter="*.dat",/fix_filter)
if n_elements(filename) eq 0 then return
if filename eq '' then return
;file='MEP_restore'
restore,filename=filename
;
XCoords=SaveParametersArray.XCoords
totalruns=SaveParametersArray.totalruns
DataType=SaveParametersArray.DataType
DataPoints=SaveParametersArray.DataPoints
DataArray_x=SaveParametersArray.DataArray_x
DataArray_y=SaveParametersArray.DataArray_y
Scan_Input=SaveParametersArray.Scan_Input
Monitor_counts=SaveParametersArray.Monitor_counts
TimeBinIndices=SaveParametersArray.TimeBinIndices
mica=SaveParametersArray.mica
YCoords=SaveParametersArray.YCoords
Scan_Type_Select=SaveParametersArray.Scan_Type_Select
Em=SaveParametersArray.Em
TimeBinNumber=SaveParametersArray.TimeBinNumber
win_raw_Slider=SaveParametersArray.win_raw_Slider
View=SaveParametersArray.View
Time_Window=SaveParametersArray.Time_Window
Master=SaveParametersArray.Master
theta_index=SaveParametersArray.theta_index
;
;
;
;
;
;
widget_control, (*pState_mabc).Monitor_counts,set_value=Monitor_counts
widget_control, (*pState_mabc).Scan_Type_Select,set_value=Scan_Type_Select
widget_control, (*pState_mabc).Em,set_value=Em
widget_control, (*pState_mabc).TimeBinNumber,set_value=TimeBinNumber
widget_control, (*pState_mabc).win_raw_Slider,set_value=win_raw_Slider
widget_control, (*pState_mabc).View,set_value=View
widget_control, (*pState_mabc).Time_Window,set_value=Time_Window
widget_control, (*pState_mabc).Master,set_value=Master
widget_control, (*pState_mabc).analyser_angle_droplist,set_droplist_select=theta_index

;print,tag_names(SaveParametersArray)
woof=strpos(tag_names(SaveParametersArray),'ENERGY_WINDOW_SLIDER')
;print,'woof: ',woof
wherezero=where(woof eq 0,count)
if count ne 0 then begin
Energy_Window_Slider=SaveParametersArray.Energy_Window_Slider
widget_control, (*pState_mabc).Energy_Window_Slider,set_value=Energy_Window_Slider
endif
;



*(*pState_mabc).XCoords=XCoords
(*pState_mabc).totalruns=totalruns
(*pState_mabc).DataType=DataType
(*pState_mabc).DataPoints=DataPoints
*(*pState_mabc).DataArray_x=DataArray_x
*(*pState_mabc).DataArray_y=DataArray_y
(*pState_mabc).Scan_Input=Scan_Input
*(*pState_mabc).YCoords=YCoords
(*pState_mabc).TimeBinIndices=TimeBinIndices
widget_control, (*pState_mabc).Scan_Table,set_value=Scan_Input
widget_control,(*pState_mabc).mica,set_value =mica


MABC_Define_Arrays,event
MABCChopperPhases,event

(*pState_mabc).Xvariable=Scan_Input[0,0]
if (*pState_mabc).datatype eq 1 then (*pState_mabc).Yvariable=Scan_Input[1,0]

help,DataArray_x
(*pstate_mabc).loaded_mabc = 1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SaveAscii,event
widget_control,event.top,get_uvalue = pState_mabc
widget_control,(*pState_mabc).Analyser_Result,get_value=Analyser_Result
widget_control,(*pstate_mabc).raw_SliderValue,get_value = spectrum_number
spectrum_number=fix(spectrum_number[0])
spectrum_number-=1
GaussParameters=*(*pState_mabc).GaussParameters  ; fltarr(10,n_TotalSpectra,6)
DataType=(*pState_mabc).DataType

IF DataType EQ 0 THEN BEGIN
DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
XCoords=*(*pState_mabc).XCoords
N_XCoords=n_elements(XCoords)
n_TotalSpectra=N_XCoords
x=DataArray_x[Analyser_Result,spectrum_number,*]
y=DataArray_y[Analyser_Result,spectrum_number,*]

ENDIF ELSE BEGIN

DataArray_x=*(*pState_mabc).DataArray_x
DataArray_y=*(*pState_mabc).DataArray_y
XCoords=*(*pState_mabc).XCoords
YCoords=*(*pState_mabc).YCoords
N_XCoords=n_elements(XCoords)
N_YCoords=n_elements(YCoords)
n_TotalSpectra=N_XCoords*N_YCoords
;print,n_TotalSpectra

;print,'spectrum_number: ',spectrum_number
xnum=spectrum_number/N_YCoords
ynum=spectrum_number-xnum*N_YCoords
;
;help,DataArray_x
;print,'xnum: ',xnum
;print,'ynum: ',ynum
;print,''

x=DataArray_x[Analyser_Result,xnum,ynum,*]
y=DataArray_y[Analyser_Result,xnum,ynum,*]
ENDELSE

widget_control,(*pstate_mabc).RawAsciiName,get_value = RawAsciiName

if RawAsciiName ne '' then begin
workDir=(*pState_mabc).workDir
FileName=workDir+RawAsciiName
openw,lun,filename,/get_lun
for i = 0, n_elements(x)-1 do begin
printf,lun,x[i],y[i]
endfor
free_lun,lun,/force
endif



end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABCEvents,event
widget_control,event.top,get_uvalue = pState_mabc

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    !ERROR_STATE.MSG)
return
endif
;
  IF (TAG_NAMES(event, /STRUCTURE_NAME) EQ 'WIDGET_TIMER') THEN BEGIN
;  print,'TIMER'
response=MABC_ProbeRunstatus(event)
if response eq 1 then begin
StoreData,event
    if (*pState_mabc).terminate eq 0 then begin
    ExecuteRun,event
    endif else begin
    MABC_TimeBinCull,event
    MABC_Define_Arrays,event
    Save_Raw_Data,event,/automatic
    return
    endelse
endif else begin
WIDGET_CONTROL, event.TOP, TIMER=10
return
endelse

  ENDIF
Scan_Input=(*pState_mabc).Scan_Input
Scan_Table=(*pState_mabc).Scan_Table
uname=widget_info(event.id,/uname)
case uname of
'chopper':    $
begin
MABCChopperPhases,event
end
'view':    $
begin
MABCChopperPhases,event
end
'Time_Window':    $
begin
MABCChopperPhases,event
end
'DoNothing':    $
begin
end
'STV_AF':    $
begin
cells= widget_info(Scan_Table,/table_select)
widget_control, Scan_Table,get_value=Scan_Input
Scan_Input[cells[0],0]='AF'
widget_control, Scan_Table,set_value=Scan_Input
(*pState_mabc).Scan_Input=Scan_Input
end
'STV_AL':    $
begin
widget_control, Scan_Table,get_value=Scan_Input
cells= widget_info(Scan_Table,/table_select)
Scan_Input[cells[0],0]='AL'
widget_control, Scan_Table,set_value=Scan_Input
(*pState_mabc).Scan_Input=Scan_Input
end
'STV_AS':    $
begin
widget_control, Scan_Table,get_value=Scan_Input
cells= widget_info(Scan_Table,/table_select)
Scan_Input[cells[0],0]='AS'
widget_control, Scan_Table,set_value=Scan_Input
(*pState_mabc).Scan_Input=Scan_Input
end
'STV_DL':    $
begin
cells= widget_info(Scan_Table,/table_select)
widget_control, Scan_Table,get_value=Scan_Input
Scan_Input[cells[0],0]='DL'
widget_control, Scan_Table,set_value=Scan_Input
(*pState_mabc).Scan_Input=Scan_Input
end
'STV_DS':    $
begin
widget_control, Scan_Table,get_value=Scan_Input
cells= widget_info(Scan_Table,/table_select)
Scan_Input[cells[0],0]='DS'
widget_control, Scan_Table,set_value=Scan_Input
(*pState_mabc).Scan_Input=Scan_Input
end
'STV_DR':    $
begin
widget_control, Scan_Table,get_value=Scan_Input
cells= widget_info(Scan_Table,/table_select)
Scan_Input[cells[0],0]='DR'
widget_control, Scan_Table,set_value=Scan_Input
(*pState_mabc).Scan_Input=Scan_Input
end
'ScanValues':    $
begin
widget_control, Scan_Table,get_value=Scan_Input
(*pState_mabc).Scan_Input=Scan_Input
end
'BeginRun' :    $
begin
IF (*pstate_mabc).demo_mabc eq 0 then begin
OK=MABC_InitialiseRun(event)
if OK eq 1 then ExecuteRun,event
endif else begin
MABC_Demo_Data,event
MABC_Define_Arrays,event
endelse
end
'Display' :    $
begin
MABC_ContourDisplay,event
MABCCross_Plot,event
end
'Analyser_Result' :    $
begin
AnalyserResult,event
end
'ColourGradient' :    $
begin
MABC_ContourDisplay,event,/no_fit
end
'LoadAnalyserTable' :    $
begin
LoadAnalyserTable,event
end
'Connect':   $
begin
Connect_mabc,event
end
'Send_Parameters':   $
begin
SendParameters,event
end
'Send_ChopperParameters':   $
begin
SendChopperParameters,event
end
'Send_TriffidParameters':   $
begin
SendTriffidParameters,event
end
'Send_AareTriffidParameters':   $
begin
SendAareTriffidParameters,event
end
'Send_BergTriffidParameters':   $
begin
SendBergTriffidParameters,event
end
'Send_HistogramParameters':   $
begin
SendHistogramParameters,event
end
'analyser_angle':   $
begin
AnalyserAngle,event
end
'Scan_Type':   $
begin
ScanType,event
end
'RawSpectrumSelect':   $
begin
RawSliderValue,event
end
'FitCurrent':   $
begin
Fit_Current,event
end
'FitAll':   $
begin
Fit_All,event
end
'FitCurrentCount':   $
begin
Fit_Current,event,/sumcount
end
'FitAllCount':   $
begin
Fit_All,event,/sumcount
end
'FitMode':   $
begin
Fit_Mode,event
end
'DeleteCurrent':   $
begin
Delete_Current,event
end
'DeleteAll':   $
begin
Delete_All,event
end
'Cross_SliderValue':   $
begin
CrossSliderValue,event
end
'CrossPlot':   $
begin
CrossSliderValue,event
MABCCross_Plot,event
end
'CrossFit':   $
begin
Cross_Fit,event
end
'CrossClear':   $
begin
Cross_Clear,event
end
'CrossFitMode':   $
begin
CrossFit_Mode,event
end
'Gauss1DFitMode':   $
begin
Gauss1DFit_Mode,event
end
'Tab_Set':   $
begin
TabSet,event
end
'Gauss1D_Display':   $
begin
MABCGauss1D_Plot,event
end
'Gauss1DFit':   $
begin
Gauss1D_Fit,event
end
'Gauss1DClear':   $
begin
Gauss1D_Clear,event
end
'Gauss1DToTables' :    $
begin
type=0
UpdateAnalyserTable,event,type
end
'ContourToTables' :    $
begin
type=1
UpdateAnalyserTable,event,type
end
'CrossToTables' :    $
begin
type=2
UpdateAnalyserTable,event,type
end
'ContourFittypes' :    $
begin
MABC_ContourDisplay,event
end
'ContourFittypes' :    $
begin
MABC_ContourDisplay,event
end
'SaveRawData' :    $
begin
Save_Raw_Data,event
end
'LoadRawData' :    $
begin
Load_Raw_Data,event
end
'SaveContourImage' :    $
begin
Save_Contour_Image,event
end
'SaveAscii' :    $
begin
SaveAscii,event
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MABC, group_leader = group_leader,notify_ids = notify_ids,  $
        register_name = register_name,workDir = workDir

;print,'Register Name =',register_name
;;;;;;;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 = 'MABC'
if xregistered(register_name) then return
if n_elements(workDir) eq 0 then begin
workDir='C:\Documents and Settings\tregenna\My Documents\temp\dave\Working Data Directory\'
endif
device, get_decomposed = old_dc
device,decomposed = 0

;loadCT,0 ,/silent
loadCT,5,NColors=12,Bottom=1 ,/silent
delim=path_sep()
;TVSCL, DIST(400)
;define constants
;calculate dspacing

;read_jpeg,!DAVE_AUXILIARY_DIR+'PSI\MARS\koennecke_pic.jpg',koennecke_pic
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'AcceptableTimebins.txt'
TimeBins=GetMARSAcceptableTimebins(filename)
;
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MARS_TimeOffsets.txt'
timeoffsets=GetMARSTimeOffsets(filename)
;help,timeoffsets,/struc
if timeoffsets.filefound eq 0 then begin
msg=strarr(2)
msg[0]='The file '+filename
msg[1]='has not been found or the information in the file is invalid.  All time offsets will be set to zero.'
        void=dialog_message(dialog_parent=group_leader,/error,msg)
master1_timeoffset=0.0
master2_timeoffset=0.0
master3_timeoffset=0.0
master4_timeoffset=0.0
master5_timeoffset=0.0
master6_timeoffset=0.0
master7_timeoffset=0.0
timeoffsets={MARSTimeOffsets, $
              filefound:0, $
              master1_timeoffset:master1_timeoffset, $
              master2_timeoffset:master2_timeoffset, $
              master3_timeoffset:master3_timeoffset, $
              master4_timeoffset:master4_timeoffset, $
              master5_timeoffset:master5_timeoffset, $
              master6_timeoffset:master6_timeoffset, $
              master7_timeoffset:master7_timeoffset}
endif



read_jpeg,!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'koennecke_pic.jpg',koennecke_pic


;filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MARSConstants.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MARSConstants.txt'
constants=GetMARSConstants(filename)
if constants.filefound eq 0 then begin
        void=dialog_message(dialog_parent=group_leader,/error, $
    'The file '+filename+' has not been found.  The program must exit.')
return
endif
;
dspace_002=constants.dspace_002
dspace_array=[dspace_002,dspace_002/2,dspace_002/3,dspace_002/4]


;filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\Calibrated_Analyser_Angles.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'Calibrated_Analyser_Angles.txt'
;
line=''
Calibration_Angles_str=strarr(2,32)
openr,lun,filename,/get_lun
for i=0,31 do begin
readf,lun,line
temp=strsplit(line,/extract)
Calibration_Angles_str[0,i]=strtrim(temp[0],2)
Calibration_Angles_str[1,i]=strtrim(temp[1],2)
endfor
free_lun,lun,/force


;
tlb = widget_base(/col,group_leader = group_leader,title = 'MARS Analyser Banks Calibration',mbar=bar)
;
       filebuttons=widget_button(bar,value='File',/menu)
          Load_Analyser_Button=widget_button(filebuttons,$
              value='Load Analyser Positions From Triffid Tables',event_pro='LoadAnalyserTable')
          Create_Table_Button=widget_button(filebuttons,$
              value='Generate Triffid Tables',event_pro='CreateTriffidTable')
;              value='Generate Triffid Tables',event_pro='CreateTriffidTableMod')
          void=widget_button(filebuttons,$
              value='Save Triffid Table as IDL Binary',event_pro='SaveTriffidTable')
          void=widget_button(filebuttons,$
              value='Load Triffid Table IDL Binary File',event_pro='LoadTriffidTable')
          doneb=widget_button(filebuttons,$
              value='EXIT',event_pro='MABC_exit')

;CreateTriffidTableMod
;
opt_tab=widget_tab(tlb)

setup_base=widget_base(opt_tab,title='Set Up and Execution',/col)
Results_base=widget_base(opt_tab,/row,title='Results')

setup_base_upper=widget_base(setup_base,/row,/align_center)
setup_base_middle=widget_base(setup_base,/row,/align_center)
setup_base_lower=widget_base(setup_base,/row,/align_center)


;

baseu1=widget_base(setup_base_upper,/frame,/col,/align_center)
baseu1A=widget_base(baseu1,/row,/align_center)
Em = cw_field(baseu1A,/col,title = 'Calibrant Peak Position',value='0',/return_events,uname='chopper')
Master=widget_slider(baseu1A,$
              value=1,min=1,max=7,title='Master * 50Hz',xsize=70, $
              event_pro='MABCEvents',uname='chopper')


baseu1B=widget_base(baseu1,/row,/align_center)

analyser_angle_droplist=widget_Droplist(baseu1B,value=reform(Calibration_Angles_str[1,*]), $
              /dynamic_resize,uname='analyser_angle',title='Select Analyser Angle' )

widget_control,analyser_angle_droplist,set_droplist_select=31



Mica_Reflection = ['002',$
              '004', $
              '006', $
              '008']
Mica = cw_bgroup(baseu1,Mica_Reflection,/row,/exclusive,label_top='Mica Reflection', $
           set_value = 2,/return_index,/no_release,uname='chopper', /frame)



baseu2=widget_base(setup_base_upper,/col,/align_center)

column_labels=['Phase','Frequencies']
chopper_names=['Snail','Master','Rabbit','Chopper 4','Chopper 5']
output=strarr(2,5)
output[0,0]='172.89180'
output[0,1]='180.000'
output[0,2]='180.04944'
output[0,3]='202.443'
output[0,4]='308.430'
;
output[1,0]='50.0000'
output[1,1]='50.0000'
output[1,2]='50.0000'
output[1,3]='50.0000'
output[1,4]='50.0000'

void=widget_label(baseu2,value='CHOPPER VARIABLES')

Chopper_Table=widget_table(baseu2,column_widths=70,$
       column_labels=column_labels,row_labels=chopper_names,xsize=2,ysize=5,/editable, $
       value=output,uname='DoNothing',alignment=2)

Analyser_Energy_Field=cw_field(baseu2,/col,title='Analyser Energy',value='3.1812842',xsize=20,/noedit)


baseu3=widget_base(setup_base_upper,/col,/align_center)

ConnectButton = widget_button(baseu3,value = 'Connect to Instrument', uname='Connect')
ParameterChopperButton = widget_button(baseu3,value = 'Send Chopper Parameters to Instrument', uname='Send_ChopperParameters')
ParameterTriffidButton = widget_button(baseu3,value = 'Send Triffid Parameters to Instrument', uname='Send_TriffidParameters')
ParameterHistogramButton = widget_button(baseu3,value = 'Send Histogram Parameters to Instrument', uname='Send_HistogramParameters')
ParameterButton = widget_button(baseu3,value = 'Send All Parameters to Instrument', uname='Send_Parameters')

baseu4=widget_base(setup_base_upper,/col,/align_center)



BeginRunButton = widget_button(baseu4,value = 'Begin Calibration Run', uname='BeginRun')
;EndRunButton = widget_button(baseu4,value = 'End Calibration Run', uname='EndRun')
Monitor_counts=cw_field(baseu4,/col,title='Monitor Counts for Run Duration',value='1000000')


base_middle2=widget_base(setup_base_middle,/col,/align_center,/frame)

void=widget_label(base_middle2,value='Scan Parameters')

base_middle3=widget_base(base_middle2,/col,/align_center)


Scan_Type_Fields=['One','Two']
Scan_Type_Select = cw_bgroup(base_middle3,Scan_Type_Fields,/row,/exclusive,label_top = $
'Number of Variables',frame = 2,set_value = 0,/no_release, uname='Scan_Type')


Scan_Input=strarr(2,4)
Scan_Input[1,*]='-'

Scan_column_labels=['Abscissa','Ordinate']
Scan_row_labels=['Variable','Midpoint','Range','Num. of Points']

Scan_Table=widget_table(base_middle2,column_widths=70,$
       column_labels=Scan_column_labels,row_labels=Scan_row_labels,xsize=2,ysize=4,/editable, $
       value=Scan_Input,alignment=1,uname='ScanValues')

base_middle4=widget_base(base_middle2,/row,/align_center)

void = widget_button(base_middle4,value = 'AF', uname='STV_AF')
void = widget_button(base_middle4,value = 'AL', uname='STV_AL')
void = widget_button(base_middle4,value = 'AS', uname='STV_AS')
void = widget_button(base_middle4,value = 'DL', uname='STV_DL')
void = widget_button(base_middle4,value = 'DS', uname='STV_DS')
void = widget_button(base_middle4,value = 'DR', uname='STV_DR')


basem1=widget_base(setup_base_middle,/col,/align_center)


void=widget_label(basem1,value='TIME AND ENERGY WINDOWS')
;
tofl=54013.0
tofm=53190.736
tofu=52393.4
;
Ewinl=-0.103654
Ewinc=0.000000
Ewinu=0.105428
;
;
Ewinlabs=3.07763
Ewincabs=3.1812842
Ewinuabs=3.28671


tofoutput=strarr(3,3)
tofoutput[0,0]=tofl
tofoutput[0,1]=tofm
tofoutput[0,2]=tofu
;
tofoutput[1,0]=Ewinl
tofoutput[1,1]=Ewinc
tofoutput[1,2]=Ewinu
;
tofoutput[2,0]=Ewinlabs
tofoutput[2,1]=Ewincabs
tofoutput[2,2]=Ewinuabs

tofwindow_column_labels=['Triffid TOF us','Relative Energy','Absolute Energy']
tofwindow_row_labels=['Lower Energy','Set Point','Higher Energy']


tofwindow=widget_table(basem1,column_widths=90,$
       column_labels=tofwindow_column_labels,row_labels=tofwindow_row_labels,xsize=3,ysize=3, $
       value=tofoutput,alignment=2)

basem2=widget_base(basem1,/col,/align_center)



Time_Window_field = ['Restricted', $
              'Full']

Time_Window = cw_bgroup(basem2,Time_Window_field,/row,/exclusive,label_top='Chopper 4,5 Time Window', $
           set_value = 0,/return_index,/no_release, /frame,uname='Time_Window')


Energy_Window_Width=cw_field(basem2,/col,title='',value='0.20908192',xsize=20,/noedit)

Energy_Window_Slider=widget_slider(basem2,$
              value=1000,min=1,max=1000,xsize=150, $
              uname='chopper',/suppress_value,title='Width of Energy Window')



View_field = ['Narrow Time Window', $
              'Complete Spectrum']

View = cw_bgroup(basem2,View_field,/row,/exclusive,label_top='Inelastic Time Bin Indices', $
           set_value = 0,/return_index,/no_release, /frame,uname='view')



basel1=widget_base(setup_base_middle,/col,/frame,/align_center)
void=widget_label(basel1,value='Neutron Arrival Times')

First_Neutrons_Time=cw_field(basel1,/col,title='First Upstream Monitor',value='48227.323',xsize=20,/noedit)
End_Monitor_Time=cw_field(basel1,/col,title='Last Upstream Monitor',value='49838.593',xsize=20,/noedit)
First_PostMonitor_Time=cw_field(basel1,/col,title='First Downstream Monitor',value='49454.126',xsize=20,/noedit)
End_PostMonitor_Time=cw_field(basel1,/col,title='Last Downstream Monitor',value='51106.383',xsize=20,/noedit)
Last_Neutrons_Time=cw_field(basel1,/col,title='Last 002',value='61771.835',xsize=20,/noedit)
tofwindow_field=cw_field(basel1,/col,title='TOF Window',value='13544.511',xsize=20,/noedit)


basel2=widget_base(setup_base_middle,/col,/frame,/align_center)

void=widget_label(basel2,value='Histogram Memory')
TimeBinNumber=cw_field(basel2,/col,title='Number of INS Time Bins ',value='101',xsize=20,/return_events,uname='chopper')
TimeBinStart=cw_field(basel2,/col,title='Start of Time Bin',value='47582',xsize=20,/noedit)
TimeBinStep=cw_field(basel2,/col,title='Time Bin Step',value='16.0',xsize=20,/noedit)
TimeBinWidth=cw_field(basel2,/col,title='Time Bin Width',value='20000',xsize=20,/noedit)
TotalTimeBinNumber=cw_field(basel2,/col,title='Total Number of Time Bins',value='1250',xsize=20,/noedit)


base_upper1=widget_base(tlb,/row,/align_center)


base_upper1a=widget_base(base_upper1,/col,/align_center)

void=widget_label(base_upper1a,value='Aare Analysers')

Aare_column_labels=['MessPunkt','Angle','AF','AL','AS','DL','DS','DR']
Aare_row_labels=['150 deg.','120 deg.','90 deg.','60 deg.','30 deg.']

Aare_Table=strarr(8,5)
AareForegroundColors=intarr(3,40)

Aare_Triffid_Table=widget_table(base_upper1a,column_widths=60,value=Aare_Table, $
       column_labels=Aare_column_labels,row_labels=Aare_row_labels,xsize=8,ysize=5,/editable, $
       alignment=2)

base_upper1b=widget_base(base_upper1,/col,/align_center)

void=widget_label(base_upper1b,value='')

ParameterAareTriffidButton = widget_button(base_upper1b,value = 'Send Aare Triffid Parameters to Instrument', $
    uname='Send_AareTriffidParameters')
;void=widget_label(base_upper1b,value='')

base_middle1=widget_base(tlb,/row,/align_center)

base_middle1a=widget_base(base_middle1,/col,/align_center)


void=widget_label(base_middle1a,value='Berg Analysers')


Berg_column_labels=['MessPunkt','Angle','AF','AL','AS','DL','DS','DR']
Berg_row_labels=['30 deg.','60 deg.','90 deg.','120 deg.','150 deg.']

Berg_Table=strarr(8,5)
BergForegroundColors=intarr(3,40)

Berg_Triffid_Table=widget_table(base_middle1a,column_widths=60,value=Berg_Table, $
       column_labels=Berg_column_labels,row_labels=Berg_row_labels,xsize=8,ysize=5,/editable, $
       alignment=2)

base_middle1b=widget_base(base_middle1,/col,/align_center)



ParameterBergTriffidButton = widget_button(base_middle1b,value = 'Send Berg Triffid Parameters to Instrument', $
    uname='Send_BergTriffidParameters')

void=widget_label(base_middle1b,value='')

Results_basel=widget_base(Results_base,/col,/align_center)


RawAsciiName=cw_field(Results_basel,/col,title='Ascii Output File Name ',value='')
void = widget_button(Results_basel,value = 'Save Ascii', uname='SaveAscii')


Analyser_Result_Names = ['Aare 150 deg.','Aare 120 deg.','Aare 90 deg.','Aare 60 deg.','Aare 30 deg.', $
                 'Berg 30 deg.','Berg 60 deg.','Berg 90 deg.','Berg 120 deg.','Berg 150 deg.']

Analyser_Result = cw_bgroup(Results_basel,Analyser_Result_Names,col=1,/exclusive, $
         label_top = 'View Result for Analyser',$
            frame = 1,set_value = 0,/no_release,uname='Analyser_Result')


void = widget_button(Results_basel,value = 'Save Raw Data', uname='SaveRawData')
void = widget_button(Results_basel,value = 'Load Raw Data', uname='LoadRawData')



Results_base_data=widget_base(Results_base,/row,/align_center)


Results_base_left=widget_base(Results_base_data,/col,/align_center)
Results_base_right=widget_base(Results_base_data,/col,/align_center)


;opt_tab_res=widget_tab(Results_base_right)



base_raw=widget_base(Results_base_left,/col,title = 'Raw Data')


GoldenRatio=0.5*(1.0+sqrt(5.0))


;xsize = 400 & ysize = 300
xsize = 400 & ysize =xsize/GoldenRatio

base_raw_u=widget_base(base_raw,/col,/align_center)

win_raw = widget_draw(base_raw_u,xsize = xsize,ysize = ysize, $
       /button_events,event_pro = 'mabcdraw_raw')

base_raw_u5=widget_base(base_raw_u,/row,/align_center)

raw_SliderValue=cw_field(base_raw_u5,/row,title='',value='1',/noedit,xsize=8)


win_raw_Slider=widget_slider(base_raw_u,$
              value=1,min=1,max=1000, $
              uname='RawSpectrumSelect',title='Select Raw Spectrum',/suppress_value)


geom_raw = widget_info(base_raw_u,/geometry)
;newysize_raw = geom_raw.ysize
newysize_raw = ysize
widget_control,win_raw,draw_ysize = newysize_raw

base_raw_l=widget_base(base_raw,/col)
base_raw_lf=widget_base(base_raw_l,/row)
base_raw_lg=widget_base(base_raw_lf,/col)



void=widget_label(base_raw_lg,value='Estimate of Gaussian Fit Parameters')


GaussEquation = strarr(2)

GaussEquation[0]= 'z = (x - A1) / A2'
GaussEquation[1]= 'f(x) = A0 exp(-z^2/2) + A3 + A4 x + A5 x^2'

void = widget_text(base_raw_lg,value = GaussEquation,xsize = 34,ysize=2)

Mode_Types = ['Automatic',$
              'Manual']

Fit_Modes = cw_bgroup(base_raw_lf,Mode_Types,/col,/exclusive, $
           set_value = 0,/return_index,/no_release, /frame,uname='FitMode')


;base_raw_lf_col1=widget_base(base_raw_lf,/col)

;Sum_Types = ['Sum Counts']

;Sum_Modes = cw_bgroup(base_raw_lf_col1,Sum_Types,/col,/nonexclusive, $
;           set_value = 0,/return_index,/no_release,uname='FitMode')


nterms_raw=widget_slider(base_raw_lf, $
              value=6,min=3,max=6,xsize=60, $
              event_pro='MABCEvents',uname='nterms_raw_Slider',title = 'Num. of Terms')

;void = widget_text(base_raw_lh,value = 'Number of Terms')


base_raw_la=widget_base(base_raw_l,/row)
base_raw_lb=widget_base(base_raw_l,/row)


A0_field=cw_field(base_raw_la,/row,title='A0',value='',xsize=10)
A1_field=cw_field(base_raw_la,/row,title='A1',value='',xsize=10)
A2_field=cw_field(base_raw_la,/row,title='A2',value='',xsize=10)
xmin_field=cw_field(base_raw_la,/row,title='xmin',value='',xsize=10)
A3_field=cw_field(base_raw_lb,/row,title='A3',value='',xsize=10)
A4_field=cw_field(base_raw_lb,/row,title='A4',value='',xsize=10)
A5_field=cw_field(base_raw_lb,/row,title='A5',value='',xsize=10)
xmax_field=cw_field(base_raw_lb,/row,title='xmax',value='',xsize=10)

;widget_control,A1_field,set_value = '54944.560'
widget_control,base_raw_la,sensitive = 0
widget_control,base_raw_lb,sensitive = 0


base_raw_lc=widget_base(base_raw_l,/row)


Action_Types = ['Zoom',$
              'Set Parameters']

Mouse_Action = cw_bgroup(base_raw_lc,Action_Types,/col,/exclusive,label_top='Mouse Action', $
           set_value = 0,/return_index,/no_release, /frame)


base_raw_ld=widget_base(base_raw_lc,/col,/frame)

void=widget_label(base_raw_ld,value='Fit Data to Gaussian')

void = widget_button(base_raw_ld,value = 'Current', uname='FitCurrent')
void = widget_button(base_raw_ld,value = 'All', uname='FitAll')

base_raw_lf=widget_base(base_raw_lc,/col,/frame)

void=widget_label(base_raw_lf,value='Sum counts')

void = widget_button(base_raw_lf,value = 'Current', uname='FitCurrentCount')
void = widget_button(base_raw_lf,value = 'All', uname='FitAllCount')


base_raw_le=widget_base(base_raw_lc,/col,/frame)

void=widget_label(base_raw_le,value='Delete Fit(s)')

void = widget_button(base_raw_le,value = 'Current', uname='DeleteCurrent')
void = widget_button(base_raw_le,value = 'All', uname='DeleteAll')

xsize = 400 & ysize = 400

base_gauss2D=widget_tab(Results_base_right,uname='Tab_Set')

base_gauss1D=widget_base(base_gauss2D,/col,title = '1D Gauss Parameters')
base_gauss2DContour=widget_base(base_gauss2D,/col,title = 'Contour 2D Gauss Parameters')
base_gauss2DCross=widget_base(base_gauss2D,/col,title = 'Cross Section 2D Contour')


xsize = 400 & ysize =xsize/GoldenRatio

base_Gauss1D_u=widget_base(base_gauss1D,/col)

win_Gauss1D = widget_draw(base_Gauss1D_u,xsize = xsize,ysize = ysize, $
       /button_events,event_pro = 'MABCGauss1D_Draw')
geom_Gauss1D = widget_info(base_Gauss1D_u,/geometry)
;newysize_raw = geom_raw.ysize
newysize_Gauss1D = ysize
widget_control,win_Gauss1D,draw_ysize = newysize_Gauss1D

base_Gauss1D_l=widget_base(base_gauss1D,/col)
base_Gauss1D_lf=widget_base(base_Gauss1D_l,/row)
base_Gauss1D_lg=widget_base(base_Gauss1D_lf,/col)


void=widget_label(base_Gauss1D_lg,value='Estimate of Gaussian Fit Parameters')

void = widget_text(base_Gauss1D_lg,value = GaussEquation,xsize = 34,ysize=2)

Mode_Types = ['Automatic',$
              'Manual']

Gauss1DFit_Modes = cw_bgroup(base_Gauss1D_lf,Mode_Types,/col,/exclusive, $
           set_value = 0,/return_index,/no_release, /frame,uname='Gauss1DFitMode')

nterms_Gauss1D=widget_slider(base_Gauss1D_lf, $
              value=6,min=3,max=6,xsize=60, $
              event_pro='MABCEvents',uname='Gauss1D_raw_Slider',title = 'Num. of Terms')


base_Gauss1D_la=widget_base(base_Gauss1D_l,/row)
base_Gauss1D_lb=widget_base(base_Gauss1D_l,/row)


A0_field_Gauss1D=cw_field(base_Gauss1D_la,/row,title='A0',value='',xsize=10)
A1_field_Gauss1D=cw_field(base_Gauss1D_la,/row,title='A1',value='',xsize=10)
A2_field_Gauss1D=cw_field(base_Gauss1D_la,/row,title='A2',value='',xsize=10)
xmin_field_Gauss1D=cw_field(base_Gauss1D_la,/row,title='xmin',value='',xsize=10)
A3_field_Gauss1D=cw_field(base_Gauss1D_lb,/row,title='A3',value='',xsize=10)
A4_field_Gauss1D=cw_field(base_Gauss1D_lb,/row,title='A4',value='',xsize=10)
A5_field_Gauss1D=cw_field(base_Gauss1D_lb,/row,title='A5',value='',xsize=10)
xmax_field_Gauss1D=cw_field(base_Gauss1D_lb,/row,title='xmax',value='',xsize=10)

;widget_control,A1_field,set_value = '54944.560'
widget_control,base_Gauss1D_la,sensitive = 0
widget_control,base_Gauss1D_lb,sensitive = 0


base_Gauss1D_lc=widget_base(base_Gauss1D_l,/row)


Action_Types = ['Zoom',$
              'Set Parameters']

Mouse_Action_Gauss1D = cw_bgroup(base_Gauss1D_lc,Action_Types,/col,/exclusive,label_top='Mouse Action', $
           set_value = 0,/return_index,/no_release, /frame)


base_Gauss1D_ld=widget_base(base_Gauss1D_lc,/row)



Gauss1D_Display_Names = ['Area','Position']

Gauss1D_Display = cw_bgroup(base_Gauss1D_ld,Gauss1D_Display_Names,row=2,/exclusive,label_top = 'Intensity Display',$
            frame = 1,set_value = 0,/no_release,uname='Gauss1D_Display')

base_Gauss1D_lh=widget_base(base_Gauss1D_lc,/col,/align_center)



base_Gauss1D_lf=widget_base(base_Gauss1D_lc,/col)

;void = widget_button(base_Gauss1D_lf,value = 'Plot', uname='Gauss1DPlot')
void = widget_button(base_Gauss1D_lf,value = 'Fit', uname='Gauss1DFit')
void = widget_button(base_Gauss1D_lf,value = 'Clear', uname='Gauss1DClear')
void = widget_button(base_Gauss1D_lf,value = 'To Tables', uname='Gauss1DToTables')


xsize = 400 & ysize = 400



base_gauss2DContour_u=widget_base(base_gauss2DContour,/row)


win_gauss2D = widget_draw(base_gauss2DContour_u,xsize = xsize,ysize = ysize, $
       /button_events,event_pro = 'MABCdraw_gauss2D')

geom_gauss2D = widget_info(base_gauss2DContour_u,/geometry)
;newysize_gauss2D = geom_gauss2D.ysize
newysize_gauss2D = ysize
widget_control,win_gauss2D,draw_ysize = newysize_gauss2D

base_gauss2DContour_l=widget_base(base_gauss2DContour,/row)

base_gauss2DContour_la1=widget_base(base_gauss2DContour_l,/col)

void=widget_label(base_gauss2DContour_la1,value='Position of Maximum Intensity')

base_gauss2DContour_la2=widget_base(base_gauss2DContour_la1,/row,/frame)


Result_Abscissa=cw_field(base_gauss2DContour_la2,/col,title='Abscissa',value='',xsize=10,/noedit,uname='ResultAbscissa')
Result_Ordinate=cw_field(base_gauss2DContour_la2,/col,title='Ordinate',value='',xsize=10,/noedit,uname='ResultOrdinate')

ColourGradient=widget_slider(base_gauss2DContour_la1, $
              value=1,min=1,max=100,title='2D Colour Gradient',xsize=100, $
              event_pro='MABCEvents',uname='ColourGradient',/suppress_value)


base_gauss2DContour_lb=widget_base(base_gauss2DContour_l,/col)

;void=widget_label(base_gauss2DContour_lb,value='')

;void = widget_button(base_gauss2DContour_lb,value = 'Gauss2DFit', uname='ContourGauss2dFit')

Contour_Fit_types_fields = ['Absolute Maximum','2-D Gauss Fit']

Contour_Fit_types = cw_bgroup(base_gauss2DContour_lb,Contour_Fit_types_fields,row=2, $
          /exclusive,label_top = 'Method for Finding Maximum',$
            frame = 1,set_value = 0,/no_release,uname='ContourFittypes')



void = widget_button(base_gauss2DContour_lb,value = 'Update Tables', uname='ContourToTables')

base_gauss2DContour_lc=widget_base(base_gauss2DContour_l,/col)

Display_Names = ['Area','Position']

Display = cw_bgroup(base_gauss2DContour_lc,Display_Names,row=2,/exclusive,label_top = 'Intensity Display',$
            frame = 1,set_value = 0,/no_release,uname='Display')

SaveImageButton = widget_button(base_gauss2DContour_lc,value = 'Save Image', uname='SaveContourImage',sensitive=0)


;base_gauss2DCrossA=widget_base(base_gauss2DCross,/col,title = 'Raw Data')



;xsize = 400 & ysize = 300
xsize = 400 & ysize =xsize/GoldenRatio

base_Cross_u=widget_base(base_gauss2DCross,/col)

win_cross = widget_draw(base_Cross_u,xsize = xsize,ysize = ysize, $
       /button_events,event_pro = 'MABCCross_Draw')
geom_cross = widget_info(base_cross_u,/geometry)
;newysize_raw = geom_raw.ysize
newysize_cross = ysize
widget_control,win_cross,draw_ysize = newysize_cross

base_cross_l=widget_base(base_gauss2DCross,/col)
base_cross_lf=widget_base(base_cross_l,/row)
base_cross_lg=widget_base(base_cross_lf,/col)



void=widget_label(base_cross_lg,value='Estimate of Gaussian Fit Parameters')

void = widget_text(base_cross_lg,value = GaussEquation,xsize = 34,ysize=2)

Mode_Types = ['Automatic',$
              'Manual']

CrossFit_Modes = cw_bgroup(base_cross_lf,Mode_Types,/col,/exclusive, $
           set_value = 0,/return_index,/no_release, /frame,uname='CrossFitMode')


nterms_cross=widget_slider(base_cross_lf, $
              value=6,min=3,max=6,xsize=60, $
              event_pro='MABCEvents',uname='Gauss1D_raw_Cross',title = 'Num. of Terms')



base_cross_la=widget_base(base_cross_l,/row)
base_cross_lb=widget_base(base_cross_l,/row)


A0_field_cross=cw_field(base_cross_la,/row,title='A0',value='',xsize=10)
A1_field_cross=cw_field(base_cross_la,/row,title='A1',value='',xsize=10)
A2_field_cross=cw_field(base_cross_la,/row,title='A2',value='',xsize=10)
xmin_field_cross=cw_field(base_cross_la,/row,title='xmin',value='',xsize=10)
A3_field_cross=cw_field(base_cross_lb,/row,title='A3',value='',xsize=10)
A4_field_cross=cw_field(base_cross_lb,/row,title='A4',value='',xsize=10)
A5_field_cross=cw_field(base_cross_lb,/row,title='A5',value='',xsize=10)
xmax_field_cross=cw_field(base_cross_lb,/row,title='xmax',value='',xsize=10)

widget_control,base_cross_la,sensitive = 0
widget_control,base_cross_lb,sensitive = 0


base_cross_lc=widget_base(base_cross_l,/row)


Action_Types = ['Zoom',$
              'Set Parameters']

Mouse_Action_cross = cw_bgroup(base_cross_lc,Action_Types,/col,/exclusive,label_top='Mouse Action', $
           set_value = 0,/return_index,/no_release, /frame)


base_cross_ld=widget_base(base_cross_lc,/row)

CrossPlot_Types = ['Abscissa',$
              'Ordinate']

Plot_cross = cw_bgroup(base_cross_ld,CrossPlot_Types,/col,/exclusive,label_top='Cross Section Through', $
           set_value = 0,/return_index,/no_release, /frame,uname='CrossPlot')


base_cross_lh=widget_base(base_cross_lc,/col,/align_center)


CrossValue_Field=cw_field(base_cross_lh,/col,title='Value',value='',xsize=10,/noedit)

CrossSlider=widget_slider(base_cross_lh, $
              value=1,min=1,max=100,xsize=100, $
              event_pro='MABCEvents',uname='Cross_SliderValue',/suppress_value)



base_cross_lf=widget_base(base_cross_lc,/col)

;void = widget_button(base_cross_lf,value = 'Plot', uname='CrossPlot')
void = widget_button(base_cross_lf,value = 'Fit', uname='CrossFit')
void = widget_button(base_cross_lf,value = 'Clear', uname='CrossClear')
void = widget_button(base_cross_lf,value = 'To Tables', uname='CrossToTables')


centertlb,tlb
widget_control,tlb,/realize


widget_control,win_raw,get_value = winVis_raw
window,/free,/pixmap,xsize = xsize,ysize = newysize_raw
winPix_raw = !d.window

widget_control,win_gauss2D,get_value = winVis_gauss
window,/free,/pixmap,xsize = xsize,ysize = newysize_gauss2D
winPix_gauss2D = !d.window
;
widget_control,win_cross,get_value = winVis_cross
window,/free,/pixmap,xsize = xsize,ysize = newysize_cross
winPix_cross = !d.window
;
widget_control,win_Gauss1D,get_value = winVis_Gauss1D
window,/free,/pixmap,xsize = xsize,ysize = newysize_Gauss1D
winPix_Gauss1D = !d.window

Aare_30={Aare_30, $
       AFA30:fltarr(3,32), $
       ALA30:fltarr(3,32), $
       ASA30:fltarr(3,32), $
       DLA30:fltarr(3,32), $
       DSA30:fltarr(3,32), $
       DRA30:fltarr(3,32)}
;
Aare_60={Aare_60, $
       AFA60:fltarr(3,32), $
       ALA60:fltarr(3,32), $
       ASA60:fltarr(3,32), $
       DLA60:fltarr(3,32), $
       DSA60:fltarr(3,32), $
       DRA60:fltarr(3,32)}
;
Aare_90={Aare_90, $
       AFA90:fltarr(3,32), $
       ALA90:fltarr(3,32), $
       ASA90:fltarr(3,32), $
       DLA90:fltarr(3,32), $
       DSA90:fltarr(3,32), $
       DRA90:fltarr(3,32)}
;
Aare_120={Aare_120, $
       AFA120:fltarr(3,32), $
       ALA120:fltarr(3,32), $
       ASA120:fltarr(3,32), $
       DLA120:fltarr(3,32), $
       DSA120:fltarr(3,32), $
       DRA120:fltarr(3,32)}
;
Aare_150={Aare_150, $
       AFA150:fltarr(3,32), $
       ALA150:fltarr(3,32), $
       ASA150:fltarr(3,32), $
       DLA150:fltarr(3,32), $
       DSA150:fltarr(3,32), $
       DRA150:fltarr(3,32)}
;
Berg_30={Berg_30, $
       AFB30:fltarr(3,32), $
       ALB30:fltarr(3,32), $
       ASB30:fltarr(3,32), $
       DLB30:fltarr(3,32), $
       DSB30:fltarr(3,32), $
       DRB30:fltarr(3,32)}
;
Berg_60={Berg_60, $
       AFB60:fltarr(3,32), $
       ALB60:fltarr(3,32), $
       ASB60:fltarr(3,32), $
       DLB60:fltarr(3,32), $
       DSB60:fltarr(3,32), $
       DRB60:fltarr(3,32)}
;
Berg_90={Berg_90, $
       AFB90:fltarr(3,32), $
       ALB90:fltarr(3,32), $
       ASB90:fltarr(3,32), $
       DLB90:fltarr(3,32), $
       DSB90:fltarr(3,32), $
       DRB90:fltarr(3,32)}
;
Berg_120={Berg_120, $
       AFB120:fltarr(3,32), $
       ALB120:fltarr(3,32), $
       ASB120:fltarr(3,32), $
       DLB120:fltarr(3,32), $
       DSB120:fltarr(3,32), $
       DRB120:fltarr(3,32)}
;
Berg_150={Berg_150, $
       AFB150:fltarr(3,32), $
       ALB150:fltarr(3,32), $
       ASB150:fltarr(3,32), $
       DLB150:fltarr(3,32), $
       DSB150:fltarr(3,32), $
       DRB150:fltarr(3,32)}



Analyser_structure={Analyser_structure, $
              Aare_30:Aare_30, $
              Aare_60:Aare_60, $
              Aare_90:Aare_90, $
              Aare_120:Aare_120, $
              Aare_150:Aare_150, $
              Berg_30:Berg_30, $
              Berg_60:Berg_60, $
              Berg_90:Berg_90, $
              Berg_120:Berg_120, $
              Berg_150:Berg_150}
;
;
state_mabc = { Chopper_Table:Chopper_Table, $
         Scan_Table:Scan_Table, $
         Scan_Input:Scan_Input, $
         dspace_array:dspace_array, $
          Em:Em, $
          Ewinc:Ewinc, $
          Ewinl:Ewinl, $
          Ewinu:Ewinu, $
          tofwindow:tofwindow, $
          tofoutput:tofoutput, $
         Master:Master, $
         mica:mica, $
         constants:constants, $
         TimeBins:TimeBins, $
         XCoords:ptr_new(/allocate_heap), $
         YCoords:ptr_new(/allocate_heap), $
         DataArray_x:ptr_new(/allocate_heap), $
         DataArray_y:ptr_new(/allocate_heap), $
         GaussFits_x:ptr_new(/allocate_heap), $
         GaussFits_y:ptr_new(/allocate_heap), $
         DataArray_Zint:ptr_new(/allocate_heap), $
         DataArray_ZPeak:ptr_new(/allocate_heap), $
         old_dc:old_dc, $
         winVis_raw:winVis_raw, $
         winPix_raw:winPix_raw, $
         winVis_gauss:winVis_gauss, $
         winPix_gauss2D:winPix_gauss2D, $
         Result_Abscissa:Result_Abscissa, $
         Result_Ordinate:Result_Ordinate, $
         Display:Display, $
         Analyser_Result:Analyser_Result, $
         ColourGradient:ColourGradient, $
         Aare_Table:Aare_Table, $
         Berg_Table:Berg_Table, $
         Aare_Triffid_Table:Aare_Triffid_Table, $
         Berg_Triffid_Table:Berg_Triffid_Table, $
         AareForegroundColors:AareForegroundColors, $
         BergForegroundColors:BergForegroundColors, $
         xrange_gauss:[0.0,0.0], $
         yrange_gauss:[0.0,0.0], $
         xrange_raw:[0.0,0.0], $
         yrange_raw:[0.0,0.0], $
         xrange_cross:[0.0,0.0], $
         yrange_cross:[0.0,0.0], $
         yrange_Gauss1D:[0.0,0.0], $
         xrange_Gauss1D:[0.0,0.0], $
         mouse_raw:0B, $
         mouse_gauss:0B, $
         mouse_cross:0B, $
         mouse_Gauss1D:0B, $
         xbox_gauss:[0.0,0.0], $
         ybox_gauss:[0.0,0.0], $
         xbox_raw:[0.0,0.0], $
         ybox_raw:[0.0,0.0], $
         xbox_cross:[0.0,0.0], $
         ybox_cross:[0.0,0.0], $
         xbox_Gauss1D:[0.0,0.0], $
         ybox_Gauss1D:[0.0,0.0], $
         autoscale_gauss:1, $
         autoscale_raw:1, $
         autoscale_cross:1, $
         autoscale_Gauss1D:1, $
         win_raw:win_raw, $
         win_gauss2D:win_gauss2D, $
         UnitUser_exe:0, $
         UnitUser_2:0, $
         UnitSpy:0, $
         UnitManager:0, $
         loaded_mabc:0, $
         demo_mabc:1, $
         ConnectButton:ConnectButton, $
         analyser_angle_droplist:analyser_angle_droplist, $
         Calibration_Angles_str:Calibration_Angles_str, $
         Analyser_Energy_Field:Analyser_Energy_Field, $
         Energy_Window_Width:Energy_Window_Width, $
         Energy_Window_Slider:Energy_Window_Slider, $
         First_Neutrons_Time:First_Neutrons_Time, $
         Last_Neutrons_Time:Last_Neutrons_Time, $
         tofwindow_field:tofwindow_field, $
         TimeBinStart:TimeBinStart, $
         TimeBinStep:TimeBinStep, $
         TimeBinWidth:TimeBinWidth, $
         TimeBinNumber:TimeBinNumber, $
         TotalTimeBinNumber:TotalTimeBinNumber, $
         TimeBinIndices:[353,454,430,533,558,666,1098,1199,734,836,613,715,-1,-1], $
         Analyser_structure:Analyser_structure, $
         Load_Analyser_Button:Load_Analyser_Button, $
         Scan_Type_Select:Scan_Type_Select, $
         win_raw_Slider:win_raw_Slider, $
         A0_field:A0_field, $
         A1_field:A1_field, $
         A2_field:A2_field, $
         A3_field:A3_field, $
         A4_field:A4_field, $
         A5_field:A5_field, $
         Mouse_Action:Mouse_Action, $
         xrange_fitwindow:[0.0,1.0], $
         yrange_fitwindow:[0.0,1.0], $
         xrange_fitwindowCross:[0.0,1.0], $
         yrange_fitwindowCross:[0.0,1.0], $
         xrange_fitwindowGauss1D:[0.0,1.0], $
         yrange_fitwindowGauss1D:[0.0,1.0], $
         pix:1, $
         xmin_field:xmin_field, $
         xmax_field:xmax_field, $
         Fit_Modes:Fit_Modes, $
         base_raw_la:base_raw_la, $
         base_raw_lb:base_raw_lb, $
         GaussParameters:ptr_new(/allocate_heap), $
         CrossSlider:CrossSlider, $
         CrossValue_Field:CrossValue_Field, $
         Plot_cross:Plot_cross, $
         Mouse_Action_cross:Mouse_Action_cross, $
         A0_field_cross:A0_field_cross, $
         A1_field_cross:A1_field_cross, $
         A2_field_cross:A2_field_cross, $
         A3_field_cross:A3_field_cross, $
         A4_field_cross:A4_field_cross, $
         A5_field_cross:A5_field_cross, $
         xmin_field_cross:xmin_field_cross, $
         xmax_field_cross:xmax_field_cross, $
         win_cross:win_cross, $
         winVis_cross:winVis_cross, $
         winPix_cross:winPix_cross, $
         winVis_Gauss1D:winVis_Gauss1D, $
         winPix_Gauss1D:winPix_Gauss1D, $
         CrossFit_Modes:CrossFit_Modes, $
         GaussCrossX:ptr_new(/allocate_heap), $
         GaussCrossY:ptr_new(/allocate_heap), $
         GaussCrossParameters:ptr_new(/allocate_heap), $
         GaussGauss1DX:ptr_new(/allocate_heap), $
         GaussGauss1DY:ptr_new(/allocate_heap), $
         GaussGauss1DParameters:ptr_new(/allocate_heap), $
         base_cross_la:base_cross_la, $
         base_cross_lb:base_cross_lb, $
         base_Gauss1D_la:base_Gauss1D_la, $
         base_Gauss1D_lb:base_Gauss1D_lb, $
         Gauss1DFit_Modes:Gauss1DFit_Modes, $
         DataType:0, $
         base_gauss1D:base_gauss1D, $
         base_gauss2DContour:base_gauss2DContour, $
         base_gauss2DCross:base_gauss2DCross, $
         base_gauss2D:base_gauss2D, $
         win_Gauss1D:win_Gauss1D, $
         A0_field_Gauss1D:A0_field_Gauss1D, $
         A1_field_Gauss1D:A1_field_Gauss1D, $
         A2_field_Gauss1D:A2_field_Gauss1D, $
         A3_field_Gauss1D:A3_field_Gauss1D, $
         A4_field_Gauss1D:A4_field_Gauss1D, $
         A5_field_Gauss1D:A5_field_Gauss1D, $
         xmin_field_Gauss1D:xmin_field_Gauss1D, $
         xmax_field_Gauss1D:xmax_field_Gauss1D, $
         Mouse_Action_Gauss1D:Mouse_Action_Gauss1D, $
         Gauss1D_Display:Gauss1D_Display, $
         Xvariable:'', $
         Yvariable:'', $
         nterms_raw:nterms_raw, $
         nterms_Gauss1D:nterms_Gauss1D, $
         nterms_cross:nterms_cross, $
         Contour_Fit_types:Contour_Fit_types, $
         Monitor_counts:Monitor_counts, $
         terminate:0B, $
         ParameterButton:ParameterButton, $
         ParameterChopperButton:ParameterChopperButton, $
         ParameterTriffidButton:ParameterTriffidButton, $
         ParameterHistogramButton:ParameterHistogramButton, $
         ParameterAareTriffidButton:ParameterAareTriffidButton, $
         ParameterBergTriffidButton:ParameterBergTriffidButton, $
         raw_SliderValue:raw_SliderValue, $
         koennecke_pic:koennecke_pic, $
         start_time:double(0.0), $
         current_j:0, $
         current_k:0, $
         current_l:0, $
         Calibration_Create_tlb:0, $
         motor_commandsX:ptr_new(/allocate_heap), $
         motor_commandsY:ptr_new(/allocate_heap), $
         ScanTypeSelect:0, $
         DataPoints:0, $
         totalruns:0, $
         delim:delim, $
         timeoffsets:timeoffsets, $
         End_Monitor_Time:End_Monitor_Time, $
         First_PostMonitor_Time:First_PostMonitor_Time, $
         End_PostMonitor_Time:End_PostMonitor_Time, $
         view:view, $
         Time_Window:Time_Window, $
         SaveImageButton:SaveImageButton, $
         RawAsciiName:RawAsciiName, $
         workDir:workDir $
         }



pState_mabc = ptr_new(state_mabc,/no_copy)
widget_control,tlb,set_uvalue = pState_mabc


daveDeSensitizeButtons,{id:0,top:tlb,handler:1,select:1}
password=MABC_password_widget(group_leader = tlb)
if password ne 'MARSLNS' then begin
MABC_cleanup,tlb
MABC_exit,{id:0,top:tlb,handler:1,select:1}
return
endif else begin
  daveSensitizeButtons,{id:0,top:tlb,handler:1,select:1}
endelse

xmanager,register_name,tlb,event_handler = 'MABCEvents',cleanup= 'MABC_cleanup'


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;