; NAME:
; MDDC
; DATE of WORKING VERSION: 25 April 2006
; MarsStatus
;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:
;
;      MDDC
;
;
; 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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Obtain programs (Filges and Koennecke) to read in the hdf files
@napi45
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MDDC_cleanup,tlb
;print,tlb
widget_control,tlb,get_uvalue = pstate_mddc
wdelete,(*pstate_mddc).windpix_mddc
device, decomposed = (*pstate_mddc).old_dc
if (*pstate_mddc).demo_mddc eq 0 then begin
sicsclose,(*pstate_mddc).UnitUser_2
sicsclose,(*pstate_mddc).UnitUser_exe
sicsclose,(*pstate_mddc).UnitSpy
sicsclose,(*pstate_mddc).UnitManager
endif
heap_free,pstate_mddc
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MDDC_exit,event
widget_control,event.top,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MDDC_save,event
widget_control,event.top,get_uvalue = pstate_mddc
;parameters in field entry
widget_control,(*pstate_mddc).Chopper_Table,get_value=Chopper_Table
widget_control,(*pstate_mddc).Triffid_Table,get_value=Triffid_Table
;
;save parameters aray
SaveParametersArray={Chopper_Table:Chopper_Table, $
               Triffid_Table:Triffid_Table $
               }

workDir=(*pstate_mddc).workDir
    filename=dialog_pickfile(path=workDir,$
      file='MarsCalibrationFile.cal',/write,filter="*.pln",/fix_filter)


;filename='C:\MarsCalibrationFile.cal'

save, filename=filename, SaveParametersArray


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MDDC_planner_Read,event
widget_control,event.top,get_uvalue = pstate_mddc
Diffraction_Output=(*pstate_mddc).Diffraction_Output
workDir=(*pstate_mddc).workDir
    filename=dialog_pickfile(path=workDir,$
      file='MarsPlannerFile.pln',/read,filter="*.pln",/fix_filter)
;      filename='c:\MarsPlannerFile.pln'
restore,filename=filename
output=SaveParametersArray.output

output=float(output)
;newoutput=fltarr(2,5)

help,output
;for i = 0,4 do begin
;newoutput[0,i]=output[0,i]
;newoutput[1,i]=output[2,i]
;endfor
widget_control,(*pstate_mddc).Chopper_Table,set_value=output
;calculate minimum and maximum d-spacing
El=SaveParametersArray.El
Eu=SaveParametersArray.Eu
constants=(*pstate_mddc).constants
h=constants.h
mn=constants.mn

conv=h*1e9*241.79890;convert from meV to joules
El*=conv ;convert to joules
Eu*=conv ;convert to joules
vl=sqrt(2.0*El/mn)
vu=sqrt(2.0*Eu/mn)
angle=7.5
for i = 0,5 do begin
dspaceMin=(h*1e10)/(2.0*mn*vu*sin(angle*!DTOR))
dspaceMax=(h*1e10)/(2.0*mn*vl*sin(angle*!DTOR))
Diffraction_Output[0,i]=dspaceMin
Diffraction_Output[1,i]=dspaceMax
angle+=15.0
endfor
(*pstate_mddc).Diffraction_Output=Diffraction_Output
widget_control,(*pstate_mddc).Diffraction_Table,set_value=Diffraction_Output

Time_Bin_Start=SaveParametersArray.Time_Bin_Start
Time_Bin_Step=SaveParametersArray.Time_Bin_Step
Total_Time_Bin_Number=SaveParametersArray.Total_Time_Bin_Number
TimeBinIndices=SaveParametersArray.TimeBinIndices
print,'TimeBinIndices = ',TimeBinIndices

(*pstate_mddc).TOF_start=Time_Bin_Start
(*pstate_mddc).TOF_step=Time_Bin_Step
(*pstate_mddc).notimebin=Total_Time_Bin_Number
(*pstate_mddc).TimeBinIndices=TimeBinIndices

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MDDCPlot,event
widget_control,event.top,get_uvalue = pstate_mddc
x = *(*pstate_mddc).x
y = *(*pstate_mddc).y
if (*pstate_mddc).autoscale eq 1 then begin
  xlo = min(x) & xhi = max(x)
  ylo = min(y) & yhi = max(y)
  (*pstate_mddc).xrange = [xlo,xhi]
  (*pstate_mddc).yrange = [ylo,yhi]
endif
;print,x[0]
;print,'n_elements(x) = ',n_elements(x)


plot,x,y,xrange = (*pstate_mddc).xrange,yrange = (*pstate_mddc).yrange, $
     xstyle = 1,ystyle = 1,xtitle = 'd-spacing / A', $
     ytitle = 'Intensity', title = 'Diffraction Pattern',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0

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 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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MDDCdraw,event
widget_control,event.top,get_uvalue = pstate_mddc
widget_control,(*pstate_mddc).action,get_value = val
if val eq 0 then begin
case event.type of
0:  begin       ; button press
      (*pstate_mddc).mouse = event.press
      if (*pstate_mddc).mouse eq 4 then begin
        (*pstate_mddc).autoscale = 1

        wset,(*pstate_mddc).windpix_mddc
        MDDCPlot,event
        wset,(*pstate_mddc).winVis_mddc
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
      endif
      if (*pstate_mddc).mouse eq 1 then begin
        (*pstate_mddc).xbox[0] = event.x
        (*pstate_mddc).ybox[0] = event.y
        wset,(*pstate_mddc).winVis_mddc
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
        empty
        (*pstate_mddc).autoscale = 0
        widget_control,(*pstate_mddc).win,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pstate_mddc).mouse eq 1 then begin
      xll = (*pstate_mddc).xbox[0] < (*pstate_mddc).xbox[1]
      yll = (*pstate_mddc).ybox[0] < (*pstate_mddc).ybox[1]
      w = abs((*pstate_mddc).xbox[1] - (*pstate_mddc).xbox[0])
      h = abs((*pstate_mddc).ybox[1] - (*pstate_mddc).ybox[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      (*pstate_mddc).xrange = [ll[0],ur[0]]
      (*pstate_mddc).yrange = [ll[1],ur[1]]
      wset,(*pstate_mddc).windpix_mddc
        MDDCPlot,event
      wset,(*pstate_mddc).winVis_mddc
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
      (*pstate_mddc).mouse = 0B
      widget_control,(*pstate_mddc).win,draw_motion_events = 0
     endif
     if (*pstate_mddc).mouse eq 4 then begin
      wset,(*pstate_mddc).windpix_mddc
        MDDCPlot,event
      wset,(*pstate_mddc).winVis_mddc
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
      (*pstate_mddc).mouse = 0B
      widget_control,(*pstate_mddc).win,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pstate_mddc).mouse eq 1 then begin
       (*pstate_mddc).xbox[1] = event.x
       (*pstate_mddc).ybox[1] = event.y
       xc = [(*pstate_mddc).xbox[0],event.x,event.x,$
             (*pstate_mddc).xbox[0],$
             (*pstate_mddc).xbox[0]]
       yc = [(*pstate_mddc).ybox[0],(*pstate_mddc).ybox[0],$
             event.y,event.y,$
             (*pstate_mddc).ybox[0]]
       wset,(*pstate_mddc).winVis_mddc
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
       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_mddc).mouse = event.press
      if (*pstate_mddc).mouse eq 4 then begin
        (*pstate_mddc).autoscale = 1

        wset,(*pstate_mddc).windpix_mddc
        MDDCPlot,event
        wset,(*pstate_mddc).winVis_mddc
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
      endif
      if (*pstate_mddc).mouse eq 1 then begin
        (*pstate_mddc).xbox[0] = event.x
        (*pstate_mddc).ybox[0] = event.y
        wset,(*pstate_mddc).winVis_mddc
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
        empty
        (*pstate_mddc).autoscale = 0
        widget_control,(*pstate_mddc).win,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pstate_mddc).mouse eq 1 then begin
      xll = (*pstate_mddc).xbox[0] < (*pstate_mddc).xbox[1]
      yll = (*pstate_mddc).ybox[0] < (*pstate_mddc).ybox[1]
      w = abs((*pstate_mddc).xbox[1] - (*pstate_mddc).xbox[0])
      h = abs((*pstate_mddc).ybox[1] - (*pstate_mddc).ybox[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_mddc).xrange_fitwindow = [ll[0],ur[0]]
      (*pstate_mddc).yrange_fitwindow = [ll[1],ur[1]]
      ;print, 'xrange:',(*pstate_mddc).xrange
      ;print, 'yrange:',(*pstate_mddc).yrange
      ;print,''
      ;print, 'xrange_fitwindow:',(*pstate_mddc).xrange_fitwindow
      ;print, 'yrange_fitwindow:',(*pstate_mddc).yrange_fitwindow
    MDDC_GaussFit,event

    ;  wset,(*pstate_mddc).windpix_mddc
    ;    MDDCPlot,event
    ;  wset,(*pstate_mddc).winVis_mddc
    ;  device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
      (*pstate_mddc).mouse = 0B
      widget_control,(*pstate_mddc).win,draw_motion_events = 0


     endif
     if (*pstate_mddc).mouse eq 4 then begin
      wset,(*pstate_mddc).windpix_mddc
        MDDCPlot,event
      wset,(*pstate_mddc).winVis_mddc
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
      (*pstate_mddc).mouse = 0B
      widget_control,(*pstate_mddc).win,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pstate_mddc).mouse eq 1 then begin
       (*pstate_mddc).xbox[1] = event.x
       (*pstate_mddc).ybox[1] = event.y
       xc = [(*pstate_mddc).xbox[0],event.x,event.x,$
             (*pstate_mddc).xbox[0],$
             (*pstate_mddc).xbox[0]]
       yc = [(*pstate_mddc).ybox[0],(*pstate_mddc).ybox[0],$
             event.y,event.y,$
             (*pstate_mddc).ybox[0]]
       wset,(*pstate_mddc).winVis_mddc
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
return
endif
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro     MDDC_GaussFit,event
widget_control,event.top,get_uvalue = pstate_mddc
colors=(*pstate_mddc).colors
xrange_fitwindow=(*pstate_mddc).xrange_fitwindow
yrange_fitwindow=(*pstate_mddc).yrange_fitwindow
x=*(*pstate_mddc).x
y=*(*pstate_mddc).y
whereinxrange=where(x ge xrange_fitwindow[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_fitwindow[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)
;print,'A2 = ',A2
A3=0.0
A4=0.0
estimates=[A0,A1,A2,A3,A4]
yfit=gaussfit(xwin,ywin,coeff,chisq=chisq,estimates=estimates,sigma=sigma,nterms=5)
;print,'A1 = ',coeff[1]
;print,'coeff ',coeff
;print,'chisq ',chisq

 widget_control,(*pstate_mddc).Gauss_Fit_Experiment,set_value=coeff[1]

xlims=!x.crange
ylims=!y.crange
xpos=xlims[0]+(xlims[1]-xlims[0])*0.6
xyouts,xpos,0.9*ylims[1],"Chisq = "+string(chisq) ,color=(*pstate_mddc).colors.red
xyouts,xpos,0.85*ylims[1],"Position = "+string(coeff[1])+' '+'+-'+string(sigma[1]) ,color=(*pstate_mddc).colors.red


  oplot,xwin,yfit,linestyle = 2, thick = 2.0, psym=0, symsize=1.0,color=(*pstate_mddc).colors.red

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mddc_dspacing,event
widget_control,event.top,get_uvalue = pstate_mddc
ElasticData_x=*(*pstate_mddc).DataArray_x
ElasticData=*(*pstate_mddc).DataArray_y
DataArray_x_original=*(*pstate_mddc).DataArray_x
DataArray_y_original=*(*pstate_mddc).DataArray_y
constants=(*pstate_mddc).constants
h=constants.h
mn=constants.mn
lDiff=constants.lDiff
constants=(*pstate_mddc).constants
DiffractionAngles=constants.DiffractionAngles
;print,'diffangle = ', DiffractionAngles[value]/2.0


   CATCH, Error_status
if Error_status ne 0 then begin
    catch, /cancel ;skip the normalisation
DataArray_x=DataArray_x_original
HELP,DataArray_x
;theta=82.5
for i=0,5 do begin ; Aare side
theta=DiffractionAngles[i]/2.0

DataArray_x[i,*]=DataArray_x_original[i,*]*((h*1e4)/(2.0*mn*lDiff*sin(theta*!DTOR)))

;theta-=15.0
endfor
;theta=7.5
for i=6,11 do begin ; Berg side
theta=DiffractionAngles[i]/2.0
DataArray_x[i,*]=DataArray_x_original[i,*]*((h*1e4)/(2.0*mn*lDiff*sin(theta*!DTOR)))
;theta+=15.0
endfor
*(*pstate_mddc).DataArray_x=DataArray_x
*(*pstate_mddc).DataArray_y=DataArray_y_original
return
endif
DataArray_x=DataArray_x_original
;theta=82.5
for i=0,5 do begin ; Aare side
theta=DiffractionAngles[i]/2.0
DataArray_x[i,*]=DataArray_x_original[i,*]*((h*1e4)/(2.0*mn*lDiff*sin(theta*!DTOR)))
;theta-=15.0
endfor
;theta=7.5
for i=6,11 do begin ; Berg side
theta=DiffractionAngles[i]/2.0
DataArray_x[i,*]=DataArray_x_original[i,*]*((h*1e4)/(2.0*mn*lDiff*sin(theta*!DTOR)))
;theta+=15.0
endfor
*(*pstate_mddc).DataArray_x=DataArray_x
*(*pstate_mddc).DataArray_y=DataArray_y_original
return

IF (*pstate_mddc).demo_mddc EQ 0 THEN BEGIN


DataMonitor2_x=*(*pstate_mddc).TOFMonitorArray_x
DataMonitor2=*(*pstate_mddc).TOFMonitorArray_y
v=lDiff/(reform(ElasticData_x[0,*])/1.0e6)
LambdaDiff=(h*1e10)/(mn*v)
lTOFMon=constants.lTOFMon
v=lTOFMon/(DataMonitor2_x/1.0e6)
LambdaMon=(h*1e10)/(mn*v)
;print,'LambdaMon: ',LambdaMon
Mon_Efficiency=1-exp(-0.0157*LambdaMon)
DataMonitor2/=Mon_Efficiency ; DataMonitor2 now corresponds to a black detector
;extract dimension of time channels
channels_mon=n_elements(LambdaMon)
channels_diff=n_elements(LambdaDiff)
index_map=intarr(2,channels_diff)
;print,'ElasticData_x: ',ElasticData_x
;print,''
;print,'DataMonitor2_x: ',DataMonitor2_x
;print,''

index_map[0,*]=indgen(channels_diff)
udiff=1+bytarr(channels_diff)
umon=1+bytarr(channels_mon)
diff=abs(LambdaDiff#umon-udiff#LambdaMon)
for i=0,channels_diff-1 do begin
void=min(diff[i,*],ind,/absolute)
index_map[1,i]=ind
endfor

;
for i=0,channels_diff-1 do begin
;print,'DataMonitor2[index_map[1,i]]: ',DataMonitor2[index_map[1,i]]
    if DataMonitor2[index_map[1,i]] gt 100 then begin  ; we must have reasonable statistics in the monitor
    ElasticData[*,i]/=DataMonitor2[index_map[1,i]]
;    ElasticError[*,i]/=sqrt((ElasticError[*,i]/DataMonitor2[index_map[1,i]]^2) + $
;             (ElasticError[*,i]^2/DataMonitor2[index_map[1,i]]^3))  ; error treatment according to Vladamir
     endif else begin
    ElasticData[*,i]=0.0
    endelse

if (index_map[1,i] eq 0) or (index_map[1,i] eq (n_elements(DataMonitor2)-1)) then begin
    if n_elements(reject) eq 0 then begin
    reject=i
    endif else begin
    reject=[reject,i]
    endelse
endif
endfor

DataArray_y=ElasticData
DataArray_x=ElasticData_x


if n_elements(reject) ne 0 then begin
;help,reject
;print,'reject: ',reject
ElasticData_new=fltarr(12,channels_diff-n_elements(reject))
ElasticData_x_new=fltarr(12,channels_diff-n_elements(reject))
    j=0
    k=0
    for i=0,channels_diff-1 do begin
    whereiconrej=where(i eq reject,count)
    if count ne 0 then begin
    k+=1
    endif else begin
    ElasticData_new[*,j]=ElasticData[*,k]
    ElasticData_x_new[*,j]=ElasticData_x[*,k]
    j+=1
    k+=1
    endelse
    endfor
;
;
DataArray_y=ElasticData_new
DataArray_x=ElasticData_x_new
endif
ENDIF ELSE BEGIN
DataArray_x=*(*pstate_mddc).DataArray_x
DataArray_y=*(*pstate_mddc).DataArray_y
ENDELSE


;theta=82.5
for i=0,5 do begin ; Aare side
theta=DiffractionAngles[i]/2.0
DataArray_x[i,*]*=((h*1e4)/(2.0*mn*lDiff*sin(theta*!DTOR)))
;theta-=15.0
endfor
;theta=7.5
for i=6,11 do begin ; Berg side
theta=DiffractionAngles[i]/2.0
DataArray_x[i,*]*=((h*1e4)/(2.0*mn*lDiff*sin(theta*!DTOR)))
;theta+=15.0
endfor



*(*pstate_mddc).DataArray_x=DataArray_x
*(*pstate_mddc).DataArray_y=DataArray_y

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro CreateFake2D_Data ,event
;This procedure plays no part in the program.  It is used to create fake data for the
; Triffid Calibration Program
;
widget_control,event.top,get_uvalue = pstate_mddc
return
workDir=(*pstate_mddc).workDir
xttt=*(*pstate_mddc).DataArray_x
yttt=*(*pstate_mddc).DataArray_y
xtt=xttt[0,*]
ytt=yttt[0,*]
xt=xtt[where(xtt gt 31.6)]
yt=ytt[where(xtt gt 31.6)]
x=xt[where(xt lt 33.6)]
y=yt[where(xt lt 33.6)]
;print, x,y
n=n_elements(x)
FakeDataArray_X=fltarr(10,10,n)
FakeDataArray_Y=fltarr(10,10,n)


for i=0,9 do begin
for j=0,9 do begin
FakeDataArray_X[i,j,*]=x
FakeDataArray_Y[i,j,*]=y
if i gt 3 then FakeDataArray_X[i,j,*]+=abs((i^1.4-3)/20.0)
if j gt 3 then FakeDataArray_X[i,j,*]+=abs((j^1.6-3)/30.0)
if i lt 3 then FakeDataArray_X[i,j,*]+=abs((i^1.7-3)/10.0)
if j lt 3 then FakeDataArray_X[i,j,*]+=abs((j^2-3)/24.0)
;sumsq=i^2+j^2
;FakeDataArray_X[i,j,*]+=abs((sumsq-18)/600.0)
;
;
factor_i=abs(3-i)
factor_j=abs(3-j)
if factor_i eq 0 then factor_i = 0.9
if factor_j eq 0 then factor_j = 0.9
FakeDataArray_Y[i,j,*]*=sqrt(0.9/(factor_i*factor_j))
endfor
endfor
;print, 'FakeDataArray_X[1,0,0] = ',FakeDataArray_X[1,0,0]
;print, 'FakeDataArray_X[2,0,0] = ',FakeDataArray_X[2,0,0]
FakeData_structure={FakeDataArray_X:FakeDataArray_X,FakeDataArray_Y:FakeDataArray_Y}
save, filename=WorkDir+'FakeData', FakeData_structure
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Load_Data,event
widget_control,event.top,get_uvalue = pstate_mddc
workDir=(*pstate_mddc).workDir
delim=(*pstate_mddc).delim
constants=(*pstate_mddc).constants
HP=constants.Histogram_Period

;
IF (*pstate_mddc).demo_mddc EQ 0 THEN BEGIN

UnitSpy=(*pstate_mddc).UnitSpy
;get all the histogram memory of the diffraction and and triffid detectors

notimebin=sicscommand(event,UnitSpy,'hm notimebin',datatype='long')
;
print,'notimebin = ',notimebin
;
nodata=24*notimebin ;number of detectors (monitors included) * number of timebins
tstart=systime(/seconds)
data=sicscommand(event,UnitSpy,'hm get 0',datatype='fltarr',dimension=nodata)
telapsed=systime(/seconds)-tstart
print,'Time to read in data = ',telapsed
;
timebin=sicscommand(event,UnitSpy,'hm timebin',datatype='fltarr',dimension=notimebin)
timebin/=10.0
timebin_space=(timebin[1]-timebin[0])/2.0
timebin+=timebin_space


widget_control,(*pstate_mddc).Chopper_Table,get_value=Choppers_Info


timeoffsets=(*pState_mddc).timeoffsets
offset=0.0
masterfundamental=fix(round(Choppers_Info[1,1]/3000.0))
;print,'masterfundamental: ',masterfundamental
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
timebin+=offset

;print,'offset: ',offset
;print,'timebin: ',timebin

DataArray_x=fltarr(12,notimebin)
DataArray_y=fltarr(12,notimebin)
dp=0 ;data_pointer
for i=0,11 do begin
DataArray_x[i,*]=timebin
DataArray_y[i,*]=data[dp:dp+notimebin-1]
dp+=notimebin
endfor

dp+=notimebin*10
TOFMonitorArray_x=fltarr(notimebin)
TOFMonitorArray_y=fltarr(notimebin)
TOFMonitorArray_x=timebin
TOFMonitorArray_y=data[dp:dp+notimebin-1]


;time bin cull
TimeBinIndices=(*pState_mddc).TimeBinIndices
;diffraction detectors
StartBin=TimeBinIndices[4]
EndBin=TimeBinIndices[5]
IF endbin GT startbin THEN BEGIN
DataArray_x=DataArray_x[*,StartBin:EndBin]
DataArray_y=DataArray_y[*,StartBin:EndBin]
ENDIF ELSE BEGIN
dimensions=size(DataArray_x)
channels=dimensions[2]
width=channels-startbin+endbin+1
firstbit=channels-startbin
secondbit=endbin+1
xdat=fltarr(12,width)
ydat=fltarr(12,width)
xdat[*,0:firstbit-1]=DataArray_x[*,StartBin:channels-1]-HP
ydat[*,0:firstbit-1]=DataArray_y[*,StartBin:channels-1]
xdat[*,firstbit:firstbit+secondbit-1]=DataArray_x[*,0:EndBin]
ydat[*,firstbit:firstbit+secondbit-1]=DataArray_y[*,0:EndBin]
DataArray_x=xdat
DataArray_y=ydat
ENDELSE
;incident monitor
slider=94
StartBin=TimeBinIndices[0]
EndBin=TimeBinIndices[1]
IF endbin GT startbin THEN BEGIN
width=endbin-startbin
newwidth=fix(width*(slider/100.0))
WidthAdjustment=fix((newwidth-width)/2) ;just in case
newstart=startbin-WidthAdjustment
newend=endbin+WidthAdjustment
TOFMonitorArray_x=TOFMonitorArray_x[newstart:newend]
TOFMonitorArray_y=TOFMonitorArray_y[newstart:newend]
ENDIF ELSE BEGIN
channels=notimebin
width=channels-startbin+endbin+1
newwidth=fix(width*(slider/100.0))
WidthAdjustment=fix((newwidth-width)/2) ;just in case
newstart=startbin-WidthAdjustment
newend=endbin+WidthAdjustment
newwidth=channels-newstart+newend+1
firstbit=channels-newstart
secondbit=newend+1
xdat=fltarr(newwidth)
ydat=fltarr(newwidth)
xdat[0:firstbit-1]=TOFMonitorArray_x[newstart:channels-1]-HP
ydat[0:firstbit-1]=TOFMonitorArray_y[newstart:channels-1]
xdat[firstbit:firstbit+secondbit-1]=TOFMonitorArray_x[0:newend]
ydat[firstbit:firstbit+secondbit-1]=TOFMonitorArray_y[0:newend]
TOFMonitorArray_x=xdat
TOFMonitorArray_y=ydat
ENDELSE

;print,'notimebin after cull = ',EndBin-StartBin+1
print,'TimeBinIndices = ',TimeBinIndices


*(*pstate_mddc).DataArray_x=DataArray_x
*(*pstate_mddc).DataArray_y=DataArray_y
*(*pstate_mddc).TOFMonitorArray_x=TOFMonitorArray_x
*(*pstate_mddc).TOFMonitorArray_y=TOFMonitorArray_y


mddc_dspacing,event

DataArray_x=*(*pstate_mddc).DataArray_x
DataArray_y=*(*pstate_mddc).DataArray_y

x=DataArray_x[0,*]
y=DataArray_y[0,*]

;print,x[0,*]
;print,'n_elements(x) = ',n_elements(x)

xlo=min(x) & xhi=max(x)
ylo=min(y) & yhi=max(y)
(*pstate_mddc).xlo=xlo
(*pstate_mddc).ylo=ylo
(*pstate_mddc).xhi=xhi
(*pstate_mddc).yhi=yhi

*(*pstate_mddc).x=x
*(*pstate_mddc).y=y
  (*pstate_mddc).xrange = [xlo,xhi]
  (*pstate_mddc).yrange = [ylo,yhi]






ENDIF ELSE BEGIN


;data=read_ascii(!DAVE_AUXILIARY_DIR+'PSI\MARS\mddc_diff.txt',count=count)
data=read_ascii(!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'mddc_diff.txt',count=count)
;data=read_ascii(workdir+'mddc_diff.txt',count=count)
;help,data
;print,tag_names(data,count=count)
field=data.field1
;print,count
x=fltarr(count)
y=fltarr(count)
DataArray_x=fltarr(12,count)
DataArray_y=fltarr(12,count)
for i=0,count-1 do begin
x[i]=field[i*2]
y[i]=field[i*2+1]
endfor
for i = 0,11 do begin
DataArray_x[i,0:n_elements(x)-1]=x
DataArray_y[i,0:n_elements(y)-1]=y
endfor
;print,x[0]
;print,'n_elements(x) = ',n_elements(x)
;print,DataArray_x[0,0]
*(*pstate_mddc).DataArray_x=DataArray_x
*(*pstate_mddc).DataArray_y=DataArray_y

mddc_dspacing,event

;CreateFake2D_Data,event



DataArray_x=*(*pstate_mddc).DataArray_x

x=DataArray_x[0,*]
y=DataArray_y[0,*]

;print,x[0,*]
;print,'n_elements(x) = ',n_elements(x)

xlo=min(x) & xhi=max(x)
ylo=min(y) & yhi=max(y)
(*pstate_mddc).xlo=xlo
(*pstate_mddc).ylo=ylo
(*pstate_mddc).xhi=xhi
(*pstate_mddc).yhi=yhi

*(*pstate_mddc).x=x
*(*pstate_mddc).y=y
  (*pstate_mddc).xrange = [xlo,xhi]
  (*pstate_mddc).yrange = [ylo,yhi]

ENDELSE
x=reform(x)
y=reform(y)
;help,y
;help,x
;print,total(y)
;print,total(x)
;print,(*pstate_mddc).yrange
;print,(*pstate_mddc).xrange
widget_control,(*pstate_mddc).Diffraction_Result,set_value=0

wset,(*pstate_mddc).windpix_mddc

plot,x,y,xrange = (*pstate_mddc).xrange,yrange =(*pstate_mddc).yrange, $
     xstyle = 1,ystyle = 1,xtitle = 'd-spacing / A', $
     ytitle = 'Intensity', title = 'Diffraction Pattern',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0
wset,(*pstate_mddc).winVis_mddc

device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Diffraction_Result_select,event
widget_control,event.top,get_uvalue = pstate_mddc
 widget_control,(*pstate_mddc).Diffraction_Result,get_value=value
; print,'value = ',value
*(*pstate_mddc).x=(*(*pstate_mddc).DataArray_x)[value,*]
*(*pstate_mddc).y=(*(*pstate_mddc).DataArray_y)[value,*]

;if value le 5 then begin
;theta=82.5-value*15.0
;endif else begin
;theta=7.5+(value-6)*15.0
;endelse
;(*pstate_mddc).theta=theta
;print,'theta = ', theta

constants=(*pstate_mddc).constants
DiffractionAngles=constants.DiffractionAngles
;print,'diffangle = ', DiffractionAngles[value]/2.0
theta=DiffractionAngles[value]/2.0
x=*(*pstate_mddc).x
y=*(*pstate_mddc).y
xlo=min(x) & xhi=max(x)
ylo=min(y) & yhi=max(y)
;print, 'xlo = ', xlo
;print, 'xhi = ', xhi

(*pstate_mddc).xlo=xlo
(*pstate_mddc).ylo=ylo
(*pstate_mddc).xhi=xhi
(*pstate_mddc).yhi=yhi
  (*pstate_mddc).xrange = [xlo,xhi]
  (*pstate_mddc).yrange = [ylo,yhi]

        wset,(*pstate_mddc).windpix_mddc
        MDDCPlot,event
        wset,(*pstate_mddc).winVis_mddc
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]
print,'theta: ',theta
(*pstate_mddc).theta=theta
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calc_DetectorLength,event
widget_control,event.top,get_uvalue = pstate_mddc
constants=(*pstate_mddc).constants
h=constants.h
mn=constants.mn
lDiff=constants.lDiff
theta=(*pstate_mddc).theta
print,'theta: ',theta
widget_control,(*pstate_mddc).Gauss_Fit_Experiment,get_value=d_experiment
widget_control,(*pstate_mddc).Gauss_Fit_Theory,get_value=d_theory
widget_control,(*pstate_mddc).Wrong,get_value=Wrong
;
;d-spacing is inversely proportional to velocity.  First calculate
;the theoretical velocity for the length lDiff
;
v_theory=(h*1e10)/(2.0*mn*d_theory*sin(theta*!DTOR))
v_experiment=(h*1e10)/(2.0*mn*d_experiment*sin(theta*!DTOR))
;
v_ratio=v_experiment/v_theory
;
;if v_ratio deviates from 1, then the length is wrong
;
length=v_ratio*lDiff
;
;correction is length-Ldiff
;


cor=(length-Ldiff)*1e3
;
experimental_angle=2.0*asin(h*1e10/(v_experiment*2.0*mn*d_theory))/!DTOR
;print,'Assuming that the length is correct, the experimental d-spacing corresponds to'
;print,'the angle: ',experimental_angle

if Wrong eq 0 then begin
value=cor
endif else begin
value=experimental_angle
endelse


widget_control,(*pstate_mddc).Length_Adjustment,set_value=value


end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Send_To_AccumulatedTable,event
widget_control,event.top,get_uvalue = pstate_mddc
Table_Contents=(*pstate_mddc).Table_Contents

void=where(Table_Contents ne '',count)
;print,'count = ',count
widget_control,(*pstate_mddc).Length_Adjustment,get_value=cor

Table_Contents[0,count]=cor
(*pstate_mddc).Table_Contents=Table_Contents
widget_control,(*pstate_mddc).Adjustment_Table,set_value=Table_Contents

values=fltarr(count+1)
for i = 0, count do begin
values[i]=float(Table_Contents[0,i])
endfor
;print,values
if count gt 0 then begin
result=moment(values)
widget_control,(*pstate_mddc).Length_Adjustment_average,set_value=result[0]
endif else begin
widget_control,(*pstate_mddc).Length_Adjustment_average,set_value=values[0]
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro AdjustmentTable_Update,event
widget_control,event.top,get_uvalue = pstate_mddc
widget_control,(*pstate_mddc).Adjustment_Table,get_value=Table_Contents
rows=(where(Table_Contents ne '',count))
;print,'rows = ',rows
;print,'count = ',count
Table_Contents_Temp=strarr(1,50)

for i = 0, count-1 do begin
Table_Contents_Temp[0,i]=Table_Contents[0,rows[i]]
endfor
Table_Contents=Table_Contents_Temp
(*pstate_mddc).Table_Contents=Table_Contents
widget_control,(*pstate_mddc).Adjustment_Table,set_value=Table_Contents

values=fltarr(count)
for i = 0, count-1 do begin
values[i]=float(Table_Contents[0,i])
endfor
;print,values
if count gt 1 then begin
result=moment(values)
widget_control,(*pstate_mddc).Length_Adjustment_average,set_value=result[0]
endif else begin
widget_control,(*pstate_mddc).Length_Adjustment_average,set_value=values[0]
endelse
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mddc_password_widget_event,event
widget_control,event.top,get_uvalue = pstate_mddc1
uname=widget_info(event.id,/uname)
case uname of
'pass':    $
begin
        case event.type of
            0: begin            ; Insert Single Character
                (*pstate_mddc1).password += string(event.ch)
            end
            1: begin            ; Insert Multiple Characters
                (*pstate_mddc1).password += event.str
            end
            2: begin            ; Delete Text
                (*pstate_mddc1).password = strmid((*pstate_mddc1).password,0,event.offset)
            end
            3:                  ; Text Selection
        endcase
        len = strlen((*pstate_mddc1).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 (*pstate_mddc1).password eq 'MARSLNS' then begin
widget_control,event.top,/destroy
endif else begin
widget_control, (*pstate_mddc1).password_field,set_value=''
(*pstate_mddc1).password=''
endelse
return
end
'cancel':    $
begin
(*pstate_mddc1).password=''
widget_control,event.top,/destroy
return
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function mddc_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 }
pstate_mddc1 = ptr_new(state1,/no_copy)
widget_control,tlb,set_uvalue = pstate_mddc1
xmanager,'mddc_password_widget',tlb,event_handler = 'mddc_password_widget_event'
password=(*pstate_mddc1).password
ptr_free,pstate_mddc1
return,password
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;pro mddc_password,event
;tlb=event.top
;      daveDeSensitizeButtons,event
;  daveSensitizeButtons,event
;password=mddc_password_widget(group_leader = event.top)
;if password ne 'MARSLNS' then begin
;  daveSensitizeButtons,event

;MDDC_exit,event
;endif else begin
;  daveSensitizeButtons,event
;  endelse

;end


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Clear_Table,event
widget_control,event.top,get_uvalue = pstate_mddc
Table_Contents=strarr(1,50)
widget_control,(*pstate_mddc).Adjustment_Table,set_value=Table_Contents
(*pstate_mddc).Table_Contents=Table_Contents
widget_control,(*pstate_mddc).Length_Adjustment_average,set_value=''

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro choppers,event
widget_control,event.top,get_uvalue = pstate_mddc

if (*pstate_mddc).demo_mddc eq 1 then return
widget_control,(*pstate_mddc).chopperButton,sensitive = 0

widget_control,(*pstate_mddc).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_2=(*pstate_mddc).UnitUser_2
UnitManager=(*pstate_mddc).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_2,ChopperCommand_array[i])
print,'response = ',i,response
print,''
endfor

response=sicsexecute(event,UnitUser_2,'success')
print,'response = ',response
print,''
widget_control,(*pstate_mddc).chopperbutton,sensitive = 1

;response=sicsexecute(event,UnitUser_2,'hm genbin 45000 10 2000')
;print,'response = ',response
;response=sicsexecute(event,UnitUser_2,'hm init')
;print,'response = ',response

;histogram memory

TOF_start=(*pstate_mddc).TOF_start
TOF_step=(*pstate_mddc).TOF_step
notimebin=(*pstate_mddc).notimebin
TimeBinIndices=(*pstate_mddc).TimeBinIndices
TOF_start=strtrim(string(TOF_start),2)
TOF_step=strtrim(string(TOF_step),2)
notimebin=strtrim(string(notimebin),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

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_2,command)
print,'response = ',response



end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MD_ProbeRunstatus,event
widget_control,event.top,get_uvalue = pState_mddc
UnitUser_exe=(*pState_mddc).UnitUser_exe
UnitSpy=(*pState_mddc).UnitSpy


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
widget_control,(*pstate_mddc).BeginRunButton,sensitive = 1
endif else begin
WIDGET_CONTROL, event.TOP, TIMER=10
endelse

;return,response_info

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro BeginRun,event
widget_control,event.top,get_uvalue = pstate_mddc
if (*pstate_mddc).demo_mddc eq 1 then return
widget_control,(*pstate_mddc).BeginRunButton,sensitive = 0
widget_control,(*pstate_mddc).Monitor_counts,get_value=Monitor_counts
UnitUser_exe=(*pstate_mddc).UnitUser_exe


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



BeginRunCommand='scancount monitor '
BeginRunCommand+=strtrim(Monitor_counts)

response=sicsexecute(event,UnitUser_exe,BeginRunCommand,/nowait)
print,'response = ',response
print,''



WIDGET_CONTROL, event.TOP, TIMER=10


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro EndRun,event
widget_control,event.top,get_uvalue = pstate_mddc
if (*pstate_mddc).demo_mddc eq 1 then return
widget_control,(*pstate_mddc).EndRunButton,sensitive = 0
UnitUser_2=(*pstate_mddc).UnitUser_2

EndRunCommand='INT1712 3'
tstart=systime(/seconds)
response=sicsinterrupt(event,UnitUser_2,EndRunCommand)
telapsed=systime(/seconds)-tstart
print,'Time to terminate run = ',telapsed
print,'response = ',response
print,''


widget_control,(*pstate_mddc).EndRunButton,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Connect,event
widget_control,event.top,get_uvalue = pstate_mddc
widget_control,(*pstate_mddc).connectbutton,sensitive = 0
delim=(*pstate_mddc).delim
;
;filename='C:\Documents and Settings\tregenna\My Documents\NIST\DAVE\cvs_nist\dave\programs\auxiliary\PSI\MARS\MarsSICSInfo.txt'

get_lun,UnitUser_2
(*pstate_mddc).UnitUser_2=UnitUser_2
get_lun,UnitUser_exe
(*pstate_mddc).UnitUser_exe=UnitUser_exe
get_lun,UnitSpy
(*pstate_mddc).UnitSpy=UnitSpy
get_lun,UnitManager
(*pstate_mddc).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_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 demonstration mode
print,'Connection Successful'
(*pstate_mddc).demo_mddc=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.')
MDDC_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_mddc).demo_mddc=1
    ENDELSE

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 demonstration mode
print,'Connection Successful'
(*pstate_mddc).demo_mddc=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.')
MDDC_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_mddc).demo_mddc=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_mddc).demo_mddc=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.')
MDDC_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_mddc).demo_mddc=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 demonstration mode
print,'Connection Successful'
(*pstate_mddc).demo_mddc=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.')
MDDC_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_mddc).demo_mddc=1
    ENDELSE

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

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MDDC_NEXUS_Read,event
widget_control,event.top,get_uvalue = pstate_mddc
datDir=(*pState_mddc).datDir
constants=(*pstate_mddc).constants
HP=constants.Histogram_Period

    filename=dialog_pickfile(path=datDir,$
      file='NEXUSDATA.hdf',/read,filter="*.hdf",/fix_filter)

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

handle=0L
;dummy = nxopen(filename,'read',handle)   ;for nidl
dummy = nxopen(filename,'NXACC_READ',handle) ;for napi45
;
;
;-------- get some global attributes
    dummy1 = nxgetattr(handle,'file_time',start_time,typ) ;start time
    dummy2 = nxgetattr(handle,'file_name',FullFileName, typ) ;full file name
    dummy3 = nxgetattr(handle,'owner',owner,typ) ;user name
    ;string: start_time
    ;string: FullFileName
    ;string: owner

;print,'start_time: ',start_time
;print,'FullFileName: ',FullFileName
;print,'owner: ',owner
;err=1
;return

    ;------ open elastic group
    dummy = nxopengroup(handle,'elastic','NXentry')

    dummy = nxopendata(handle,'end_time')
    dummy = nxgetdata(handle,end_time)
    dummy = nxclosedata(handle)
    ;string: end_time
    dummy = nxopendata(handle,'title')
    dummy = nxgetdata(handle,title)
    dummy = nxclosedata(handle)
    ;string: title
    dummy = nxopendata(handle,'unix_start_time')
    dummy = nxgetdata(handle,unix_start_time)
    dummy = nxclosedata(handle)
    ;long: unix_start_time

     ;------ open user group
    dummy = nxopengroup(handle,'user','NXuser')

    dummy = nxopendata(handle,'address')
    dummy = nxgetdata(handle,address)
    dummy = nxclosedata(handle)
    ;string: address
    dummy = nxopendata(handle,'email')
    dummy = nxgetdata(handle,email)
    dummy = nxclosedata(handle)
    ;string: email
    dummy = nxopendata(handle,'telephone_number')
    dummy = nxgetdata(handle,telephone_number)
    dummy = nxclosedata(handle)
    ;string: telephone_number
    dummy = nxclosegroup(handle)

    ;------ open instrument responsible group
    dummy = nxopengroup(handle,'instrumentresponsible','NXuser')
    dummy = nxopendata(handle,'name')
    dummy = nxgetdata(handle,instrumentresponsible)
    dummy = nxclosedata(handle)
    ;string: instrumentresponsible
    dummy = nxclosegroup(handle)

     ;------ open sample group
    dummy = nxopengroup(handle,'sample','NXsample')
    dummy = nxopendata(handle,'environment')
    dummy = nxgetdata(handle,environment)
    dummy = nxclosedata(handle)
    ;string: environment
    dummy = nxopendata(handle,'name')
    dummy = nxgetdata(handle,SampleName)
    dummy = nxclosedata(handle)
    ;string: SampleName
    dummy = nxopendata(handle, 'temperature')

    if dummy then begin
    dummy = nxgetdata(handle, temp)
    dummy = nxclosedata(handle)
    endif else begin
    ;temp_float = opan_Temperature_widget(filename,group_leader = event.top)
    ;temp=MAKE_ARRAY(1, /float, value=temp_float)
    temp=200.0
    endelse
    if temp[0] le 0 then begin
    temp_float = opan_Temperature_widget(filename,group_leader = event.top)
    temp=MAKE_ARRAY(1, /float, value=temp_float)
    endif
    dummy = nxclosegroup(handle)


    ;------ open MARS group
    dummy = nxopengroup(handle,'MARS','NXInstrument')

    ;------ open snail_chopper group
    dummy = nxopengroup(handle,'snail_chopper','NXdisk_chopper')

    dummy = nxopendata(handle,'rotation_speed')
    dummy = nxgetdata(handle,SnailSpeed)
    dummy = nxclosedata(handle)
    ;float: SnailSpeed

    dummy = nxopendata(handle,'phase')
    dummy = nxgetdata(handle,SnailPhase)
    dummy = nxclosedata(handle)
    ;float: SnailPhase
    dummy = nxclosegroup(handle)

    ;------ open rabbit_chopper group
    dummy = nxopengroup(handle,'rabbit_chopper','NXdisk_chopper')

    dummy = nxopendata(handle,'rotation_speed')
    dummy = nxgetdata(handle,RabbitSpeed)
    dummy = nxclosedata(handle)
    ;float: RabbitSpeed

    dummy = nxopendata(handle,'phase')
    dummy = nxgetdata(handle,RabbitPhase)
    dummy = nxclosedata(handle)
    ;float: RabbitPhase
    dummy = nxclosegroup(handle)

    ;------ open master_chopper group
    dummy = nxopengroup(handle,'pulse_producing_chopper','NXdisk_chopper')

    dummy = nxopendata(handle,'rotation_speed')
    dummy = nxgetdata(handle,MasterSpeed)
    dummy = nxclosedata(handle)
    ;float: MasterSpeed

    dummy = nxopendata(handle,'phase')
    dummy = nxgetdata(handle,MasterPhase)
    dummy = nxclosedata(handle)
    ;float: MasterPhase
    dummy = nxclosegroup(handle)

    ;------ open frame1_chopper group
    dummy = nxopengroup(handle,'frame1_chopper','NXdisk_chopper')

    dummy = nxopendata(handle,'rotation_speed')
    dummy = nxgetdata(handle,Chopper4Speed)
    dummy = nxclosedata(handle)
    ;float: Chopper4Speed

    dummy = nxopendata(handle,'phase')
    dummy = nxgetdata(handle,Chopper4Phase)
    dummy = nxclosedata(handle)
    ;float: Chopper4Phase
    dummy = nxclosegroup(handle)

    ;------ open frame2_chopper group
    dummy = nxopengroup(handle,'frame2_chopper','NXdisk_chopper')

    dummy = nxopendata(handle,'rotation_speed')
    dummy = nxgetdata(handle,Chopper5Speed)
    dummy = nxclosedata(handle)
    ;float: Chopper5Speed

    dummy = nxopendata(handle,'phase')
    dummy = nxgetdata(handle,Chopper5Phase)
    dummy = nxclosedata(handle)
    ;float: Chopper5Phase
    dummy = nxclosegroup(handle)

    dummy = nxclosegroup(handle) ;close MARS group


    ;------ open integrated TOF monitor group
    dummy = nxopengroup(handle,'proton_beam_monitor','NXmonitor')
    dummy = nxopendata(handle,'integral')
    dummy = nxgetdata(handle,DataMonitor1)
    dummy = nxclosedata(handle)
    ;long64: DataMonitor1
    dummy = nxclosegroup(handle)

    ;------ open pre-sample TOF monitor group
    dummy = nxopengroup(handle,'pre_sample_monitor','NXmonitor')
    dummy = nxopendata(handle,'time_of_flight')
    dummy = nxgetdata(handle,tof) ; need only get this once as array is common to all detectors
    dummy = nxclosedata(handle)
    ;fltarr tof
    dummy = nxopendata(handle,'data')
    dummy = nxgetdata(handle,DataMonitor2)
    dummy = nxclosedata(handle)
    ;fltarr DataMonitor2
    dummy = nxopendata(handle,'preset')
    dummy = nxgetdata(handle,PresetMonitor2)
    dummy = nxclosedata(handle)
    ;long64 PresetMonitor2
    dummy = nxclosegroup(handle)

    ;------ open post-sample TOF monitor group
    dummy = nxopengroup(handle,'after_sample_monitor','NXmonitor')
    dummy = nxopendata(handle,'data')
    dummy = nxgetdata(handle,DataMonitor3)
    dummy = nxclosedata(handle)
    ;fltarr DataMonitor3
    dummy = nxclosegroup(handle)

    ;------ open elastic bank group
    dummy = nxopengroup(handle,'elastic_bank','NXdata')
    dummy = nxopendata(handle,'data')
    dummy = nxgetdata(handle,DataElastic)
    dummy = nxclosedata(handle)
    ;2dfltarr DataElastic
    dummy = nxopendata(handle,'scattering_angle')
    dummy = nxgetdata(handle,ElasticAngles)
    dummy = nxclosedata(handle)
    ;fltarr ElasticAngles
    dummy = nxclosegroup(handle)

    dummy = nxclosegroup(handle) ; close elastic group

    ;------ open inelastic group
    dummy = nxopengroup(handle,'inelastic','NXentry')

    ;------ open MARS group
    dummy = nxopengroup(handle,'MARS','NXInstrument')

    ;------ open inelastic_bank group
    dummy = nxopengroup(handle,'inelastic_bank','NXdetector')
    dummy = nxopendata(handle,'signal_bins')
    dummy = nxgetdata(handle,TimeBinIndices)
    dummy = nxclosedata(handle)
    ;string TimeBinIndices
    dummy = nxclosegroup(handle)

    ;------ open analyser group
    dummy = nxopengroup(handle,'analyser','NXcrystal')
    dummy = nxopendata(handle,'analyser_angle')
    dummy = nxgetdata(handle,TriffidAngles)
    dummy = nxclosedata(handle)
    ;fltarr TriffidAngles
    dummy = nxopendata(handle,'target_reflection')
    dummy = nxgetdata(handle,targetreflection)
    dummy = nxclosedata(handle)
    ;string: targetreflection

    dummy = nxclosegroup(handle)

    ;------ open inelastic bank group
    dummy = nxopengroup(handle,'inelastic_bank','NXdata')
    dummy = nxopendata(handle,'data')
    dummy = nxgetdata(handle,DataInelastic)
    dummy = nxclosedata(handle)
    ;2dfltarr DataInelastic
    dummy = nxopendata(handle,'scattering_angle')
    dummy = nxgetdata(handle,InelasticAngles)
    dummy = nxclosedata(handle)
    ;fltarr InelasticAngles
    dummy = nxclosegroup(handle)


    dummy = nxclosegroup(handle) ; close inelastic group
    dummy = nxclose(handle) ; close file


masterfundamental=fix(round(MasterSpeed/3000.0))
timeoffsets=(*pState_mddc).timeoffsets
offset=0.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
tof+=offset
;
;help,ElasticAngles
;print,ElasticAngles
;ElasticAngles[4]=45.064
;InelasticAngles=[150.0,120.0,90.0,60.0,30.0,30.0,60.0,90.0,120.0,150.0]

;print,InelasticAngles

;print,'n_elements(tof): ',n_elements(tof)
;err=1
;return
;convert to point data
tof+=(tof[1]-tof[0])/2.0

;

notimebin=n_elements(tof)
DataArray_x=fltarr(12,notimebin)
DataArray_y=fltarr(12,notimebin)
TOFMonitorArray_x=fltarr(notimebin)
TOFMonitorArray_y=fltarr(notimebin)
for i = 0,11 do begin
DataArray_x[i,*]=tof
DataArray_y[i,*]=float(DataElastic[*,i])
endfor
TOFMonitorArray_x=tof
TOFMonitorArray_y=float(DataMonitor2)
TimeBinIndices=strsplit(TimeBinIndices,',',/extract)
TimeBinIndices=fix(TimeBinIndices)
(*pState_mddc).TimeBinIndices=timebinindices
;time bin cull
;diffraction detectors
StartBin=TimeBinIndices[4]
EndBin=TimeBinIndices[5]
IF endbin GT startbin THEN BEGIN
DataArray_x=DataArray_x[*,StartBin:EndBin]
DataArray_y=DataArray_y[*,StartBin:EndBin]
ENDIF ELSE BEGIN
dimensions=size(DataArray_x)
channels=dimensions[2]
width=channels-startbin+endbin+1
firstbit=channels-startbin
secondbit=endbin+1
xdat=fltarr(12,width)
ydat=fltarr(12,width)
xdat[*,0:firstbit-1]=DataArray_x[*,StartBin:channels-1]-HP
ydat[*,0:firstbit-1]=DataArray_y[*,StartBin:channels-1]
xdat[*,firstbit:firstbit+secondbit-1]=DataArray_x[*,0:EndBin]
ydat[*,firstbit:firstbit+secondbit-1]=DataArray_y[*,0:EndBin]
DataArray_x=xdat
DataArray_y=ydat
ENDELSE
;incident monitor
slider=94
StartBin=TimeBinIndices[0]
EndBin=TimeBinIndices[1]
IF endbin GT startbin THEN BEGIN
width=endbin-startbin
newwidth=fix(width*(slider/100.0))
WidthAdjustment=fix((newwidth-width)/2) ;just in case
newstart=startbin-WidthAdjustment
newend=endbin+WidthAdjustment
TOFMonitorArray_x=TOFMonitorArray_x[newstart:newend]
TOFMonitorArray_y=TOFMonitorArray_y[newstart:newend]
ENDIF ELSE BEGIN
channels=notimebin
width=channels-startbin+endbin+1
newwidth=fix(width*(slider/100.0))
WidthAdjustment=fix((newwidth-width)/2) ;just in case
newstart=startbin-WidthAdjustment
newend=endbin+WidthAdjustment
newwidth=channels-newstart+newend+1
firstbit=channels-newstart
secondbit=newend+1
xdat=fltarr(newwidth)
ydat=fltarr(newwidth)
xdat[0:firstbit-1]=TOFMonitorArray_x[newstart:channels-1]-HP
ydat[0:firstbit-1]=TOFMonitorArray_y[newstart:channels-1]
xdat[firstbit:firstbit+secondbit-1]=TOFMonitorArray_x[0:newend]
ydat[firstbit:firstbit+secondbit-1]=TOFMonitorArray_y[0:newend]
TOFMonitorArray_x=xdat
TOFMonitorArray_y=ydat
ENDELSE

;print,'notimebin after cull = ',EndBin-StartBin+1
print,'TimeBinIndices = ',TimeBinIndices


*(*pstate_mddc).DataArray_x=DataArray_x
*(*pstate_mddc).DataArray_y=DataArray_y
*(*pstate_mddc).TOFMonitorArray_x=TOFMonitorArray_x
*(*pstate_mddc).TOFMonitorArray_y=TOFMonitorArray_y


mddc_dspacing,event

DataArray_x=*(*pstate_mddc).DataArray_x
DataArray_y=*(*pstate_mddc).DataArray_y

x=DataArray_x[0,*]
y=DataArray_y[0,*]

;print,x[0,*]
;print,'n_elements(x) = ',n_elements(x)

xlo=min(x) & xhi=max(x)
ylo=min(y) & yhi=max(y)
(*pstate_mddc).xlo=xlo
(*pstate_mddc).ylo=ylo
(*pstate_mddc).xhi=xhi
(*pstate_mddc).yhi=yhi

*(*pstate_mddc).x=x
*(*pstate_mddc).y=y
  (*pstate_mddc).xrange = [xlo,xhi]
  (*pstate_mddc).yrange = [ylo,yhi]


*(*pstate_mddc).DataArray_x=DataArray_x
*(*pstate_mddc).DataArray_y=DataArray_y
*(*pstate_mddc).TOFMonitorArray_x=TOFMonitorArray_x
*(*pstate_mddc).TOFMonitorArray_y=TOFMonitorArray_y

x=reform(x)
y=reform(y)
;help,y
;help,x
;print,total(y)
;print,total(x)
;print,(*pstate_mddc).yrange
;print,(*pstate_mddc).xrange
widget_control,(*pstate_mddc).Diffraction_Result,set_value=0

wset,(*pstate_mddc).windpix_mddc

plot,x,y,xrange = (*pstate_mddc).xrange,yrange =(*pstate_mddc).yrange, $
     xstyle = 1,ystyle = 1,xtitle = 'd-spacing / A', $
     ytitle = 'Intensity', title = 'Diffraction Pattern',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0
wset,(*pstate_mddc).winVis_mddc

device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pstate_mddc).windpix_mddc]


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MDDCEvents,event
widget_control,event.top,get_uvalue = pstate_mddc
  IF (TAG_NAMES(event, /STRUCTURE_NAME) EQ 'WIDGET_TIMER') THEN MD_ProbeRunstatus,event
uname=widget_info(event.id,/uname)
case uname of
'LoadData':    $
begin
Load_Data,event
end
'DiffractionResult':    $
begin
Diffraction_Result_select,event
end
'CalcDetectorLength':    $
begin
Calc_DetectorLength,event
end
'SendToAccumulatedTable':   $
begin
Send_To_AccumulatedTable,event
end
'AdjustmentTable':   $
begin
AdjustmentTable_Update,event
end
'ClearTable':   $
begin
Clear_Table,event
end
'Connect':   $
begin
Connect,event
end
'Choppers':   $
begin
Choppers,event
end
'BeginRun':   $
begin
BeginRun,event
end
'EndRun':   $
begin
EndRun,event
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MDDC, group_leader = group_leader,notify_ids = notify_ids,  $
        register_name = register_name,workDir = workDir, datDir = datDir

;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 = 'MDDC'
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
delim=path_sep()


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
DiffractionAngles=constants.DiffractionAngles
;print,'diffangle = ', DiffractionAngles[value]/2.0
theta=DiffractionAngles[0]/2.0

;theta=82.5
; First get the colors upon entering this program
tvlct,rorig,gorig,borig,/get
device, get_decomposed = old_dc
device,decomposed = 1
colors = hfbs_GetColor(/Load, Start=1)
;       COLOR: A string with the "name" of the color. Valid names are:
;           black
;           magenta
;           cyan
;           yellow
;           green
;           red
;           blue
;           navy
;           pink
;           aqua
;           orchid
;           sky
;           beige
;           charcoal
;           gray
;           white






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


  tlb = widget_base(/col,group_leader = group_leader,title = 'MARS Diffraction Detectors Calibration',mbar=bar)



;
       filebuttons=widget_button(bar,value='File',/menu)
          openplan=widget_button(filebuttons,$
              value='Read Planner File',event_pro='MDDC_planner_Read')
          openfile=widget_button(filebuttons,$
              value='Read NEXUS File',event_pro='MDDC_NEXUS_Read')
          doneb=widget_button(filebuttons,$
              value='EXIT',event_pro='MDDC_exit')

;;
base_upper = widget_base(tlb,/row)
base_middle = widget_base(tlb,/row)
base_lower = widget_base(tlb,/row)
baseu1=widget_base(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]=''
output[0,1]=''
output[0,2]=''
output[0,3]=''
output[0,4]=''
;
output[1,0]=''
output[1,1]=''
output[1,2]=''
output[1,3]=''
output[1,4]=''

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

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

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

void=widget_label(baseu2,value='DIFFRACTION DETECTER d-SPACING')

Diffraction_Column_labels=['Min.','Max.']
Diffraction_names=['15 deg.','45 deg.','75 deg.','105 deg.','135 deg.','165 deg.']
Diffraction_Output=strarr(2,6)
Diffraction_Output[0,0]=''
Diffraction_Output[0,1]=''
Diffraction_Output[0,2]=''
Diffraction_Output[0,3]=''
Diffraction_Output[0,4]=''
Diffraction_Output[0,5]=''
;
;


Diffraction_Table=widget_table(baseu2,column_widths=70,$
       column_labels=Diffraction_column_labels,row_labels=Diffraction_names,xsize=2,ysize=6, $
       value=Diffraction_Output,alignment=0)

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

connectButton = widget_button(baseu3,value = 'Connect to Instrument', uname='Connect')
ChopperButton = widget_button(baseu3,value = 'Chopper Parameters to Instrument', uname='Choppers')
BeginRunButton = widget_button(baseu3,value = 'Begin Calibration Run', uname='BeginRun')
void = widget_button(baseu3,value = 'Load Data', uname='LoadData')
EndRunButton = widget_button(baseu3,value = 'End Calibration Run', uname='EndRun')
Monitor_counts=cw_field(baseu3,/col,title='Monitor Counts for Run Duration',value='100000')

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

Diffraction_Result_Names = ['Aare 165 deg.','Aare 135 deg.','Aare 105 deg.','Aare 75 deg.','Aare 45 deg.', $
    'Aare 15 deg.','Berg 15 deg.','Berg 45 deg.','Berg 75 deg.','Berg 105 deg.','Berg 135 deg.', $
    'Berg 165 deg.']



Diffraction_Result = cw_bgroup(basem1,Diffraction_Result_Names,column=2,/exclusive,label_top = $
'View Result for Diffraction Detector',frame = 1,set_value = 0,/no_release, uname='DiffractionResult')

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



basem2a=widget_base(basem2,/row,/align_center)

basem2a1=widget_base(basem2a,/col,/align_center,/frame)


void=widget_label(basem2a1,value='d-values')


Gauss_Fit_Experiment=cw_field(basem2a1,/col,title='Value from Gaussian Fit',/noedit)
Gauss_Fit_Theory=cw_field(basem2a1,/col,title='Theoretical Value')

basem2a2=widget_base(basem2a,/col,/align_center)


Action_Types = ['Zoom',$
              'Fit']
Action = cw_bgroup(basem2a2,Action_Types,/col,/exclusive,label_top='Mouse Action', $
           set_value = 0,/return_index,/no_release, /frame)


Wrong_Types = ['Length',$
              'Angle']
Wrong = cw_bgroup(basem2a2,Wrong_Types,/col,/exclusive, $
           set_value = 0,/return_index,/no_release, /frame)

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


basem2b1=widget_base(basem2b,/row,/align_center,/frame)

void = widget_button(basem2b1,value = 'Calculate', uname='CalcDetectorLength')

Length_Adjustment=cw_field(basem2b1,/col,title='Length Adjustment (mm) / Angle (deg.)',/noedit)
void = widget_button(basem2b,value = 'Send to Table of Results', uname='SendToAccumulatedTable')

basem3=widget_base(base_middle,/col,/align_center)

Table_Contents=strarr(1,50)

Adjustment_Table=widget_table(basem3,column_widths=110, $
       column_labels=['Accumulated Results'],xsize=1,ysize=50,/editable, $
       alignment=2,value=Table_Contents,scr_ysize=130,uname='AdjustmentTable')

;basem4=widget_base(base_middle,/col,/align_center)

void = widget_button(basem3,value = 'Clear Table', uname='ClearTable')


Length_Adjustment_average=cw_field(basem3,/col,title='Average Adjustment (mm) / Angle (deg)',/noedit)

;quit = widget_button(basem4,value = 'Exit', event_pro ='MDDC_exit')

xsize = 650 & ysize = 350
win = widget_draw(base_lower,xsize = xsize,ysize = ysize,/button_events, $
      event_pro = 'MDDCdraw')

geom = widget_info(base_lower,/geometry)
newxsize = geom.xsize
xsize=newxsize
widget_control,win,draw_xsize = xsize




centertlb,tlb
widget_control,tlb,/realize

widget_control,win,get_value = winVis_mddc
window,/free,/pixmap,xsize = xsize,ysize = ysize
windpix_mddc = !d.window

;!p.charsize = 1.0

xlo=0.0 & xhi=1.0
ylo=0.0 & yhi=1.0

;

;
;
state = { Chopper_Table:Chopper_Table, $
         Diffraction_Table:Diffraction_Table, $
         Diffraction_Output:Diffraction_Output, $
         Diffraction_Result:Diffraction_Result, $
         colors:colors, $
         constants:constants, $
         old_dc:old_dc, $
         windpix_mddc:windpix_mddc, $
         winVis_mddc:winVis_mddc, $
         autoscale:1, $
         xrange:[xlo,xhi], $
         yrange:[ylo,yhi], $
         xrange_fitwindow:[0.0,1.0], $
         yrange_fitwindow:[0.0,1.0], $
         xbox:[xlo,xhi], $
         ybox:[ylo,yhi], $
         mouse:0B, $
         win:win, $
         xlo:xlo, $
         xhi:xhi, $
         ylo:ylo, $
         yhi:yhi, $
         Action:Action, $
         x:ptr_new(/allocate_heap), $
         y:ptr_new(/allocate_heap), $
         DataArray_x:ptr_new(/allocate_heap), $
         DataArray_y:ptr_new(/allocate_heap), $
        TOFMonitorArray_x:ptr_new(/allocate_heap), $
        TOFMonitorArray_y:ptr_new(/allocate_heap), $
         Gauss_Fit_Experiment:Gauss_Fit_Experiment, $
         Gauss_Fit_Theory:Gauss_Fit_Theory, $
         Theta:Theta, $
         Length_Adjustment:Length_Adjustment, $
         Table_Contents:Table_Contents, $
         Adjustment_Table:Adjustment_Table, $
         Length_Adjustment_average:Length_Adjustment_average, $
         demo_mddc:1, $
         UnitUser_2:0, $
         UnitUser_exe:0, $
         UnitSpy:0, $
         UnitManager:0, $
         connectbutton:connectbutton, $
         ChopperButton:ChopperButton, $
         Monitor_counts:Monitor_counts, $
         BeginRunButton:BeginRunButton, $
         EndRunButton:EndRunButton, $
         TOF_start:0.0, $
         TOF_step:0.0, $
         notimebin:0, $
         TimeBinIndices:intarr(14)-1, $
         delim:delim, $
         timeoffsets:timeoffsets, $
         Wrong:Wrong, $
         workDir:workDir, $
         datDir:datDir $
         }


pstate_mddc = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pstate_mddc

daveDeSensitizeButtons,{id:0,top:tlb,handler:1,select:1}
password=mddc_password_widget(group_leader = tlb)
if password ne 'MARSLNS' then begin
MDDC_cleanup,tlb
MDDC_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 = 'MDDCEvents',cleanup= 'MDDC_cleanup'




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