;
; NAME:
; Mag_Workup_MagProp
; DATE of WORKING VERSION: 16 May 2008
;
;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
;
;
;
;
; 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:
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MAG_cleanup,tlb
widget_control,tlb,get_uvalue = pState

wdelete,(*pState).winState.winPix
heap_free,pState

end


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MAG_EXIT,event
widget_control,event.top,/destroy

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Specify_Output_File,event
widget_control,event.top,get_uvalue = pstate

delim=(*pstate).delim
widget_control,(*pstate).Source_File,get_value=Source_File
  if Source_File ne '' then begin
  textLen = strlen(Source_File)
    pos=strpos(Source_File,delim,/reverse_Search)
textLen-=pos
  FileTitle = strmid(Source_File,textLen-2,/reverse_offset)
  dir = strmid(Source_File,0,pos)
    pos=strpos(FileTitle,'.')
FileTitle=strmid(FileTitle,0,pos)
FileTitle+='_Mag.txt'
file = DIALOG_PICKFILE(title = 'Select Output File',file=FileTitle,path=dir)
endif else begin
file = DIALOG_PICKFILE(title = 'Select Output File')
endelse


widget_control,(*pstate).Output_File,set_value=file

END
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Specify_Source_File,event
widget_control,event.top,get_uvalue = pstate

file = DIALOG_PICKFILE(title = 'Select Input File',/read,path=(*pstate).workDir)

widget_control,(*pstate).Source_File,set_value=file

*(*pstate).DataMaskArray=-1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mag_save,event
widget_control,event.top,get_uvalue = pstate

widget_control,(*pstate).SampleMass,get_value=SampleMass
widget_control,(*pstate).MolarMass,get_value=MolarMass
widget_control,(*pstate).FilmMass,get_value=FilmMass
widget_control,(*pstate).DiamagneticChi,get_value=DiamagneticChi
widget_control,(*pstate).Source_File,get_value=Source_File
widget_control,(*pstate).Output_File,get_value=Output_File
widget_control,(*pstate).OutputQuantities,get_value=OutputQuantities
widget_control,(*pstate).SampleHolder,get_value=SampleHolder
widget_control,(*pstate).SampleHolder_Moment,get_value=SampleHolder_Moment
if strlowcase(size(*(*pstate).DiaArray,/tname)) eq 'undefined' then begin
DiaArray=-1
endif else begin
DiaArray=*(*pstate).DiaArray
endelse
if strlowcase(size(*(*pstate).DataMaskArray,/tname)) eq 'undefined' then begin
DataMaskArray=-1
endif else begin
DataMaskArray=*(*pstate).DataMaskArray
endelse

Save_Info = { Source_File:Source_File, $
         Output_File:Output_File, $
         SampleMass:SampleMass, $
         MolarMass:MolarMass, $
         FilmMass:FilmMass, $
         DiamagneticChi:DiamagneticChi, $
         SampleHolder:SampleHolder, $
         SampleHolder_Moment:SampleHolder_Moment, $
         DiaArray:DiaArray, $
         DataMaskArray:DataMaskArray, $
         OutputQuantities:OutputQuantities}


widget_control,(*pstate).Source_File,get_value=Source_File
if Source_File ne '' then begin
delim=(*pstate).delim
    textLen = strlen(Source_File)
    pos=strpos(Source_File,delim,/reverse_Search)
textLen-=pos
  FileTitle = strmid(Source_File,textLen-2,/reverse_offset)
  dir = strmid(Source_File,0,pos)
    pos=strpos(FileTitle,'.')
FileTitle=strmid(FileTitle,0,pos)
FileTitle+='_settings.sav'
filename = DIALOG_PICKFILE(title = 'Save Settings',file=FileTitle,path=dir,/write,filter="*.sav",/fix_filter)
endif else begin
filename = DIALOG_PICKFILE(title = 'Save Settings',/write,filter="*.sav",/fix_filter,path=(*pstate).workdir)
endelse


if filename eq '' then return
save, filename=filename, Save_Info

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mag_restore,event
widget_control,event.top,get_uvalue = pstate

widget_control,(*pstate).Output_File,get_value=Output_File
if Output_File eq '' then begin
filename=dialog_pickfile(/read,filter="*.sav",/fix_filter,path=(*pstate).workdir)
endif else begin
filename=dialog_pickfile(path=Output_File,/read,filter="*.sav",/fix_filter)
endelse
if filename eq '' then return
restore,filename=filename

widget_control,(*pstate).SampleMass,set_value=Save_Info.SampleMass
widget_control,(*pstate).MolarMass,set_value=Save_Info.MolarMass
widget_control,(*pstate).FilmMass,set_value=Save_Info.FilmMass
widget_control,(*pstate).DiamagneticChi,set_value=Save_Info.DiamagneticChi
widget_control,(*pstate).Source_File,set_value=Save_Info.Source_File
widget_control,(*pstate).Output_File,set_value=Save_Info.Output_File
widget_control,(*pstate).OutputQuantities,set_value=Save_Info.OutputQuantities
widget_control,(*pstate).SampleHolder,set_value=Save_Info.SampleHolder
widget_control,(*pstate).SampleHolder_Moment,set_value=Save_Info.SampleHolder_Moment
*(*pstate).DiaArray=Save_Info.DiaArray
*(*pstate).DataMaskArray=Save_Info.DataMaskArray
(*pState).winState.autoscale = 1
MAG_Calculate,event,/create_graph

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MWReset,event
widget_control,event.top,get_uvalue = pState

(*(*pState).DataMaskArray)[*]=1
mag_plotdata,event
widget_control,(*pState).temppurge,set_value = ''

(*pState).winState.autoscale=1
mag_plotdata,event
(*pState).winState.mouse = 0B

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MWremove_detectors,event
widget_control,event.top,get_uvalue = pState
xrangedel=(*pState).winState.xrangedel
yrangedel=(*pState).winState.yrangedel

x=*(*pState).x
y=*(*pState).y

DataMaskArray=*(*pState).DataMaskArray

Newmask=(x ge xrangedel[0]) and $
		(x le xrangedel[1]) and $
		(y ge yrangedel[0]) and $
		(y le yrangedel[1])


DataMaskArray-=Newmask

*(*pState).DataMaskArray=DataMaskArray

wherezero=where(DataMaskArray eq 0,count)
num=n_elements(y)-count
if num eq 0 then begin
MWReset,event
return
endif

n=n_elements(wherezero)
omit=strtrim(string(round(x[wherezero[0]])),2)
for i=1,n-1 do begin
omit=[omit,','+strtrim(string(round(x[wherezero[i]])),2)]
endfor

widget_control,(*pState).temppurge,set_value = omit

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MAG_MouseEvents,event
widget_control,event.top,get_uvalue = pState

if strlowcase(size(*(*pstate).x,/tname)) eq 'undefined' then return

widget_control,(*pState).MouseAction,get_value = val
IF val EQ 0 THEN BEGIN
case event.type of
0:  begin       ; button press
      (*pState).winState.mouse = event.press
      if (*pState).winState.mouse eq 4 then begin
        (*pState).winState.autoscale = 1
        wset,(*pState).winState.winPix
        mag_plotdata,event
        wset,(*pState).winState.winVis
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
      endif
      if (*pState).winState.mouse eq 1 then begin
        (*pState).winState.xbox[0] = event.x
        (*pState).winState.ybox[0] = event.y
        wset,(*pState).winState.winVis
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
        empty
        (*pState).winState.autoscale = 0
        widget_control,(*pState).winState.win,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pState).winState.mouse eq 1 then begin
      xll = (*pState).winState.xbox[0] < (*pState).winState.xbox[1]
      yll = (*pState).winState.ybox[0] < (*pState).winState.ybox[1]
      w = abs((*pState).winState.xbox[1] - (*pState).winState.xbox[0])
      h = abs((*pState).winState.ybox[1] - (*pState).winState.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).winState.xrange = [ll[0],ur[0]]
      (*pState).winState.yrange = [ll[1],ur[1]]
      wset,(*pState).winState.winPix
        mag_plotdata,event
      wset,(*pState).winState.winVis
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
      (*pState).winState.mouse = 0B
;      widget_control,(*pState).winState.win,draw_motion_events = 0
     endif
     if (*pState).winState.mouse eq 4 then begin
      wset,(*pState).winState.winPix
         mag_plotdata,event
      wset,(*pState).winState.winVis
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
      (*pState).winState.mouse = 0B
;      widget_control,(*pState).winState.win,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion

data_coords = convert_coord(event.x,event.y,/device,/to_data)
; Now get the nearest data coordinate
xrange = (*pState).winState.xrange
yrange =  (*pState).winState.yrange
x = (xrange[1]-1) < (data_coords[0] > (xrange[0]))

if strlowcase(size(*(*pstate).DataMaskArray,/tname)) eq 'undefined' then begin
void=min(((*(*pState).x)-x),minx,/abs)
x=(*(*pState).x)[minx]
y=(*(*pState).y)[minx]
endif else begin
wherenotmask=where(*(*pstate).DataMaskArray ne 0, count)
void=min((((*(*pState).x)[wherenotmask])-x),minx,/abs)
x=((*(*pState).x)[wherenotmask])[minx]
y=((*(*pState).y)[wherenotmask])[minx]
endelse

mag_plotdata,event
plots,x,y,psym = 4, thick = 4.0

widget_control,(*pstate).Mouse_x,set_value=x
widget_control,(*pstate).Mouse_y,set_value=y


      if (*pState).winState.mouse eq 1 then begin
       (*pState).winState.xbox[1] = event.x
       (*pState).winState.ybox[1] = event.y
       xc = [(*pState).winState.xbox[0],event.x,event.x,$
             (*pState).winState.xbox[0],$
             (*pState).winState.xbox[0]]
       yc = [(*pState).winState.ybox[0],(*pState).winState.ybox[0],$
             event.y,event.y,$
             (*pState).winState.ybox[0]]
       wset,(*pState).winState.winVis
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
ENDIF ELSE BEGIN
case event.type of
0:  begin       ; button press
      (*pState).winState.mouse = event.press
      if (*pState).winState.mouse eq 4 then begin
        (*pState).winState.autoscale = 1
        wset,(*pState).winState.winPix
        mag_plotdata,event
        wset,(*pState).winState.winVis
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
      endif
      if (*pState).winState.mouse eq 1 then begin
        (*pState).winState.xbox[0] = event.x
        (*pState).winState.ybox[0] = event.y
        wset,(*pState).winState.winVis
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
        empty
        (*pState).winState.autoscale = 0
        widget_control,(*pState).winState.win,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pState).winState.mouse eq 1 then begin
      xll = (*pState).winState.xbox[0] < (*pState).winState.xbox[1]
      yll = (*pState).winState.ybox[0] < (*pState).winState.ybox[1]
      w = abs((*pState).winState.xbox[1] - (*pState).winState.xbox[0])
      h = abs((*pState).winState.ybox[1] - (*pState).winState.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).winState.xrangedel = [ll[0],ur[0]]
      (*pState).winState.yrangedel = [ll[1],ur[1]]


      MWremove_detectors,event
      mag_plotdata,event
      (*pState).winState.mouse = 0B
      ;widget_control,(*pState).winState.win,draw_motion_events = 0

     endif
     if (*pState).winState.mouse eq 4 then begin
      wset,(*pState).winState.winPix
         mag_plotdata,event
      wset,(*pState).winState.winVis
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
      (*pState).winState.mouse = 0B
      widget_control,(*pState).winState.win,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion

      if (*pState).winState.mouse eq 1 then begin
       (*pState).winState.xbox[1] = event.x
       (*pState).winState.ybox[1] = event.y
       xc = [(*pState).winState.xbox[0],event.x,event.x,$
             (*pState).winState.xbox[0],$
             (*pState).winState.xbox[0]]
       yc = [(*pState).winState.ybox[0],(*pState).winState.ybox[0],$
             event.y,event.y,$
             (*pState).winState.ybox[0]]
       wset,(*pState).winState.winVis
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase

ENDELSE

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mag_plotdata,event,to_window = to_window
widget_control,event.top,get_uvalue = pstate

x=*(*pState).x
y=*(*pState).y

x=x[where(*(*pstate).DataMaskArray eq 1)]
y=y[where(*(*pstate).DataMaskArray eq 1)]

if (*pState).winState.autoscale eq 1 then begin
  xlo = min(x, max = xhi)
  ylo = min(y, max = yhi)
  (*pState).winState.xrange = [xlo,xhi]
  (*pState).winState.yrange = [ylo,yhi]
endif

    if NOT keyword_set(to_window) then wset,(*pState).winState.winPix

    plot,x,y,title="Magnetic Data", $
      xrange = (*pstate).winState.xrange,yrange = (*pstate).winState.yrange, $
      xstyle = 1,ystyle = 1,psym=4,xtitle=(*pstate).xtitle,ytitle=(*pstate).ytitle


if NOT keyword_set(to_window) then begin
wset,(*pState).winState.winVis
device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
endif


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function CorrectForSampleHolder,event,moment,field,temperature
widget_control,event.top,get_uvalue = pstate

widget_control,(*pstate).SampleHolder_Moment,get_value=FilmChi

IF FilmChi EQ 'Temp. Dependant' THEN BEGIN

field_SH=reform((*(*pstate).DiaArray)[0,*])
moment_SH=reform((*(*pstate).DiaArray)[1,*])
temperature_SH=reform((*(*pstate).DiaArray)[2,*])


;print,'field_SH ',field_SH
;print,'moment_SH ',moment_SH
;print,'temperature_SH ',temperature_SH


n_temperature=n_elements(temperature)
n_temperature_SH=n_elements(temperature_SH)
ut=1+bytarr(n_temperature)
utSH=1+bytarr(n_temperature_SH)




diff=abs(ut#temperature_SH-temperature#utSH)
;help,diff
;help,temperature
;help,temperature_SH
index_map=intarr(n_temperature)
for i=0,n_temperature-1 do begin
void=min(diff[i,*],ind)
index_map[i]=ind
endfor


for i = 0, n_temperature-1 do begin
FieldFactor=field_SH[index_map[i]]/field[i]
;print,'temperature[i]: ',temperature[i]
;print,'temperature_SH[index_map[i]]: ',temperature_SH[index_map[i]]
;print,'FieldFactor: ',FieldFactor
;print,'moment[i]: ',moment[i]
;print,'moment_SH[index_map[i]]: ',moment_SH[index_map[i]]
moment[i]-=moment_SH[index_map[i]]/FieldFactor
endfor


ENDIF ELSE BEGIN

FilmChi=float(FilmChi[0])
widget_control,(*pstate).FilmMass,get_value=FilmMass
FilmMass=double(FilmMass[0])

Filmmoment=FilmChi*field*FilmMass/1000.0
moment-=Filmmoment
;

ENDELSE

return,moment

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MAG_Calculate,event,create_file=create_file,create_graph=create_graph,Send_MagProp=Send_MagProp
widget_control,event.top,get_uvalue = pstate
msg=''
widget_control,(*pstate).SampleMass,get_value=SampleMass
  if SampleMass eq '' then begin
    msg='Sample Mass Required'
    void = dialog_message(dialog_parent = event.top,/error,msg)
    return
  endif

SampleMass=double(SampleMass[0])
widget_control,(*pstate).MolarMass,get_value=MolarMass
  if MolarMass eq '' then begin
    msg='Molar Mass of Sample Required'
    void = dialog_message(dialog_parent = event.top,/error,msg)
    return
  endif
MolarMass=double(MolarMass[0])
widget_control,(*pstate).DiamagneticChi,get_value=DiamagneticChi
DiamagneticChi=double(DiamagneticChi[0])
widget_control,(*pstate).Source_File,get_value=Source_File
widget_control,(*pstate).Output_File,get_value=Output_File
widget_control,(*pstate).OutputQuantities,get_value=OutputQuantities

;
;read file
data = read_ascii(Source_File,delimiter=',',data_start=31)

;help,data,/struc
;print,data.field01
;return
field = reform(data.field01[2,*])
temperature = reform(data.field01[3,*])
reciprocal_T=1/temperature
moment = reform(data.field01[4,*])
;help,moment
;print,moment
;return
;correct for diamagnetism of sample
diamagnetic_moment=DiamagneticChi*field*SampleMass/(1000.0*MolarMass)
;print,DiamagneticChi
;print,diamagnetic_moment
moment-=diamagnetic_moment
;correct for diamagnetism of film

moment=CorrectForSampleHolder(event,moment,field,temperature)


;calculate chi
MolarMoment=moment*1000.0*MolarMass/SampleMass
Chi=MolarMoment/field
Reciprocal_Chi=1.0/Chi

ChiT=Chi*temperature
u_eff=2.82788*sqrt(ChiT)
Moment=MolarMoment/5584.897346
BoT=field/(temperature*1000.0)
;
;which quantities are to be outputed ?
;
n=n_elements(field)

if strlowcase(size(*(*pstate).DataMaskArray,/tname)) eq 'undefined' then begin
*(*pState).DataMaskArray=bytarr(n)+1
endif
if (*(*pstate).DataMaskArray)[0] eq -1 then begin
*(*pState).DataMaskArray=bytarr(n)+1
endif

;Basic Workup Completed
if keyword_set(create_file) then action = 0
if keyword_set(create_graph) then action = 1
if keyword_set(Send_MagProp) then action = 2

case action of
0:   $
begin
whereone=where(OutputQuantities eq 1, count)

if count eq 0 then return
if count eq 1 then format_float = '(f-12.5)'
if count eq 2 then format_float = '(f-12.5,5x,f-12.5)'
if count eq 3 then format_float = '(f-12.5,5x,f-12.5,5x,f-12.5)'
if count eq 4 then format_float = '(f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5)'
if count eq 5 then format_float = '(f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5)'
if count eq 6 then format_float = '(f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5)'
if count eq 7 then format_float = '(f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5)'
if count eq 8 then format_float = '(f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5)'
if count eq 9 then format_float = '(f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5,5x,f-12.5)'


;OutputQuantities_Field=['ChiT','Chi','1/Chi','u_eff','Moment','T','1/T','B','B/T']


outputlabels=strarr(9)

;outputlabels[0]='ChiT             '
;outputlabels[1]='Chi              '
;outputlabels[2]='1/Chi            '
;outputlabels[3]='u_eff            '
;outputlabels[4]='Moment           '
;outputlabels[5]='T / K            '
;outputlabels[6]='1 / T            '
;outputlabels[7]='B / Tesla        '
;outputlabels[8]='10 * B / T       '


outputlabels[0]='T / K            '
outputlabels[1]='1 / T            '
outputlabels[2]='ChiT             '
outputlabels[3]='Chi              '
outputlabels[4]='1/Chi            '
outputlabels[5]='u_eff            '
outputlabels[6]='Moment           '
outputlabels[7]='10 * B / T       '
outputlabels[8]='B / Gauss        '

string_output=outputlabels[whereone[0]]
for i = 1, count - 1 do begin
string_output+=outputlabels[whereone[i]]
endfor

output_array=fltarr(9,n)

;output_array[0,*]=ChiT
;output_array[1,*]=Chi
;output_array[2,*]=Reciprocal_Chi
;output_array[3,*]=u_eff
;output_array[4,*]=moment
;output_array[5,*]=temperature
;output_array[6,*]=reciprocal_T
;output_array[7,*]=field
;output_array[8,*]=BoT

output_array[0,*]=temperature
output_array[1,*]=reciprocal_T
output_array[2,*]=ChiT
output_array[3,*]=Chi
output_array[4,*]=Reciprocal_Chi
output_array[5,*]=u_eff
output_array[6,*]=moment
output_array[7,*]=BoT
output_array[8,*]=field

openw,lun,Output_File,/get_lun
printf,lun,string_output
for i = 0, n-1 do begin
mask=(*(*pstate).DataMaskArray)[i]
if mask eq 1 then printf,lun,output_array[whereone,i],format = format_float
endfor
free_lun,lun,/force

    msg='Data Have Been Written to Disk'
    void = dialog_message(dialog_parent = event.top,/information,msg)
end
1:   $
begin
outputlabels=strarr(9)
outputlabels[0]='T / K'
outputlabels[1]='1 / T'
outputlabels[2]='ChiT'
outputlabels[3]='Chi'
outputlabels[4]='1/Chi'
outputlabels[5]='u_eff'
outputlabels[6]='Moment'
outputlabels[7]='10 * B / T'
outputlabels[8]='B / Gauss'



widget_control,(*pstate).Abscissa_Quantity,get_value=Abscissa_Quantity
widget_control,(*pstate).Ordinate_Quantity,get_value=Ordinate_Quantity

;['ChiT','Chi','1/Chi' 'u_eff','Moment','T','1/T','B','B/T']
;['T','1/T','ChiT','Chi','1/Chi' 'u_eff','Moment','B/T','B']

;
case Abscissa_Quantity of
0:   $
begin
x=temperature
end
1:   $
begin
x=reciprocal_T
end
2:   $
begin
x=ChiT
end
3:   $
begin
x=Chi
end
4:   $
begin
x=reciprocal_Chi
end
5:   $
begin
x=u_eff
end
6:   $
begin
x=Moment
end
7:   $
begin
x=BoT
end
8:   $
begin
x=field
end
else:
endcase
;
;
case Ordinate_Quantity of
0:   $
begin
y=temperature
end
1:   $
begin
y=reciprocal_T
end
2:   $
begin
y=ChiT
end
3:   $
begin
y=Chi
end
4:   $
begin
y=reciprocal_Chi
end
5:   $
begin
y=u_eff
end
6:   $
begin
y=Moment
end
7:   $
begin
y=BoT
end
8:   $
begin
y=field
end
else:
endcase
;

;wherenotmask=where(*(*pstate).DataMaskArray ne 0, count)
;
;if count ne 0 then begin
;*(*pState).x=x[wherenotmask]
;*(*pState).y=y[wherenotmask]
;endif else begin
;*(*pState).x=x
;*(*pState).y=y
;endelse

*(*pState).x=x
*(*pState).y=y


(*pState).xtitle=outputlabels[Abscissa_Quantity]
(*pState).ytitle=outputlabels[Ordinate_Quantity]

mag_plotdata,event

end
2:   $
begin
widget_control,(*pstate).MagPropQuantities,get_value=MPQ
if (*pstate).MagPropEvent.id eq -1 then return
widget_control,(*pstate).MagPropEvent.top,get_uvalue = pstateMagProp

Quantities=strarr(3)
;


	if MPQ ne 3 then begin
	Quantities[0]='t'
	*(*pstateMagProp).x=temperature[where(*(*pstate).DataMaskArray eq 1)]
		case MPQ of
		0:   $
		begin
		Quantities[1]='chit'
		*(*pstateMagProp).y=Chit[where(*(*pstate).DataMaskArray eq 1)]
		end
		1:   $
		begin
		Quantities[1]='chi'
		*(*pstateMagProp).y=Chi[where(*(*pstate).DataMaskArray eq 1)]
		end
		2:   $
		begin
		Quantities[1]='ueff'
		*(*pstateMagProp).y=u_eff[where(*(*pstate).DataMaskArray eq 1)]
		end
		else:
		endcase
	widget_control,(*pstateMagProp).Graphical_Base_colb,sensitive=1
	widget_control,(*pstateMagProp).ExperimentalQuantityButton,sensitive=1
  widget_control,(*pstateMagProp).SetFieldButton,sensitive=1

	endif else begin
	Quantities[0]='B/T'
    Quantities[1]='Moment'
	x=BoT[where(*(*pstate).DataMaskArray eq 1)]
	y=Moment[where(*(*pstate).DataMaskArray eq 1)]
	;order the arrays in terms of their field values.  This will be essential later
	;
	field=field[where(*(*pstate).DataMaskArray eq 1)]
	temperature=temperature[where(*(*pstate).DataMaskArray eq 1)]
	indices=sort(field)
	y=y[indices]
	x=x[indices]
	field=field[indices]
	temperature=temperature[indices]
	*(*pstateMagProp).x=x
	*(*pstateMagProp).y=y
	*(*pstateMagProp).field=field
	*(*pstateMagProp).temperature=temperature
	;
	widget_control,(*pstateMagProp).SetFieldButton,sensitive=0

	endelse

	(*pstateMagProp).Quantities=Quantities

if (*pstateMagProp).quantities[0] eq 't' then begin
widget_control,(*pstateMagProp).TemperatureRangeButton,sensitive=1
endif else begin
widget_control,(*pstateMagProp).TemperatureRangeButton,sensitive=0
endelse
widget_control,(*pstateMagProp).ErrorBarButton,sensitive=1

*(*pstateMagProp).y_original=*(*pState).y
(*pstateMagProp).DataScaleFactor=1.0
(*pstateMagProp).data=1
(*pstateMagProp).CursorPosition=0
widget_control,(*pstateMagProp).CursorPosition_Type,set_value = 0

*(*pstateMagProp).yt=0

CursorPositionType,(*pstate).MagPropEvent
MagProp_Plot_Experimental_Data,(*pstate).MagPropEvent

end
else:
endcase

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SampleHolder_Handler,event
widget_control,event.top,get_uvalue = pstate
widget_control,(*pstate).SampleHolder,get_value=SampleHolder

case SampleHolder of
0:   $
begin
widget_control,(*pstate).SampleHolder_Moment,set_value=-4.56e-7
widget_control,(*pstate).Input_Base_col3A,sensitive = 0
end
1:   $
begin
widget_control,(*pstate).SampleHolder_Moment,set_value=-5.0e-7
widget_control,(*pstate).Input_Base_col3A,sensitive = 0
end
2:   $
begin
widget_control,(*pstate).SampleHolder_Moment,set_value=''
widget_control,(*pstate).Input_Base_col3A,sensitive = 1
end
else:
endcase

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mag_SaveImage,event,tiff=tiff,jpeg=jpeg,gif=gif
widget_control,event.top,get_uvalue = pState
widget_control,(*pstate).Source_File,get_value=Source_File


delim=(*pstate).delim
if Source_File ne '' then begin
  textLen = strlen(Source_File)
    pos=strpos(Source_File,delim,/reverse_Search)
  directory = strmid(Source_File,0,pos)
endif else begin
directory = 'c:\'
endelse


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

if keyword_set(tiff) then begin
image24=reverse(image24,3)
ok = dialog_write_image(image24,type='tiff',/fix_type,dialog_parent=event.top,path=directory)
endif


if keyword_set(gif) then ok = dialog_write_image(image24,type='gif',/fix_type,dialog_parent=event.top,path=directory)
if keyword_set(jpeg) then ok = dialog_write_image(image24,type='jpeg',/fix_type,dialog_parent=event.top,path=directory)


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


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mag_SavePs,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pstate).Source_File,get_value=Source_File
delim=(*pstate).delim
thisDevice = !d.name
if Source_File ne '' then begin
  textLen = strlen(Source_File)
    pos=strpos(Source_File,delim,/reverse_Search)
  directory = strmid(Source_File,0,pos)
endif else begin
directory = DIALOG_PICKFILE(title = 'Select directory',/directory)
endelse
deviceKeywords = PSConfig(Cancel=canceled,directory = directory,group_leader = event.top)
if canceled ne 1 then begin
  SET_PLOT, 'PS'
  DEVICE, _Extra = deviceKeywords
   mag_PlotData,event,/to_window
  DEVICE, /CLOSE_FILE
  set_plot,thisDevice
endif

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mag_PrintImage,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pstate).Source_File,get_value=Source_File
delim=(*pstate).delim
if Source_File ne '' then begin
  textLen = strlen(Source_File)
    pos=strpos(Source_File,delim,/reverse_Search)
  directory = strmid(Source_File,0,pos)
endif else begin
directory = DIALOG_PICKFILE(title = 'Select directory',/directory)
endelse

thisDevice = !d.name
  SET_PLOT, 'printer',/copy
    result = dialog_printersetup(dialog_parent = event.top)
      if result ne 0 then mag_PlotData,event,/to_window
  DEVICE, /CLOSE
  set_plot,thisDevice

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MW_LaunchHelp,event
widget_control,event.top,get_uvalue = pState
pdf_file = !DAVE_AUXILIARY_DIR+'\PSI\MagProp\SQUIDWorkupHelp.pdf'
void = launch_help(pdf_file,tlb = event.top)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro HolderSquidFile,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pstate).Source_File,get_value=Source_File

delim=(*pstate).delim
if Source_File ne '' then begin
  textLen = strlen(Source_File)
    pos=strpos(Source_File,delim,/reverse_Search)
  directory = strmid(Source_File,0,pos)
endif

filename = DIALOG_PICKFILE(title = 'Enter Raw Squid File of Sample Holder', $
         /read,filter="*.dat",/fix_filter,path=directory)
if filename eq '' then return

data = read_ascii(filename,delimiter=',',data_start=31)


field = reform(data.field01[2,*])
temperature = reform(data.field01[3,*])
moment = reform(data.field01[4,*])
n=n_elements(moment)

DiaArray=fltarr(3,n)

DiaArray[0,*]=field
DiaArray[1,*]=moment
DiaArray[2,*]=temperature

*(*pstate).DiaArray=DiaArray

;print,'field ',field
;print,'moment ',moment
;print,'temperature ',temperature
widget_control,(*pstate).SampleHolder_Moment,set_value='Temp. Dependant'

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MAG_Events,event


   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
msg=strarr(1)
msg[0]='Error Message from IDL: '+!ERROR_STATE.MSG
    void=dialog_message(dialog_parent=event.top,/error,msg)
return
endif


uname=widget_info(event.id,/uname)
case uname of
'Create_File':   $
begin
MAG_Calculate,event,/create_file
end
'Plot_Graph':   $
begin
MAG_Calculate,event,/create_graph
end
'mag_exit':   $
begin
MAG_EXIT,event
end
'Specify_Source_File':    $
begin
Specify_Source_File,event
end
'Specify_Output_File':    $
begin
Specify_Output_File,event
end
'mag_save':    $
begin
mag_save,event
end
'mag_restore':    $
begin
mag_restore,event
end
'SampleHolder_Handler':    $
begin
SampleHolder_Handler,event
end
'Save_jpeg':    $
begin
mag_SaveImage,event,/jpeg
end
'Save_tiff':    $
begin
mag_SaveImage,event,/tiff
end
'Save_gif':    $
begin
mag_SaveImage,event,/gif
end
'Save_ps':    $
begin
mag_SavePs,event
end
'Print_Image':    $
begin
mag_PrintImage,event
end
'SendMagProp':    $
begin
MAG_Calculate,event,/Send_MagProp
end
'LaunchHelp':    $
begin
MW_LaunchHelp,event
end
'RestoreData':    $
begin
MWReset,event
end
'HolderSquidFile':    $
begin
HolderSquidFile,event
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Mag_Workup_MagProp,tlb,group_leader = group_leader,notify_ids = notify_ids,  $
        register_name = register_name,workDir = workDir,ExternalEvent = ExternalEvent, $
        ExternalProgramName=ExternalProgramName

delim=path_sep()
if not keyword_set(workdir) then workdir = 'c:'+delim

if n_elements(group_leader) eq 0 then group_leader = 0L
if n_elements(ExternalProgramName) eq 0 then ExternalProgramName=''
if n_elements(register_name) eq 0 then register_name='Mag_Workup_MagProp'

if xregistered(register_name) then return


if n_elements(ExternalEvent) eq 0 then begin
ExternalEvent={ID:-1}
tlb = widget_base(/row,title = 'Workup of Squid Data',mbar=bar,group_leader = group_leader)
endif else begin

tlb = widget_base(group_leader = group_leader,/row,$
          title = 'Workup of Squid Data Started from '+ExternalProgramName,mbar=bar)
endelse


       filebuttons=widget_button(bar,value='File',/menu)
          save=widget_button(filebuttons,$
              value='Save',uname='mag_save')
          restore=widget_button(filebuttons,$
              value='Restore',uname='mag_restore')
          doneb=widget_button(filebuttons,$
              value='EXIT',uname='mag_exit')
       saveimagebuttons=widget_button(bar,value='Save Image',/menu)
          void=widget_button(saveimagebuttons,$
              value='Save jpeg',uname='Save_jpeg')
          void=widget_button(saveimagebuttons,$
              value='Save gif',uname='Save_gif')
          void=widget_button(saveimagebuttons,$
              value='Save tiff',uname='Save_tiff')
          void=widget_button(saveimagebuttons,$
              value='Save PS',uname='Save_ps')
       printbuttons=widget_button(bar,value='Print Image',/menu)
          void=widget_button(printbuttons,$
              value='Print',uname='Print_Image')
       helpbuttons=widget_button(bar,value='Help',/menu)
          void=widget_button(helpbuttons,$
              value='Launch Help File',uname='LaunchHelp')

BaseLeft=widget_base(tlb,/col)

Input_Base=widget_base(BaseLeft,/col,/align_center)

void = widget_label(Input_Base,value = 'SAMPLE')

Input_Base_row4=widget_base(Input_Base,/row,/frame,/align_center)


SampleMass=cw_field(Input_Base_row4,xsize=21,/col,title='Mass / mg',value='')
MolarMass=cw_field(Input_Base_row4,xsize=21,/col,title='Molar Mass / grams',value='')
DiamagneticChi=cw_field(Input_Base_row4,xsize=21,/col,title='Dia. Sus. / emu per mole',value='')


void = widget_label(Input_Base,value = '')
void = widget_label(Input_Base,value = 'SAMPLE HOLDER')


Input_Base_row3=widget_base(Input_Base,/row,/frame,/align_center)

SampleHolderType_Field=['Saran Film','Gelatine Capsule','User Defined']
SampleHolder = cw_bgroup(Input_Base_row3,SampleHolderType_Field,/row,/exclusive, $
           set_value = 0,/return_index,/no_release,uname='SampleHolder_Handler')

Input_Base_col2A=widget_base(Input_Base_row3,/row)
Input_Base_col3A=widget_base(Input_Base_col2A,/col,sensitive=0)

SampleHolder_Moment=cw_field(Input_Base_col3A,/col, $
                 title='Sus./ emu per gram',value='-4.56e-7',xsize=15)


void = widget_button(Input_Base_row3,value = 'From File', uname='HolderSquidFile')


FilmMass=cw_field(Input_Base_col2A,xsize=8,/col,title='Mass / mg',value='')

Input_Base_row1=widget_base(Input_Base,/row)
Source_File=cw_field(Input_Base_row1,/col,title='Source File',xsize=80,value='')
void = widget_button(Input_Base_row1,value = 'Browse', uname='Specify_Source_File')

Input_Base_row2=widget_base(Input_Base,/row)

Output_File=cw_field(Input_Base_row2,/col,title='Output File',xsize=80,value='')
void = widget_button(Input_Base_row2,value = 'Browse', uname='Specify_Output_File')

Output_Base=widget_base(BaseLeft,/col,/align_center,/frame)

;OutputQuantities_Field=['ChiT','Chi','1/Chi','u_eff','Moment','T','1/T','B','B/T']
OutputQuantities_Field=['T','1/T','ChiT','Chi','1/Chi','u_eff','Moment','B/T','B']

OutputQuantities = cw_bgroup(Output_Base,OutputQuantities_Field,/row, $
          /nonexclusive,label_top='Quantities to be written to output file', $
           set_value = [1,0,1,0,0,0,0,0,0],/return_index,/no_release)

void = widget_button(Output_Base,value = 'Create Output File', uname='Create_File')

void = widget_label(BaseLeft,value=' ')

MagProp_Base=widget_base(BaseLeft,/col,/align_center,/frame)

MagPropQuantities_Field=['ChiT vs. T','Chi vs. T','u_eff vs. T','Moment vs. B/T']

MagPropQuantities = cw_bgroup(MagProp_Base,MagPropQuantities_Field,/row, $
          /exclusive,label_top='Quantity to be sent to MagProp', $
           set_value = 0,/return_index,/no_release)

void = widget_button(MagProp_Base,value = 'Send to MagProp', uname='SendMagProp')

BaseRight=widget_base(tlb,/col)

Graphical_Base=widget_base(BaseRight,/col,/align_center)

Graphical_Base_rowa=widget_base(Graphical_Base,/row,/align_center)


Graphical_Base_cola=widget_base(Graphical_Base_rowa,/col,/align_center)

Ordinate_Quantity = cw_bgroup(Graphical_Base_cola,OutputQuantities_Field,/col, $
          /exclusive,label_top='Ordinate', $
           set_value = 2,/return_index,/no_release,/frame)


Graphical_Base_colb=widget_base(Graphical_Base_rowa,/col,/align_center)


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

xsize = 500 & ysize =xsize/GoldenRatio

win = widget_draw(Graphical_Base_colb,xsize = xsize,ysize = ysize,/button_events,/motion_events, $
      event_pro = 'MAG_MouseEvents')


Graphical_Base_rowb=widget_base(Graphical_Base,/row,/align_center)

void = widget_label(Graphical_Base_cola,value = '')

Graphical_Base_colc=widget_base(Graphical_Base_cola,/col,/align_center,/frame)

void = widget_label(Graphical_Base_colc,value = 'Cursor Position')

Mouse_x=cw_field(Graphical_Base_colc,/col, $
                 title='X co-ordinate',value='',xsize=10,/noedit)

Mouse_y=cw_field(Graphical_Base_colc,/col, $
                 title='Y co-ordinate',value='',xsize=10,/noedit)

Graphical_Base_cold=widget_base(Graphical_Base_colb,/col,/align_center,/frame)


Abscissa_Quantity = cw_bgroup(Graphical_Base_cold,OutputQuantities_Field,/row, $
          /exclusive,label_top='Abscissa', $
           set_value = 0,/return_index,/no_release,/frame)

void = widget_button(Graphical_Base_cold,value = 'Plot Graph', uname='Plot_Graph')

void = widget_label(Graphical_Base_colb,value = '')

Graphical_Base_rowc=widget_base(Graphical_Base_colb,/row,/align_center,/frame)


;Graphical_Base_cole=widget_base(Graphical_Base_rowc,/row,/align_center,/frame)

;void = widget_label(Graphical_Base_cole,value = 'Mouse Action')


MouseAction_Field=['Zoom','Purge']

MouseAction = cw_bgroup(Graphical_Base_rowc,MouseAction_Field,/row, $
          /exclusive,label_top='Mouse Action', $
           set_value = 0,/return_index,/no_release,/frame)


TempPurge=cw_field(Graphical_Base_rowc,/col, $
                 title='X Vals. of Purged Data',value='',xsize=10,/noedit)

void = widget_button(Graphical_Base_rowc,value = 'Restore Original Data', uname='RestoreData')


centertlb,tlb
widget_control,tlb,/realize

widget_control,win,get_value = winVis
window,/free,/pixmap,xsize = xsize,ysize = ysize
winPix = !d.window


; Define winState

winState={$
         win:win, $
         winVis:winVis, $
         winPix:winPix, $
         mouse:0B, $
         xbox:[0.0,0.0], $
         ybox:[0.0,0.0], $
         xrangedel:[0.0,1.0], $
         yrangedel:[0.0,1.0], $
         autoscale:1, $
         xrange:[0.0,1.0], $
         yrange:[0.0,1.0]}


state = { Source_File:Source_File, $
         Output_File:Output_File, $
         workDir:workDir, $
         SampleMass:SampleMass, $
         winState:winState, $
         MolarMass:MolarMass, $
         FilmMass:FilmMass, $
         SampleHolder:SampleHolder, $
         SampleHolder_Moment:SampleHolder_Moment, $
         DiamagneticChi:DiamagneticChi, $
         Input_Base_col3A:Input_Base_col3A, $
         Ordinate_Quantity:Ordinate_Quantity, $
         Abscissa_Quantity:Abscissa_Quantity, $
         Mouse_x:Mouse_x, $
         Mouse_y:Mouse_y, $
         x:ptr_new(/allocate_heap), $
         y:ptr_new(/allocate_heap), $
         DataMaskArray:ptr_new(/allocate_heap), $
         xtitle:'', $
         ytitle:'', $
         MouseAction:MouseAction, $
         TempPurge:TempPurge, $
         delim:delim, $
         DiaArray:ptr_new(/allocate_heap), $
         MagPropEvent:ExternalEvent, $
         MagPropQuantities:MagPropQuantities, $
         OutputQuantities:OutputQuantities}


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


xmanager,'MAG',tlb,event_handler = 'MAG_Events',cleanup= 'MAG_cleanup'


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