;
; NAME:
; MarsProp
; DATE of WORKING VERSION:14 June 2007
;
;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 MagProp_exit,event
widget_control,event.top,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagProp_cleanup,tlb
widget_control,tlb,get_uvalue = pState
wdelete,(*pState).winState.winPix
device, decomposed = (*pState).old_dc
if xregistered('HamiltonianGenerator') ne 0 then begin
widget_control,(*pState).HamGenTlb,get_uvalue = pStateHamGen
heap_free,pStateHamGen
endif
if xregistered('Mag_Workup_MagProp') ne 0 then begin
widget_control,(*pState).MagWorkupTlb,get_uvalue = MagWorkupTlb
heap_free,MagWorkupTlb
endif

heap_free,pState
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro LigfieldMatrixDetails_Events,event
widget_control,event.top,get_uvalue = pState
uname=widget_info(event.id,/uname)
case uname of
'LigfieldMatrixDetailsAccept':    $
begin
n=n_elements((*pstate).MatrixNames)
for i=0,n-1 do begin
;print,'reached here'

widget_control,(*pstate).Fieldstruc.(i),get_value=MatrixName
widget_control,(*pstate).TypeStruc.(i),get_value=Des
widget_control,(*pstate).Valuestruc.(i),get_value=Value
(*pstate).MatrixNames[i]=MatrixName
(*pstate).Type[i]=Des
(*pstate).InitialValues[i]=Value
endfor
(*pstate).cancel=0
widget_control,event.top,/destroy
return
end
'LigfieldMatrixDetailsCancel':    $
begin
widget_control,event.top,/destroy
return
end
else:
endcase

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro LigfieldMatrixDetails,MatrixNames,Type,InitialValues,cancel,main_event
;
wheremyx=where(MatrixNames eq 'my_x',count)
if count ne 0 then begin
Type[wheremyx[0]]=1
InitialValues[wheremyx[0]]=strtrim('1',2)
endif
wheremyy=where(MatrixNames eq 'my_y',count)
if count ne 0 then begin
Type[wheremyy[0]]=2
InitialValues[wheremyy[0]]=strtrim('1',2)
endif
wheremyz=where(MatrixNames eq 'my_z',count)
if count ne 0 then begin
Type[wheremyz[0]]=3
InitialValues[wheremyz[0]]=strtrim('1',2)
endif
;
whereSx=where(MatrixNames eq 'Sx',count)
if count ne 0 then begin
Type[whereSx[0]]=1
InitialValues[whereSx[0]]=strtrim('2.0023',2)
endif
whereSy=where(MatrixNames eq 'Sy',count)
if count ne 0 then begin
Type[whereSy[0]]=2
InitialValues[whereSy[0]]=strtrim('2.0023',2)
endif
whereSz=where(MatrixNames eq 'Sz',count)
if count ne 0 then begin
Type[whereSz[0]]=3
InitialValues[whereSz[0]]=strtrim('2.0023',2)
endif
;
whereLx=where(MatrixNames eq 'Lx',count)
if count ne 0 then begin
Type[whereLx[0]]=1
InitialValues[whereLx[0]]=strtrim('1',2)
endif
whereLy=where(MatrixNames eq 'Ly',count)
if count ne 0 then begin
Type[whereLy[0]]=2
InitialValues[whereLy[0]]=strtrim('1',2)
endif
whereLz=where(MatrixNames eq 'Lz',count)
if count ne 0 then begin
Type[whereLz[0]]=3
InitialValues[whereLz[0]]=strtrim('1',2)
endif
;
geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Ligfield Matrices',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/align_center,/modal)
space='                                                  '
void=widget_text(tlb,value='          Designation'+space+'Type'+space+'Value')
n=n_elements(MatrixNames)
suffix=strtrim(string(0),2)
Basestruc=create_struct('Base'+suffix,0L)
Fieldstruc=create_struct('Field'+suffix,0L)
TypeStruc=create_struct('Type'+suffix,0L)
Valuestruc=create_struct('Value'+suffix,0L)

if n gt 1 then begin
    for i = 1, n-1 do begin
    suffix=strtrim(string(i),2)
    Basestruc=create_struct(Basestruc,'Base'+suffix,0L)
    Fieldstruc=create_struct(Fieldstruc,'Field'+suffix,0L)
    TypeStruc=create_struct(TypeStruc,'Type'+suffix,0L)
    Valuestruc=create_struct(Valuestruc,'Value'+suffix,0L)
    endfor
endif

TypeStrucNames=['Parameter','Bx','By','Bz']
for i = 0, n-1 do begin
Basestruc.(i)=widget_base(tlb,/row,/align_center)
Fieldstruc.(i)=cw_field(Basestruc.(i),/col,title='', $
       value=MatrixNames[i])
TypeStruc.(i) = cw_bgroup(Basestruc.(i),TypeStrucNames,/row,/exclusive,$
            frame = 1,set_value = Type[i])
Valuestruc.(i)=cw_field(Basestruc.(i),/col,title='', $
       value=InitialValues[i])
endfor


void = widget_button(tlb,value = 'Accept', uname='LigfieldMatrixDetailsAccept')
void = widget_button(tlb,value = 'Cancel', uname='LigfieldMatrixDetailsCancel')


state={Fieldstruc:Fieldstruc, $
       TypeStruc:TypeStruc, $
       Valuestruc:Valuestruc, $
       MatrixNames:MatrixNames, $
       Type:Type, $
       cancel:1, $
       InitialValues:InitialValues}

widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'LigfieldMatrixDetails',tlb,event_handler = 'LigfieldMatrixDetails_Events' ;register with the xmanager

MatrixNames=(*pstate).MatrixNames
Type=(*pstate).Type
InitialValues=(*pstate).InitialValues
cancel=(*pstate).cancel
ptr_free,pState

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro OneEle,matrix,entry,imagin=imagin
rowindex=0
colindex=0
element=double(0.0)
reads,entry,rowindex,colindex,element
rowindex-=1
colindex-=1
matrix[colindex,rowindex]=element
if keyword_set(imagin) then begin
matrix[rowindex,colindex]=-element
endif else begin
matrix[rowindex,colindex]=element
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TwoEle,matrix,entry,imagin=imagin
rowindex1=0
colindex1=0
rowindex2=0
colindex2=0
element1=double(0.0)
element2=double(0.0)
reads,entry,rowindex1,colindex1,element1,rowindex2,colindex2,element2
rowindex1-=1
colindex1-=1
rowindex2-=1
colindex2-=1
matrix[colindex1,rowindex1]=element1
matrix[colindex2,rowindex2]=element2
if keyword_set(imagin) then begin
matrix[rowindex1,colindex1]=-element1
matrix[rowindex2,colindex2]=-element2
endif else begin
matrix[rowindex1,colindex1]=element1
matrix[rowindex2,colindex2]=element2
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ThreeEle,matrix,entry,imagin=imagin
;print,'entry: ',entry
rowindex1=0
colindex1=0
rowindex2=0
colindex2=0
rowindex3=0
colindex3=0
element1=double(0.0)
element2=double(0.0)
element3=double(0.0)
reads,entry,rowindex1,colindex1,element1,rowindex2,colindex2,element2,rowindex3,colindex3,element3
rowindex1-=1
colindex1-=1
rowindex2-=1
colindex2-=1
rowindex3-=1
colindex3-=1
matrix[colindex1,rowindex1]=element1
matrix[colindex2,rowindex2]=element2
matrix[colindex3,rowindex3]=element3
if keyword_set(imagin) then begin
matrix[rowindex1,colindex1]=-element1
matrix[rowindex2,colindex2]=-element2
matrix[rowindex3,colindex3]=-element3
endif else begin
matrix[rowindex1,colindex1]=element1
matrix[rowindex2,colindex2]=element2
matrix[rowindex3,colindex3]=element3
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function Read_Jesper,filename,main_event


CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
LigFieldFileStruc={fail:1}
return,LigFieldFileStruc
endif


line=''
nlines=file_lines(filename)
str=strarr(nlines)
openr,lun,filename,/get_lun
for i = 0, nlines-1 do begin
readf,lun,line
str[i]=strtrim(line)
endfor
free_lun,lun,/force
;
;if the history file has been included by mistake then get rid of it.

;print,'First str'
;print,str[nlines-10:*]
;print,' '
;void=strpos(str, 'The history')
;historyPos=where(void ne -1,count)
;if count ne 0 then begin
;str=str[0:historyPos[0]-1]
;nlines=n_elements(str)
;endif
;print,'Second str'
;print,str[nlines-10:*]
;print,'n_elements(str): ',n_elements(str)
;
;;
;openw,lun,'C:\woof.txt',/get_lun
;for i = 0, nlines-1 do begin
;printf,lun,str[i]
;endfor
;free_lun,lun,/force





;How many matrix files are there?
NewFileCharacter='--'
void=strpos(str, NewFileCharacter)
MatrixNamePos=where(void ne -1,n_Names)
;print,MatrixNamePos
;print,n_Names
if n_Names ne 0 then begin ;
character=NewFileCharacter
endif else begin
character='Ä'
void=strpos(str, Character)
index=where(void ne -1)
crop=str[index] ;contains a lot of junk

void=strpos(crop, 'Ú' )
index=where(void eq -1)
crop=crop[index]
;
void=strpos(crop, '¿' )
index=where(void eq -1)
crop=crop[index]
;
void=strpos(crop, 'À' )
index=where(void eq -1)
crop=crop[index]
;
void=strpos(crop, 'Ù' )
index=where(void eq -1)
crop=crop[index]
;
void=strpos(crop, 'Ã' )
index=where(void eq -1)
crop=crop[index]
;
void=strpos(crop, '´' )
index=where(void eq -1,n_crop)
crop=crop[index]


    for i = 0, n_crop-1 do begin
    wherecrop=where(crop[i] eq str)
       if i eq 0 then begin
       MatrixNamePos = wherecrop[0]
       endif else begin
       MatrixNamePos=[MatrixNamePos,wherecrop[0]]
       endelse
    endfor
    n_Names=n_crop
endelse
MatrixNames=strarr(n_Names)
for i = 0, n_Names-1 do begin
;print,str[MatrixNamePos[i]]
MatrixNames[i]=strtrim(strsplit(str[MatrixNamePos[i]],character,/extract),2)
;print,MatrixNames[i]
endfor
;
;
wherespin=where(MatrixNames eq 'Spin',count)
if count ne 0 then begin
MatrixNames[wherespin]='Spin_Orbit_Coupling'
endif

wherespin=where(MatrixNames eq 'Spin-orbit coupling',count)
if count ne 0 then begin
MatrixNames[wherespin]='Spin_Orbit_Coupling'
endif

;
;the matrix names must be valid structure tags
for i = 0, n_Names-1 do begin
whereillegal=strpos(MatrixNames[i],'(')
if whereillegal[0] ne -1 then begin
components=strtrim(strsplit(MatrixNames[i],'(',/extract),2)
newname=strjoin(components,'_')
MatrixNames[i]=newname
endif
;
whereillegal=strpos(MatrixNames[i],')')
if whereillegal[0] ne -1 then begin
components=strtrim(strsplit(MatrixNames[i],')',/extract),2)
newname=strjoin(components)
MatrixNames[i]=newname
endif
;
whereillegal=strpos(MatrixNames[i],'[')
if whereillegal[0] ne -1 then begin
components=strtrim(strsplit(MatrixNames[i],'[',/extract),2)
newname=strjoin(components)
MatrixNames[i]=newname
endif
;
whereillegal=strpos(MatrixNames[i],']')
if whereillegal[0] ne -1 then begin
components=strtrim(strsplit(MatrixNames[i],']',/extract),2)
newname=strjoin(components)
MatrixNames[i]=newname
endif
;
whereillegal=strpos(MatrixNames[i],'{')
if whereillegal[0] ne -1 then begin
components=strtrim(strsplit(MatrixNames[i],'{',/extract),2)
newname=strjoin(components)
MatrixNames[i]=newname
endif
;
whereillegal=strpos(MatrixNames[i],'}')
if whereillegal[0] ne -1 then begin
components=strtrim(strsplit(MatrixNames[i],'}',/extract),2)
newname=strjoin(components)
MatrixNames[i]=newname
endif
;
whereillegal=strpos(MatrixNames[i],'.')
if whereillegal[0] ne -1 then begin
components=strtrim(strsplit(MatrixNames[i],'.',/extract),2)
newname=strjoin(components)
MatrixNames[i]=newname
endif
;
whereillegal=strpos(MatrixNames[i],'-')
if whereillegal[0] ne -1 then begin
components=strtrim(strsplit(MatrixNames[i],'-',/extract),2)
newname=strjoin(components)
MatrixNames[i]=newname
endif
;
whereillegal=strpos(MatrixNames[i],' ') ;not illegal but good to remove at this stage
if whereillegal[0] ne -1 then begin
components=strtrim(strsplit(MatrixNames[i],' ',/extract),2)
newname=strjoin(components,'_')
MatrixNames[i]=newname
endif
endfor

DodgyCharacters=['å','ã','æ']
ReplacementCharacters=['sigma','pi','my']

for i = 0, n_Names-1 do begin
    for j = 0, 2 do begin
    DodgyCharacter=DodgyCharacters[j]
    wheredodgy=strpos(MatrixNames[i],DodgyCharacter)
    if wheredodgy[0] ne -1 then begin
    components=strtrim(strsplit(MatrixNames[i],DodgyCharacter,/extract),2)
    newname=strjoin(components,ReplacementCharacters[j])
       if j eq 2 then    newname='my_'+newname
    MatrixNames[i]=newname
    endif
    endfor
endfor



;print,'MatrixNames: ',MatrixNames

LineLengths=[23,47,71]
;if character eq NewFileCharacter then begin
;LineLengths=[23,47,71]
;endif else begin
;LineLengths=[24,48,72]
;endelse

;determine matrix dimension
wherethree=where(strlen(str) eq LineLengths[2], count3)
wheretwo=where(strlen(str) eq LineLengths[1], count2)
whereone=where(strlen(str) eq LineLengths[0], count1)

;print,'whereone: ',whereone
;print,'wheretwo: ',wheretwo
;print,'wherethree: ',wherethree


vowels=['a','e','i','o','u']

if count1 ne 0 then begin
WhereOneString=str[whereone]
    for i = 0, 4 do begin
    void=strpos(WhereOneString, vowels[i])
    whereNoVowel=where(void eq -1,count)
    if count ne 0 then WhereOneString=WhereOneString[whereNoVowel]
    count1 = count
    endfor
endif
;
if count2 ne 0 then begin
WhereTwoString=str[wheretwo]
    for i = 0, 4 do begin
    void=strpos(WhereTwoString, vowels[i])
    whereNoVowel=where(void eq -1,count)
    if count ne 0 then WhereTwoString=WhereTwoString[whereNoVowel]
    count2 = count
    endfor
endif
;
if count3 ne 0 then begin
WhereThreeString=str[wherethree]
    for i = 0, 4 do begin
    void=strpos(WhereThreeString, vowels[i])
    whereNoVowel=where(void eq -1,count)
    if count ne 0 then WhereThreeString=WhereThreeString[whereNoVowel]
    count3 = count
    endfor
endif
;

;print,'WhereOneString ',WhereOneString
;print,'WhereTwoString ',WhereTwoString
;print,'WhereThreeString ',WhereThreeString

MatrixDimension=0

;print,'count1 ',count1
;print,'count2 ',count2
;print,'count3 ',count3
;help,str
;
if count1 ne 0 then begin
iar=intarr(2)
i1=0
i2=0
void=0.0
    for i = 0, count1-1 do begin
    reads,WhereOneString[i],i1,i2,void
    iar[0]=i1
    iar[1]=i2
    maxint=max(iar)
    if MatrixDimension lt maxint then  MatrixDimension = maxint
    endfor
endif
;
if count2 ne 0 then begin
iar=intarr(4)
i1=0
i2=0
i3=0
i4=0
void1=0.0
void2=0.0
    for i = 0, count2-1 do begin
;   print, 'WhereTwoString ',WhereTwoString[i]
    reads,WhereTwoString[i],i1,i2,void1,i3,i4,void2
    iar[0]=i1
    iar[1]=i2
    iar[2]=i3
    iar[3]=i4
    maxint=max(iar)
    if MatrixDimension lt maxint then  MatrixDimension = maxint
    endfor
endif
;
if count3 ne 0 then begin
iar=intarr(6)
i1=0
i2=0
i3=0
i4=0
i5=0
i6=0
void1=0.0
void2=0.0
void3=0.0
    for i = 0, count3-1 do begin
    reads,WhereThreeString[i],i1,i2,void1,i3,i4,void2,i5,i6,void3
    iar[0]=i1
    iar[1]=i2
    iar[2]=i3
    iar[3]=i4
    iar[4]=i5
    iar[5]=i6
    maxint=max(iar)
    if MatrixDimension lt maxint then  MatrixDimension = maxint
    endfor
endif
;print,'MatrixDimension ',MatrixDimension
;At this point the user should have the opportunity to
;change the names of the matrix files and ammend the
;matrix dimension, and specify the Zeeman files
InitialValues=fltarr(n_Names)
Type=intarr(n_Names)
cancel=1
LigfieldMatrixDetails,MatrixNames,Type,InitialValues,cancel,main_event
if cancel eq 1 then begin
LigFieldFileStruc={fail:2}
return,LigFieldFileStruc
endif
;Print,'MatrixNames: ',MatrixNames
;Print,'Type: ',Type
;Print,'InitialValues: ',InitialValues
;
;Read in the matrix files
;
n=n_elements(MatrixNames)
Matrices=dcomplexarr(n,MatrixDimension,MatrixDimension)
;
FOR J = 0, n-1 DO BEGIN
realpart=dblarr(MatrixDimension,MatrixDimension)
imaginarypart=dblarr(MatrixDimension,MatrixDimension)
;
;
;
i=MatrixNamePos[j]
i+=6
if str[i] eq '' then i+=1
;print,'FirstEntry: ',str[i]
valid=4
while valid ne 0 do begin
entry=str[i]
;if j eq 0 then print,'entry ',entry
EntryLength=strlen(entry)
;print,'EntryLength ',EntryLength 
whereentry=where(EntryLength eq LineLengths,valid)
;if (valid eq -1) and (j eq 0) then print,'entry ',entry
;if (j eq 0) then print,'whereentry ',whereentry
    if valid ne 0 then begin
       if whereentry[0] eq 0 then OneEle,realpart,entry
       if whereentry[0] eq 1 then TwoEle,realpart,entry
       if whereentry[0] eq 2 then ThreeEle,realpart,entry
    i+=1
    endif
endwhile

;if j eq 0 then begin
;wherenezero = where(realpart ne 0.0,woof)
;print,'woof ',woof
;print,'realpart[wherenezero] ',realpart[wherenezero]
;endif
;

 i+=5
;print,'FirstEntry: ',str[i]
if str[i] eq '' then i+=1

valid=4
while valid ne 0 do begin
entry=str[i]
;if j eq 0 then print,'entry ',entry
EntryLength=strlen(entry)
whereentry=where(EntryLength eq LineLengths,valid)
;if (valid eq -1) and (j eq 0) then print,'entry ',entry
;if (valid eq 0) and (j eq 0) then print,'entry ',entry
    if valid ne 0 then begin
       if whereentry[0] eq 0 then OneEle,imaginarypart,entry,/imagin
       if whereentry[0] eq 1 then TwoEle,imaginarypart,entry,/imagin
       if whereentry[0] eq 2 then ThreeEle,imaginarypart,entry,/imagin
    i+=1
    endif
endwhile

;if j eq 0 then begin
;wherenezero = where(imaginarypart ne 0.0,woof)
;print,'woof ',woof
;print,'imaginarypart[wherenezero] ',imaginarypart[wherenezero]
;endif


;
Matrices[j,*,*]=complex(realpart,imaginarypart)

;if j eq 0 then begin
;for q = 0,119 do begin
;for w = 0,119 do begin
;diff = reform(imaginary(Matrices[0,q,w]))+reform(imaginary(Matrices[0,w,q]))
;if diff ne 0 then begin
;print,'q',q
;print,'w',w
;print,'reform(imaginary(Matrices[0,q,w]))',reform(imaginary(Matrices[0,q,w]))
;print,'reform(imaginary(Matrices[0,w,q]))',reform(imaginary(Matrices[0,w,q]))
;endif
;
;endfor
;endfor
;wherenezero = where(imaginarypart ne 0.0,woof)
;print,'woof ',woof
;print,'imaginarypart[wherenezero] ',imaginarypart[wherenezero]
;endif

ENDFOR





;for q= 0,119 do begin
;print,'reform(Matrices[0,q,q]) ',reform(Matrices[0,q,q])
;endfor
LigFieldFileStruc={fail:0, $
              Matrices:Matrices, $
              MatrixNames:MatrixNames, $
              Type:Type, $
              MatrixDimension:MatrixDimension, $
              InitialValues:InitialValues}
return,LigFieldFileStruc
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagProp_ReadAscii_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
case uname of
'Specify_Source_File':    $
begin
Source_Dir=(*pstate1).Source_Dir
delim=(*pstate1).delim
file = DIALOG_PICKFILE(title = 'Select Input File',/read,path=Source_Dir)
  if file ne '' then begin
  textLen = strlen(file)
    pos=strpos(file,delim,/reverse_Search)
textLen-=pos
  FileTitle = strmid(file,textLen-2,/reverse_offset)
    endif else begin
    return
    endelse
widget_control,(*pstate).Source_File,set_value=FileTitle
(*pstate1).Source_File=FileTitle
(*pstate1).file=file
end
'Read_Experimental_Data':    $
begin
file=(*pstate1).file
widget_control,(*pstate).Source_File,get_value=Source_File
(*pstate1).Source_File=Source_File
Source_Dir=(*pstate1).Source_Dir

if file eq '' then begin
widget_control,(*pstate).Source_File,get_value=Source_File
Source_Dir=(*pstate1).Source_Dir
file=Source_Dir+Source_File
endif

if file eq Source_Dir then return
(*pstate1).file=file
if file_test(file) eq 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The file '+file+' is not valid')
return
endif

line=''
LinesToSkip=0
    finished=0
    openr,lun,file,/get_lun
    while finished eq 0 do begin
    readf,lun,line
    if (strpos(line, '/'))[0] ne -1 and $
    (strpos(strlowcase(line), 't'))[0] ne -1 or $
    (strpos(strlowcase(line), 'a'))[0] ne -1 or $
    (strpos(strlowcase(line), 'e'))[0] ne -1 or $
    (strpos(strlowcase(line), 'i'))[0] ne -1 or $
    (strpos(strlowcase(line), 'o'))[0] ne -1 or $
    (strpos(strlowcase(line), 'u'))[0] ne -1 then begin
    LinesToSkip+=1
    endif else begin
    finished=1
    endelse
    endwhile
    free_lun,lun,/force

;print,'LinesToSkip ', LinesToSkip


data = read_ascii(file,DATA_START=LinesToSkip)

;help,data
;help,data,/struc

;ChiT = reform(data.field1[0,*])
;temperature = reform(data.field1[1,*])
;x=temperature
;y=ChiT
;*(*pState).x=x
;*(*pState).y=y
;return

column_num=(size(data.field1))[1]
Quantities=strarr(3)
;print,'(*pState1).Quantities1: ',(*pState).Quantities
DefineQuantities,main_event,column_num,Quantities
;print,'Quantities: ',Quantities
;print,'(*pState1).Quantities1: ',(*pState1).Quantities
if Quantities[0] eq '' then return
if column_num eq 2 then begin
;rearrange
wheret=where(Quantities eq 't')
*(*pState1).x = reform(data.field1[wheret,*]) ;temperature
    if wheret eq 0 then begin
    wheremag = 1
    endif else begin
    wheremag=0
    endelse
*(*pState1).y=reform(data.field1[wheremag,*])
Quantities[1]=Quantities[wheremag]
Quantities[0]='t'
widget_control,(*pstate1).Graphical_Base_colb,sensitive=1
widget_control,(*pstate1).ExperimentalQuantityButton,sensitive=1
widget_control,(*pstate1).SetFieldButton,sensitive=1


endif else begin
wheret=where(Quantities eq 't')
wheremom=where(Quantities eq 'mom')
whereb=where(Quantities eq 'b')
;
;
;
y=reform(data.field1[wheremom,*])
x=reform(data.field1[whereb,*])/(reform(data.field1[wheret,*])*1e3)
field=reform(data.field1[whereb,*])
temperature=reform(data.field1[wheret,*])
;
;order the arrays in terms of their field values.  This will be essential later
;
indices=sort(field)
y=y[indices]
x=x[indices]
field=field[indices]
temperature=temperature[indices]
;
*(*pState1).y=y
*(*pState1).x=x
*(*pState1).field=field
*(*pState1).temperature=temperature
;
Quantities[0]='B/T'
Quantities[1]='Moment'
widget_control,(*pstate1).SetFieldButton,sensitive=0
endelse

(*pState1).Quantities=Quantities

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

*(*pState1).y_original=*(*pState1).y
(*pState1).DataScaleFactor=1.0
(*pState1).data=1
(*pstate1).CursorPosition=0
widget_control,(*pstate1).CursorPosition_Type,set_value = 0
*(*pstate1).yt=0
CursorPositionType,main_event
MagProp_Plot_Experimental_Data,main_event
end
'Exit':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagProp_ReadAscii,main_event

widget_control,main_event.top,get_uvalue = pState_main

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50


tlb = widget_base(title='Read Data from Ascii File',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)


;Graphical_Base_cola2=widget_base(tlb,/col,/base_align_center,/frame)


Source_File=cw_field(tlb,/col,title='Source File',xsize=30, $
       value=(*pState_main).Source_File)

void = widget_button(tlb,value = 'Browse', uname='Specify_Source_File')


void = widget_button(tlb,value = 'Read and Plot Data', uname='Read_Experimental_Data')

;
void = widget_button(tlb,value = 'Exit', uname='Exit')


state={Source_File:Source_File, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'MagProp_ReadAscii',tlb,event_handler = 'MagProp_ReadAscii_Events' ;register with the xmanager

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

Source_Dir=(*pstate).Source_Dir
FitPresent = 0
if strlowcase(size(*(*pstate).yt,/tname)) eq 'double' then FitPresent = 1
if FitPresent eq 0 and (*pstate).data eq 0 then return

ErrorsPresent=0
if (strlowcase(size(*(*pstate).dy,/tname)) eq 'double') OR $ 
(strlowcase(size(*(*pstate).dy,/tname)) eq 'float') then ErrorsPresent = 1

filename = DIALOG_PICKFILE(title = 'Save Fit as Ascii',file='MagProp.out', $
         /write,filter="*.out",/fix_filter,path=Source_Dir)
if filename eq '' then return
quantities=(*pState).quantities
xtitle=quantities[0]
ytitle=quantities[1]
ytitle=strlowcase(ytitle)

;print,ytitle
case ytitle of
'moment'       : $
begin
ytitle='Magnetic Moment'
xtitle='B / T'
end
'chit'   :   $
begin
ytitle='ChiT'
xtitle='Temperature'
end
'chi'     :    $
begin
ytitle='Chi'
xtitle='Temperature'
end
'ueff'   :   $
begin
ytitle='Ueff'
xtitle='Temperature
end
else:
endcase
x=*(*pState).x
nx=n_elements(x)

if FitPresent eq 1 and (*pstate).data eq 0 then DataType = 0 ;just theory
if FitPresent eq 0 and (*pstate).data eq 1 and ErrorsPresent eq 0 then DataType = 1 ;just Experiment, no errors
if FitPresent eq 1 and (*pstate).data eq 1 and ErrorsPresent eq 0 then DataType = 2 ;Experiment, no errors and Theory
if FitPresent eq 0 and (*pstate).data eq 1 and ErrorsPresent eq 1 then DataType = 3 ;Experiment with errors
if FitPresent eq 1 and (*pstate).data eq 1 and ErrorsPresent eq 1 then DataType = 4 ;Experiment, no errors and Theory

case DataType of
0:   $
begin
    if ytitle ne 'Magnetic Moment' then begin
    format_float = '(2x,f-12.5,1x,f-12.5)'
    outputlabels=strarr(2)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Model      '
    string_output=outputlabels[0]+outputlabels[1]
    output_array=fltarr(2,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).yt
;
;
    endif else begin
    format_float = '(f-12.5,2x,f-12.5,10x,f-12.5,1x,f-12.5)'
    outputlabels=strarr(4)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Model     '
    outputlabels[2]='Temperature'+'      '
    outputlabels[3]='Field'+'           '
    string_output=outputlabels[0]+outputlabels[1]+outputlabels[2]+outputlabels[3]
    output_array=fltarr(4,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).yt
    output_array[2,*]=*(*pState).temperature
    output_array[3,*]=*(*pState).field
    endelse
;
end
1:   $
begin
    if ytitle ne 'Magnetic Moment' then begin
    format_float = '(2x,f-12.5,1x,f-12.5)'
    outputlabels=strarr(2)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Data      '
    string_output=outputlabels[0]+outputlabels[1]
    output_array=fltarr(2,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).y
;
;
    endif else begin
    format_float = '(f-12.5,2x,f-12.5,10x,f-12.5,1x,f-12.5)'
    outputlabels=strarr(4)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Data     '
    outputlabels[2]='Temperature'+'      '
    outputlabels[3]='Field'+'           '
    string_output=outputlabels[0]+outputlabels[1]+outputlabels[2]+outputlabels[3]
    output_array=fltarr(4,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).y
    output_array[2,*]=*(*pState).temperature
    output_array[3,*]=*(*pState).field
    endelse
;
end
2:   $
begin
    if ytitle ne 'Magnetic Moment' then begin
    format_float = '(2x,f-12.5,1x,f-12.5,3x,f-12.5)'
    outputlabels=strarr(3)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Data      '
    outputlabels[2]=ytitle+'_Model      '
    string_output=outputlabels[0]+outputlabels[1]+outputlabels[2]
    output_array=fltarr(3,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).y
    output_array[2,*]=*(*pstate).yt
;
;
    endif else begin
    format_float = '(f-12.5,2x,f-12.5,13x,f-12.5,10x,f-12.5,1x,f-12.5)'
    outputlabels=strarr(5)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Data     '
    outputlabels[2]=ytitle+'_Model     '
    outputlabels[3]='Temperature'+'      '
    outputlabels[4]='Field'+'           '
    string_output=outputlabels[0]+outputlabels[1]+outputlabels[2]+outputlabels[3]+outputlabels[4]
    output_array=fltarr(5,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).y
    output_array[2,*]=*(*pstate).yt
    output_array[3,*]=*(*pState).temperature
    output_array[4,*]=*(*pState).field
    endelse
end
3:   $
begin
    if ytitle ne 'Magnetic Moment' then begin
    format_float = '(2x,f-12.5,1x,f-12.5,3x,f-12.5)'
    outputlabels=strarr(3)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Data      '
    outputlabels[2]=ytitle+'_Error      '
    string_output=outputlabels[0]+outputlabels[1]+outputlabels[2]
    output_array=fltarr(3,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).y
    output_array[2,*]=*(*pstate).dy
;
;
    endif else begin
    format_float = '(f-12.5,2x,f-12.5,13x,f-12.5,10x,f-12.5,1x,f-12.5)'
    outputlabels=strarr(5)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Data     '
    outputlabels[2]=ytitle+'_Error    '
    outputlabels[3]='Temperature'+'      '
    outputlabels[4]='Field'+'           '
    string_output=outputlabels[0]+outputlabels[1]+outputlabels[2]+outputlabels[3]+outputlabels[4]
    output_array=fltarr(5,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).y
    output_array[2,*]=*(*pstate).dy
    output_array[3,*]=*(*pState).temperature
    output_array[4,*]=*(*pState).field
    endelse
end
4:   $
begin
    if ytitle ne 'Magnetic Moment' then begin
    format_float = '(2x,f-12.5,1x,f-12.5,3x,f-12.5,3x,f-12.5)'
    outputlabels=strarr(4)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Data      '
    outputlabels[2]=ytitle+'_Error     '
    outputlabels[3]=ytitle+'_Model      '
    string_output=outputlabels[0]+outputlabels[1]+outputlabels[2]+outputlabels[3]
    output_array=fltarr(4,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).y
    output_array[2,*]=*(*pstate).dy
    output_array[3,*]=*(*pstate).yt
;
;
    endif else begin
    format_float = '(f-12.5,2x,f-12.5,2x,f-12.5,13x,f-12.5,10x,f-12.5,1x,f-12.5)'
    outputlabels=strarr(6)
    outputlabels[0]=xtitle+'   '
    outputlabels[1]=ytitle+'_Data     '
    outputlabels[2]=ytitle+'_Error    '
    outputlabels[2]=ytitle+'_Model    '
    outputlabels[3]='Temperature'+'      '
    outputlabels[4]='Field'+'           '
    string_output=outputlabels[0]+outputlabels[1]+outputlabels[2]+outputlabels[3]+outputlabels[4]
    output_array=fltarr(6,nx)
    output_array[0,*]=x
    output_array[1,*]=*(*pstate).y
    output_array[2,*]=*(*pstate).dy
    output_array[3,*]=*(*pstate).yt
    output_array[4,*]=*(*pState).temperature
    output_array[5,*]=*(*pState).field
    endelse
end
else:
endcase

    openw,lun,filename,/get_lun
    printf,lun,string_output
    for i = 0, nx-1 do begin
    printf,lun,output_array[*,i],format = format_float
    endfor
    free_lun,lun,/force


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagPropSaveSession,event
widget_control,event.top,get_uvalue = pState
;get widget info
widget_control,(*pstate).Parameter_Table,get_value=Parameter_Table_Input
Source_Dir=(*pstate).Source_Dir
Source_File=(*pstate).Source_File
file=(*pstate).file
Matrix_Dimension=(*pstate).Matrix_Dimension
MagFieldTheoryValue=(*pstate).MagFieldTheoryValue
Theta_sc=(*pstate).Theta_sc
Phi_sc=(*pstate).Phi_sc
Sample_Type=(*pstate).Sample_Type
FieldWidth=(*pstate).FieldWidth
DerivOption=(*pstate).DerivOption
theta_start=(*pState).theta_start
theta_end=(*pState).theta_end
theta_nsteps=(*pState).theta_nsteps
phi_start=(*pState).phi_start
phi_end=(*pState).phi_end
phi_nsteps=(*pState).phi_nsteps
SusPowderMethod=(*pState).SusPowderMethod
Diamagnetism=(*pState).Diamagnetism
ModelScaleFactor=(*pState).ModelScaleFactor
MFTC_Pointers=(*pState).MFTC_Pointers
TempLims=(*pState).TempLims
MaxIterations=(*pState).MaxIterations
Weighting=(*pState).Weighting
title=(*pState).title
DataScaleFactor=(*pState).DataScaleFactor
Data=(*pState).Data
dv=(*pState).dv
PlotFullRange=(*pState).PlotFullRange
Algorithm_type=(*pState).Algorithm_type
EigenvalueRange_type=(*pState).EigenvalueRange_type
EigenvalueTolerance_type=(*pState).EigenvalueTolerance_type
EigenvalueTolerance_Value=(*pState).EigenvalueTolerance_Value
EigenvalueRange_Value=(*pState).EigenvalueRange_Value
EigenvalueRange_Value_str=(*pState).EigenvalueRange_Value_str
MFT_Treatment=(*pState).MFT_Treatment
MFT_Criterion=(*pState).MFT_Criterion
MFTC=(*pState).MFTC
Energy_Weights=(*pState).Energy_Weights
Energy_Refine=(*pState).Energy_Refine
SzMatrixName=(*pState).SzMatrixName
SxMatrixName=(*pState).SxMatrixName
SyMatrixName=(*pState).SyMatrixName
Jint=(*pState).Jint
RefineEnergyTemperature=(*pState).RefineEnergyTemperature


;
if strlowcase(size(*(*pstate).x,/tname)) ne 'undefined' then begin
x=*(*pstate).x
endif else begin
x='undefined'
endelse
if strlowcase(size(*(*pstate).y,/tname)) ne 'undefined' then begin
y=*(*pstate).y
endif else begin
y='undefined'
endelse
if strlowcase(size(*(*pstate).y_original,/tname)) ne 'undefined' then begin
y_original=*(*pstate).y_original
endif else begin
y_original='undefined'
endelse
if strlowcase(size(*(*pstate).dy,/tname)) ne 'undefined' then begin
dy=*(*pstate).dy
endif else begin
dy='undefined'
endelse
if strlowcase(size(*(*pstate).field,/tname)) ne 'undefined' then begin
field=*(*pstate).field
endif else begin
field='undefined'
endelse
if strlowcase(size(*(*pstate).temperature,/tname)) ne 'undefined' then begin
temperature=*(*pstate).temperature
endif else begin
temperature='undefined'
endelse
if strlowcase(size(*(*pstate).ParameterInfoStruc,/tname)) ne 'undefined' then begin
;print,'strlowcase(size(*(*pstate).ParameterInfoStruc,/tname)) ', strlowcase(size(*(*pstate).ParameterInfoStruc,/tname))
ParameterInfoStruc=*(*pstate).ParameterInfoStruc
;help,ParameterInfoStruc,/struc
endif else begin
ParameterInfoStruc={Fields:strarr(1,3),Limits:intarr(1,4)}
endelse
Quantities=(*pState).Quantities
Parameter_Table=(*pState).Parameter_Table
;define structure
if strlowcase(size(*(*pstate).MatricesInMemory,/tname)) ne 'undefined' then begin
MatricesInMemory=*(*pstate).MatricesInMemory
endif else begin
MatricesInMemory=0
endelse
if strlowcase(size(*(*pstate).InputEnergies,/tname)) ne 'undefined' then begin
InputEnergies=*(*pstate).InputEnergies
endif else begin
InputEnergies=0.0
endelse


Save_Info = { Source_File:Source_File, $
         Source_Dir:Source_Dir, $
         Matrix_Dimension:Matrix_Dimension, $
         MagFieldTheoryValue:MagFieldTheoryValue, $
         FieldWidth:FieldWidth, $
         Parameter_Table_Input:Parameter_Table_Input, $
         x:x, $
         y:y, $
         y_original:y_original, $
         dy:dy, $
         field:field, $
         file:file, $
         temperature:temperature, $
         ParameterInfoStruc:ParameterInfoStruc, $
         Quantities:Quantities, $
         theta_start:theta_start, $
         theta_end:theta_end, $
         theta_nsteps:theta_nsteps, $
         phi_start:phi_start, $
         phi_end:phi_end, $
         phi_nsteps:phi_nsteps, $
         DerivOption:DerivOption, $
         SusPowderMethod:SusPowderMethod, $
         Sample_Type:Sample_Type, $
         Theta_sc:Theta_sc, $
         Phi_sc:Phi_sc, $
         Diamagnetism:Diamagnetism, $
         ModelScaleFactor:ModelScaleFactor, $
         TempLims:TempLims, $
         MaxIterations:MaxIterations, $
         Weighting:Weighting, $
         title:title, $
         DataScaleFactor:DataScaleFactor, $
         Data:Data, $
         dv:dv, $
         MatricesInMemory:MatricesInMemory, $
         MFTC_Pointers:MFTC_Pointers, $
         PlotFullRange:PlotFullRange, $
         Algorithm_type:Algorithm_type, $
         EigenvalueRange_type:EigenvalueRange_type, $
         EigenvalueTolerance_type:EigenvalueTolerance_type, $
         EigenvalueTolerance_Value:EigenvalueTolerance_Value, $
         EigenvalueRange_Value:EigenvalueRange_Value, $
         EigenvalueRange_Value_str:EigenvalueRange_Value_str, $
         MFT_Treatment:MFT_Treatment, $
         MFT_Criterion:MFT_Criterion, $
         MFTC:MFTC, $
         Jint:Jint, $
         Energy_Weights:Energy_Weights, $
         Energy_Refine:Energy_Refine, $
         InputEnergies:InputEnergies, $
         SzMatrixName:SzMatrixName, $
         SxMatrixName:SxMatrixName, $
         SyMatrixName:SyMatrixName, $
         RefineEnergyTemperature:RefineEnergyTemperature, $
         Parameter_Table:Parameter_Table}


filename = DIALOG_PICKFILE(title = 'Save Settings',file='MagProp.MPP', $
         /write,filter="*.MPP",/fix_filter,path=Source_Dir)

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

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagPropRestoreSession,event
widget_control,event.top,get_uvalue = pState
filename=dialog_pickfile(path=(*pstate).Source_Dir,/read,filter="*.MPP",/fix_filter)
if filename eq '' then return
restore,filename=filename;,/RELAXED_STRUCTURE_ASSIGNMENT 

widget_control,(*pstate).Parameter_Table,set_value=Save_Info.Parameter_Table_Input
;
;(*pstate).Source_Dir=Save_Info.Source_Dir
(*pstate).Source_File=Save_Info.Source_File
(*pstate).Matrix_Dimension=Save_Info.Matrix_Dimension
(*pstate).MagFieldTheoryValue=Save_Info.MagFieldTheoryValue
(*pstate).Theta_sc=Save_Info.Theta_sc
(*pstate).Phi_sc=Save_Info.Phi_sc
(*pstate).Sample_Type=Save_Info.Sample_Type
(*pstate).quantities=Save_Info.quantities
(*pstate).Parameter_Table_Input=Save_Info.Parameter_Table_Input
(*pstate).FieldWidth=Save_Info.FieldWidth
(*pstate).DerivOption=Save_Info.DerivOption
(*pstate).theta_start=Save_Info.theta_start
(*pstate).theta_end=Save_Info.theta_end
(*pstate).theta_nsteps=Save_Info.theta_nsteps
(*pstate).phi_start=Save_Info.phi_start
(*pstate).phi_end=Save_Info.phi_end
(*pstate).phi_nsteps=Save_Info.phi_nsteps
(*pstate).DerivOption=Save_Info.DerivOption
(*pstate).SusPowderMethod=Save_Info.SusPowderMethod
(*pState).TempLims=Save_Info.TempLims
(*pState).Diamagnetism=Save_Info.Diamagnetism
(*pState).ModelScaleFactor=Save_Info.ModelScaleFactor
(*pState).MFTC_Pointers=Save_Info.MFTC_Pointers
(*pState).MaxIterations=Save_Info.MaxIterations
(*pState).Weighting=Save_Info.Weighting
(*pState).title=Save_Info.title
(*pState).DataScaleFactor=Save_Info.DataScaleFactor
(*pState).Data=Save_Info.Data
(*pState).dv=Save_Info.dv
(*pState).PlotFullRange=Save_Info.PlotFullRange
*(*pstate).yt=0
*(*pstate).MatricesInMemory=Save_Info.MatricesInMemory




;
*(*pstate).ParameterInfoStruc=Save_Info.ParameterInfoStruc
ParameterInfoStruc=Save_Info.ParameterInfoStruc
;help,ParameterInfoStruc,/struc
;
;
woof=strmatch(tag_names(Save_Info),'MFT_TREATMENT')
void=where(woof eq 1,count)
if count ne 0 then (*pState).MFT_Treatment=Save_Info.MFT_Treatment
;
woof=strmatch(tag_names(Save_Info),'MFT_CRITERION')
void=where(woof eq 1,count)
if count ne 0 then (*pState).MFT_Criterion=Save_Info.MFT_Criterion
;
woof=strmatch(tag_names(Save_Info),'MFTC')
void=where(woof eq 1,count)
if count ne 0 then (*pState).MFTC=Save_Info.MFTC
;
woof=strmatch(tag_names(Save_Info),'ENERGY_WEIGHTS')
void=where(woof eq 1,count)
if count ne 0 then (*pState).Energy_Weights=Save_Info.Energy_Weights
;
woof=strmatch(tag_names(Save_Info),'ENERGY_REFINE')
void=where(woof eq 1,count)
if count ne 0 then (*pState).Energy_Refine=Save_Info.Energy_Refine
;
woof=strmatch(tag_names(Save_Info),'INPUTENERGIES')
void=where(woof eq 1,count)
if count ne 0 then *(*pState).InputEnergies=Save_Info.InputEnergies
;
woof=strmatch(tag_names(Save_Info),'SZMATRIXNAME')
void=where(woof eq 1,count)
if count ne 0 then begin
(*pState).SzMatrixName=Save_Info.SzMatrixName
(*pState).SxMatrixName=Save_Info.SxMatrixName
(*pState).SyMatrixName=Save_Info.SyMatrixName
endif
;
woof=strmatch(tag_names(Save_Info),'JINT')
void=where(woof eq 1,count)
if count ne 0 then begin
(*pState).Jint=Save_Info.Jint
endif
;
woof=strmatch(tag_names(Save_Info),'REFINEENERGYTEMPERATURE')
void=where(woof eq 1,count)
if count ne 0 then begin
(*pState).RefineEnergyTemperature=Save_Info.RefineEnergyTemperature
endif
;
;
x=Save_Info.x
y=Save_Info.y
y_original=Save_Info.y_original
dy=Save_Info.dy
field=Save_Info.field
temperature=Save_Info.temperature
if strlowcase(size(temperature,/tname)) ne 'string' then begin
*(*pstate).temperature=temperature
endif
if strlowcase(size(y,/tname)) ne 'string' then begin
widget_control,(*pstate).ErrorBarButton,sensitive=1
endif else begin
widget_control,(*pstate).ErrorBarButton,sensitive=0
endelse
if strlowcase(size(x,/tname)) ne 'string' then begin
*(*pstate).x=x
*(*pstate).y=y
*(*pstate).y_original=y_original
*(*pstate).dy=dy
MagProp_Plot_Experimental_Data,event
endif
if strlowcase(size(field,/tname)) ne 'string' then begin
*(*pstate).field=field
endif
if (*pstate).quantities[0] eq 't' then begin
widget_control,(*pstate).TemperatureRangeButton,sensitive=1
widget_control,(*pstate).ExperimentalQuantityButton,sensitive=1
widget_control,(*pstate).SetFieldButton,sensitive=1
endif else begin
widget_control,(*pstate).TemperatureRangeButton,sensitive=0
widget_control,(*pstate).ExperimentalQuantityButton,sensitive=0
widget_control,(*pstate).SetFieldButton,sensitive=0
endelse


if (*pState).data eq 1 then begin
(*pstate).CursorPosition=0
widget_control,(*pstate).CursorPosition_Type,set_value = 0
endif else begin
(*pstate).CursorPosition=1
widget_control,(*pstate).CursorPosition_Type,set_value = 1
endelse


MagProp_Update_Droplist,event
ParameterInfoUpdate,event,/DisplayEntry
;SampleType,event


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

if strlowcase(size(*(*pstate).x,/tname)) eq 'undefined' then return
if ((*pState).data eq 0) and (strlowcase(size(*(*pstate).yt,/tname)) ne 'double') then return

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
        MagProp_Plot_Experimental_Data,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
        MagProp_Plot_Experimental_Data,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
         MagProp_Plot_Experimental_Data,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]))
void=min(((*(*pState).x)-x),minx,/abs)
x=(*(*pState).x)[minx]



if (*pState).data eq 1 then begin
;print,'(*pstate).CursorPosition: ',(*pstate).CursorPosition
    if (*pState).CursorPosition eq 0 then begin
    ymouse=(*(*pState).y)[minx]
    endif else begin
    ymouse=(*(*pState).yt)[minx]
    endelse
    y=(*(*pState).y)[minx]
;print,'ymouse: ',ymouse
endif else begin
ymouse=(*(*pState).yt)[minx]
endelse

MagProp_Plot_Experimental_Data,event
plots,x,ymouse,psym = 4, thick = 4.0


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


      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



end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro DefineQuantities_Events,event
widget_control,event.top,get_uvalue = pState
uname=widget_info(event.id,/uname)
case uname of
'Accept':    $
begin
IF (*pstate).column_num eq 2 THEN BEGIN
widget_control,(*pstate).Column1Name,get_value=Column1Name
widget_control,(*pstate).Column2Name,get_value=Column2Name
Column1Name=strlowcase(Column1Name[0])
Column2Name=strlowcase(Column2Name[0])
if Column1Name eq Column2Name then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The data in the respective columns cannot be designated the same name')
return
endif
if (Column1Name ne 't') and  (Column2Name ne 't') then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'One column must specifiy the temperature')
return
endif
Accepted_Fields=['chit','chi','ueff','t']
void=where(Column1Name eq Accepted_Fields, count1)
void=where(Column2Name eq Accepted_Fields, count2)
if (count1 eq 0) or (count2 eq 0) then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'Accepted Fields are ''chit'', ''chi'', ''ueff'', ''t'' in any case')
return
endif
(*pstate).Quantities[0]=Column1Name
(*pstate).Quantities[1]=Column2Name
widget_control,event.top,/destroy
return
ENDIF ELSE BEGIN
widget_control,(*pstate).Column1Name,get_value=Column1Name
widget_control,(*pstate).Column2Name,get_value=Column2Name
widget_control,(*pstate).Column3Name,get_value=Column3Name
Column1Name=strlowcase(Column1Name[0])
Column2Name=strlowcase(Column2Name[0])
Column3Name=strlowcase(Column3Name[0])
if (Column1Name eq Column2Name) or $
    (Column1Name eq Column3Name) or $
    (Column2Name eq Column3Name) then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The data in the respective columns cannot be designated the same name')
return
endif
Accepted_Fields=['t','mom','b']
void=where(Column1Name eq Accepted_Fields, count1)
void=where(Column2Name eq Accepted_Fields, count2)
void=where(Column3Name eq Accepted_Fields, count3)
if (count1 eq 0) or (count2 eq 0) or (count3 eq 0) then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'Accepted Fields are ''T'', ''Mom'', ''B'' in any case')
return
endif
(*pstate).Quantities[0]=Column1Name
(*pstate).Quantities[1]=Column2Name
(*pstate).Quantities[2]=Column3Name
widget_control,event.top,/destroy
return
ENDELSE
end
'Cancel':    $
begin
widget_control,event.top,/destroy
return
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro DefineQuantities,main_event,column_num,Quantities
geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

if column_num eq 2 then begin
tlb = widget_base(title='Two Column Ascii Data Detected',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)

Base1=widget_base(tlb,/row,/align_center)
msg=strarr(4)
msg[0]='The program assumes that one column contains'
msg[1]='the temperature, T, and the other column contains'
msg[2]='ChiT, Chi or ueff.  Please designate the data in each'
msg[3]= 'of the two columns.'
void = widget_text(Base1,value = msg,xsize = 42,ysize=4)
Base2=widget_base(tlb,/row,/align_center)

Column1Name=cw_field(Base2,/col,title='Column 1',xsize=10, $
       value='T')

Column2Name=cw_field(Base2,/col,title='Column 2',xsize=10, $
       value='ChiT')

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

void = widget_button(Base3,value = 'Accept', uname='Accept')
void = widget_button(Base3,value = 'Cancel', uname='Cancel')
state={Quantities:Quantities, $
       Column1Name:Column1Name, $
       Column2Name:Column2Name, $
       column_num:column_num}

endif else begin
tlb = widget_base(title='Three Column Ascii Data Detected',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)

Base1=widget_base(tlb,/row,/align_center)
msg=strarr(3)
msg[0]='The program assumes that the three columns comprise'
msg[1]='the temperature, T, the magnetic moment, mom, '
msg[2]='and the field, B, in units of gauss'
void = widget_text(Base1,value = msg,xsize = 42,ysize=3)
Base2=widget_base(tlb,/row,/align_center)

Column1Name=cw_field(Base2,/col,title='Column 1',xsize=10, $
       value='T')

Column2Name=cw_field(Base2,/col,title='Column 2',xsize=10, $
       value='Mom')

Column3Name=cw_field(Base2,/col,title='Column 3',xsize=10, $
       value='B')

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

void = widget_button(Base3,value = 'Accept', uname='Accept')
void = widget_button(Base3,value = 'Cancel', uname='Cancel')
state={Quantities:Quantities, $
       Column1Name:Column1Name, $
       Column2Name:Column2Name, $
       Column3Name:Column3Name, $
       column_num:column_num}
endelse
widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'DefineQuantities',tlb,event_handler = 'DefineQuantities_Events' ;register with the xmanager
Quantities=(*pState).Quantities
ptr_free,pState
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro PlotTheoryOnly,event,to_window = to_window,fitting=fitting
widget_control,event.top,get_uvalue = pstate


quantities=(*pState).quantities
ytitle=quantities[1]
ytitle=strlowcase(ytitle)
;
case ytitle of
'moment'       : $
begin
ytitle='Magnetic Moment (Bohr Magnetons per ion)'
xtitle='B / T (Tesla * 10 / Kelvin)'
end
'chit'   :   $
begin
ytitle='ChiT (emu Kelvin / mole)'
xtitle='Temperature (Kelvin)'
end
'chi'     :    $
begin
ytitle='Chi (emu / mole)'
xtitle='Temperature (Kelvin)'
end
'ueff'   :   $
begin
ytitle='Ueff (Bohr Magnetons per ion)'
xtitle='Temperature (Kelvin)'
end
endcase
x=*(*pState).x
if strlowcase(size(*(*pstate).yt,/tname)) eq 'double' then begin
yt=*(*pstate).yt
endif else begin
return
endelse



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

endif

;print,'x: ',x
;print,'yt: ',yt

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

if (*pState).quantities[1] ne 'Moment' then begin

    plot,x,yt,title=(*pstate).title, $
      xrange = (*pstate).winState.xrange,yrange = (*pstate).winState.yrange, $
      xstyle = 1,ystyle = 1, psym=0, thick = 2.0, $
      xtitle=xtitle, ytitle=ytitle
    oplot,x,yt,psym = 0,thick = 2.0,color=6

endif else begin

    plot,x,yt,title=(*pstate).title, $
      xrange = (*pstate).winState.xrange,yrange = (*pstate).winState.yrange, $
      xstyle = 1,ystyle = 1,psym = 7,thick = 2.0,symsize=1, $
      xtitle=xtitle, ytitle=ytitle
    oplot,x,yt,psym = 7,thick = 2.0,color=3,symsize=1

endelse

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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagProp_Plot_Experimental_Data,event,to_window = to_window,fitting=fitting
widget_control,event.top,get_uvalue = pstate



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

if (*pstate).data eq 0 then begin
PlotTheoryOnly,event,to_window = to_window
return
endif


quantities=(*pState).quantities
ytitle=quantities[1]
ytitle=strlowcase(ytitle)

case ytitle of
'moment'       : $
begin
ytitle='Magnetic Moment (Bohr Magnetons per ion)'
xtitle='B / T (Tesla * 10 / Kelvin)'
end
'chit'   :   $
begin
ytitle='ChiT (emu Kelvin / mole)'
xtitle='Temperature (Kelvin)'
end
'chi'     :    $
begin
ytitle='Chi (emu / mole)'
xtitle='Temperature (Kelvin)'
end
'ueff'   :   $
begin
ytitle='Ueff (Bohr Magnetons per ion)'
xtitle='Temperature (Kelvin)'
end
endcase
x=*(*pState).x
y=*(*pState).y
if strlowcase(size(*(*pstate).yt,/tname)) ne 'undefined' then yt=*(*pstate).yt
if strlowcase(size(*(*pstate).dy,/tname)) ne 'undefined' AND $
    strlowcase(size(*(*pstate).dy,/tname)) ne 'string' then dy=*(*pState).dy

chisq=(*pState).chisq


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]

if n_elements(yt) gt 0 then begin
        if ((*pState).TempLims[0] ne -1) and $
        ((*pState).PlotFullRange eq 1) and $
        (keyword_set(fitting) eq 0) and $
        n_elements(yt) gt (*pState).TempLims[1] then begin
        ytmod=yt[(*pState).TempLims[0]:(*pState).TempLims[1]]
        endif else begin
        ytmod=yt
        endelse
ytmin=min(ytmod,max=ytmax)
ylo=(*pState).winState.yrange[0]
yhi=(*pState).winState.yrange[1]
        if (ytmin lt ylo)  then begin
    (*pState).winState.yrange[0] = ytmin
    endif
    if ytmax gt yhi then begin
    (*pState).winState.yrange[1] = ytmax
    endif
endif

endif

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

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


if n_elements(dy) gt 1 then begin
errplot,x,y-dy,y+dy,width = 0.0
endif
;print,'ytitle: ',ytitle

if n_elements(yt) gt 1 then begin
xt=x
yt=*(*pstate).yt
    if strpos(ytitle,'Moment') eq -1 then begin
        if (((*pState).TempLims[0] ne -1) and (keyword_set(fitting) eq 1)) then begin  ;must be an easier way
        xt=x[(*pState).TempLims[0]:(*pState).TempLims[1]]
        endif
        if ((*pState).TempLims[0] ne -1) and ((*pState).PlotFullRange eq 1) and (keyword_set(fitting) eq 0) then begin
        xt=x[(*pState).TempLims[0]:(*pState).TempLims[1]]
        yt=(*(*pstate).yt)[(*pState).TempLims[0]:(*pState).TempLims[1]]
        endif
    oplot,xt,yt,psym = 0,thick = 2.0,color=6
    endif else begin
    oplot,xt,yt,psym = 7,thick = 2.0,color=3,symsize=1
    endelse
endif

if chisq ne -10.0 then begin
xlims=!x.crange
ylims=!y.crange
xpos=xlims[0]+(xlims[1]-xlims[0])*0.6
ypos=ylims[0]+(ylims[1]-ylims[0])*0.4

xyouts,xpos,ypos,"Chisq = "+strtrim(string(chisq),2),color=7
endif


;print,'yt ',*(*pstate).yt

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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagProp_Update_Droplist,event
widget_control,event.top,get_uvalue = pstate
Parameter_Table_Input=(*pstate).Parameter_Table_Input
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries ne '',Num_Entries)
if Num_Entries eq 0 then begin
Entries=''
endif else begin
Entries=Entries[0:Num_Entries-1]
endelse
widget_control,(*pstate).Parameter_Droplist,set_value=Entries
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ParameterInfoUpdate,event,NewEntry=NewEntry,DeleteEntry=DeleteEntry, $
    UpdateEntry=UpdateEntry,DisplayEntry=DisplayEntry,NewTable=NewTable
widget_control,event.top,get_uvalue = pstate
treatment=3
if keyword_set(NewEntry) then treatment=0
if keyword_set(DeleteEntry) then treatment=1
if keyword_set(UpdateEntry) then treatment=2
if keyword_set(DisplayEntry) then treatment=3
if keyword_set(NewTable) then treatment=4
case treatment of
0:   $
begin
Parameter_Table_Input=(*pstate).Parameter_Table_Input
;establish how many entries there are
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries ne '',Num_Entries)
if Num_Entries eq 1 then begin ;first entry
ParameterInfoStruc={Fields:strarr(1,3),Limits:intarr(1,4)}
Parameter_Value=strtrim(string(Parameter_Table_Input[3,0]),2)
ParameterInfoStruc.Fields[0,0]=Parameter_Value
ParameterInfoStruc.Limits[0,0]=1
*(*pState).ParameterInfoStruc=ParameterInfoStruc
endif else begin
;get old values
ParameterInfoStruc=*(*pState).ParameterInfoStruc
;help,ParameterInfoStruc,/struc
Fields=strarr(Num_Entries,3)
Limits=intarr(Num_Entries,4)
Parameter_Value=strtrim(string(Parameter_Table_Input[3,Num_Entries-1]),2)
Fields[Num_Entries-1,0]=Parameter_Value
Limits[Num_Entries-1,0]=1
    if Num_Entries eq 2 then begin
    Fields[0,*]=ParameterInfoStruc.Fields[*]
    Limits[0,*]=ParameterInfoStruc.Limits[*]
    endif else begin
    Fields[0:Num_Entries-2,*]=ParameterInfoStruc.Fields[*,*]
    Limits[0:Num_Entries-2,*]=ParameterInfoStruc.Limits[*,*]
    endelse
ParameterInfoStruc={Fields:Fields,Limits:Limits}
*(*pState).ParameterInfoStruc=ParameterInfoStruc
endelse
end
1:   $
begin
Parameter_Table_Input=(*pstate).Parameter_Table_Input
;establish how many entries there are
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries ne '',Num_Entries)
if Num_Entries eq 0 then return
;establish droplist parameter designation
index=widget_info((*pstate).Parameter_Droplist,/droplist_select)
;widget_control,(*pstate).Parameter_Droplist
;remove from table
Parameter_Table_InputOld=(*pstate).Parameter_Table_Input
Parameter_Table_InputNew=strarr(5,100)

;remove from memory if there.
if strlowcase(size(*(*pstate).MatricesInMemory,/tname)) eq 'struct' then begin
designation=Parameter_Table_InputOld[0,index]
designation=designation[0]
tags=tag_names(*(*pstate).MatricesInMemory)
wheretag=where(strupcase(designation) ne tags,count)
    if (count ne 0) and (count ne n_elements(tags)) then begin
       for i = 0, count-1 do begin
         if i eq 0 then begin
          tempstruct=create_struct(tags[wheretag[i]], $
          (*(*pstate).MatricesInMemory).(wheretag[i]))
          endif else begin
          tempstruct=create_struct(tempstruct,tags[wheretag[i]], $
          (*(*pstate).MatricesInMemory).(wheretag[i]))
          endelse
       endfor
       *(*pstate).MatricesInMemory=tempstruct
    endif
    if count eq 0 then *(*pstate).MatricesInMemory=0
endif


;print,index
;print,'Parameter_Table_InputOld[0,index]: ',Parameter_Table_InputOld[0,index]

wherevalid=where(indgen(Num_Entries) ne index,count)

if count ne 0 then begin
Parameter_Table_InputNew[*,0:Num_Entries-2]=Parameter_Table_InputOld[*,wherevalid]
(*pstate).Parameter_Table_Input=Parameter_Table_InputNew
;update parameter info
ParameterInfoStruc=*(*pState).ParameterInfoStruc
Fields=strarr(Num_Entries-1,3)
Limits=intarr(Num_Entries-1,4)
Fields[*,*]=ParameterInfoStruc.Fields[wherevalid,*]
Limits[*,*]=ParameterInfoStruc.Limits[wherevalid,*]
ParameterInfoStruc={Fields:Fields,Limits:Limits}
*(*pState).ParameterInfoStruc=ParameterInfoStruc
endif else begin
(*pstate).Parameter_Table_Input=strarr(5,100)
ParameterInfoStruc={Fields:strarr(1,3),Limits:intarr(1,4)}
*(*pState).ParameterInfoStruc=ParameterInfoStruc
endelse
widget_control,(*pstate).Parameter_Table,set_value=Parameter_Table_InputNew
MagProp_Update_Droplist,event
index=widget_info((*pstate).Parameter_Droplist,/droplist_select)
Parameter_Value=(*(*pState).ParameterInfoStruc).fields[index,0]
LowLimit_Value=(*(*pState).ParameterInfoStruc).fields[index,1]
UpperLimit_Value=(*(*pState).ParameterInfoStruc).fields[index,2]
Parameters_Fix_Value=(*(*pState).ParameterInfoStruc).limits[index,*]
;
widget_control,(*pstate).Parameter_Value,set_value=Parameter_Value[0]
widget_control,(*pstate).LowLimit_Value,set_value=LowLimit_Value[0]
widget_control,(*pstate).UpperLimit_Value,set_value=UpperLimit_Value[0]
widget_control,(*pstate).Parameters_Fix_Value,set_value=Parameters_Fix_Value
;
;delete from memory
;
;print,'Parameter_Table_InputNew[0,index]: ',Parameter_Table_InputNew[0,index]

end
2:   $
begin
Parameter_Table_Input=(*pstate).Parameter_Table_Input
;establish how many entries there are
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries ne '',Num_Entries)
if Num_Entries eq 0 then return
;establish droplist parameter designation
index=widget_info((*pstate).Parameter_Droplist,/droplist_select)
widget_control,(*pstate).Parameter_Value,get_value=Parameter_Value
widget_control,(*pstate).LowLimit_Value,get_value=LowLimit_Value
widget_control,(*pstate).UpperLimit_Value,get_value=UpperLimit_Value
widget_control,(*pstate).Parameters_Fix_Value,get_value=Parameters_Fix_Value
;ParameterInfoStruc=*(*pState).ParameterInfoStruc
;ParameterInfoStruc.fields[index,0]=Parameter_Value[0]
;ParameterInfoStruc.fields[index,1]=LowLimit_Value[0]
;ParameterInfoStruc.fields[index,2]=UpperLimit_Value[0]
;ParameterInfoStruc.limits[index,*]=Parameter_Value[0]


if Parameters_Fix_Value[0] eq 0 then begin
    type=(reform(Parameter_Table_Input[2,*]))[index]
   ZeemanDesignations=['Bx','By','Bz','Bx_m','By_m','Bz_m']
    wherezee=where(type eq ZeemanDesignations,count)
    if count ne 0 then begin
    str=strarr(2)
    str[0]='All Zeeman Matrices Defined Must be Included in the Model'
    str[1]='Fix at Zero or Remove Parameter from the Model'
    void=dialog_message(dialog_parent=event.top,/information, str)
    widget_control,(*pstate).Parameters_Fix_Value,set_value=1
    return
    endif
endif


;woof=Parameter_Value[0]
;help,woof
;woofy=((*(*pState).ParameterInfoStruc).fields)[index,0]
;help,woofy

(*(*pState).ParameterInfoStruc).fields[index,0]=Parameter_Value[0]
(*(*pState).ParameterInfoStruc).fields[index,1]=LowLimit_Value[0]
(*(*pState).ParameterInfoStruc).fields[index,2]=UpperLimit_Value[0]
(*(*pState).ParameterInfoStruc).limits[index,*]=Parameters_Fix_Value

(*pstate).Parameter_Table_Input[3,index]=Parameter_Value[0]
widget_control,(*pstate).Parameter_Table,set_value=(*pstate).Parameter_Table_Input

end
3:   $
begin
Parameter_Table_Input=(*pstate).Parameter_Table_Input
;establish how many entries there are
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries ne '',Num_Entries)
if Num_Entries eq 0 then return
;establish droplist parameter designation
index=widget_info((*pstate).Parameter_Droplist,/droplist_select)
Parameter_Value=(*(*pState).ParameterInfoStruc).fields[index,0]
LowLimit_Value=(*(*pState).ParameterInfoStruc).fields[index,1]
UpperLimit_Value=(*(*pState).ParameterInfoStruc).fields[index,2]
Parameters_Fix_Value=(*(*pState).ParameterInfoStruc).limits[index,*]
;
widget_control,(*pstate).Parameter_Value,set_value=Parameter_Value[0]
widget_control,(*pstate).LowLimit_Value,set_value=LowLimit_Value[0]
widget_control,(*pstate).UpperLimit_Value,set_value=UpperLimit_Value[0]
widget_control,(*pstate).Parameters_Fix_Value,set_value=Parameters_Fix_Value

end
4:   $
begin
Parameter_Table_Input=(*pstate).Parameter_Table_Input
;establish how many entries there are
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries ne '',Num_Entries)
Fields=strarr(Num_Entries,3)
Limits=intarr(Num_Entries,4)
for i = 0, Num_Entries-1 do begin
Parameter_Value=strtrim(string(Parameter_Table_Input[3,i]),2)
Fields[i,0]=Parameter_Value
;print,'Parameter_Value ',Parameter_Value
Limits[i,0]=1
endfor
ParameterInfoStruc={Fields:Fields,Limits:Limits}
*(*pState).ParameterInfoStruc=ParameterInfoStruc
MagProp_Update_Droplist,event
index=widget_info((*pstate).Parameter_Droplist,/droplist_select)
Parameter_Value=(*(*pState).ParameterInfoStruc).fields[index,0]
LowLimit_Value=(*(*pState).ParameterInfoStruc).fields[index,1]
UpperLimit_Value=(*(*pState).ParameterInfoStruc).fields[index,2]
Parameters_Fix_Value=(*(*pState).ParameterInfoStruc).limits[index,*]
widget_control,(*pstate).Parameter_Value,set_value=Parameter_Value[0]
widget_control,(*pstate).LowLimit_Value,set_value=LowLimit_Value[0]
widget_control,(*pstate).UpperLimit_Value,set_value=UpperLimit_Value[0]
widget_control,(*pstate).Parameters_Fix_Value,set_value=Parameters_Fix_Value
widget_control,(*pstate).Parameter_Table,set_value=(*pstate).Parameter_Table_Input
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MFT_Entry,event,SpinMatrixNames=SpinMatrixNames

widget_control,event.top,get_uvalue = pState
if keyword_set(SpinMatrixNames) then begin
designation='Jint'
value=(*pstate).Jint
endif else begin
designation='lambda'
value=(*pstate).MFTC
endelse
Parameter_Table_Input=(*pstate).Parameter_Table_Input
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries eq 'lambda' or Entries eq 'Jint',count)
if count ne 0 then return
void=where(Entries ne '',Num_Entries)
InputRow=Num_Entries
Parameter_Table_Input[0,InputRow]=Designation
Parameter_Table_Input[1,InputRow]='-'
Parameter_Table_Input[2,InputRow]='MFT'
Parameter_Table_Input[3,InputRow]=value
(*pstate).Parameter_Table_Input=Parameter_Table_Input
widget_control,(*pstate).Parameter_Table,set_value=Parameter_Table_Input
MagProp_Update_Droplist,event
ParameterInfoUpdate,event,/NewEntry
ParameterInfoUpdate,event,/Display
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ModelScale,event
widget_control,event.top,get_uvalue = pState
designation='ModelScale'
Parameter_Table_Input=(*pstate).Parameter_Table_Input
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries eq Designation,count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The parameter designation '+''+Designation+''+' is already in use')
    return
endif
void=where(Entries ne '',Num_Entries)
InputRow=Num_Entries
Parameter_Table_Input[0,InputRow]=Designation
Parameter_Table_Input[1,InputRow]='-'
Parameter_Table_Input[2,InputRow]='ModelScale'
Parameter_Table_Input[3,InputRow]=1.0
(*pstate).Parameter_Table_Input=Parameter_Table_Input
widget_control,(*pstate).Parameter_Table,set_value=Parameter_Table_Input
MagProp_Update_Droplist,event
ParameterInfoUpdate,event,/NewEntry
ParameterInfoUpdate,event,/Display
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Enter_Diamagnetism,event
widget_control,event.top,get_uvalue = pState
designation='Diamagnetism'
Parameter_Table_Input=(*pstate).Parameter_Table_Input
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries eq Designation,count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The parameter designation '+''+Designation+''+' is already in use')
    return
endif
void=where(Entries ne '',Num_Entries)
InputRow=Num_Entries
Parameter_Table_Input[0,InputRow]=Designation
Parameter_Table_Input[1,InputRow]='-'
Parameter_Table_Input[2,InputRow]='Diamagnetism'
Parameter_Table_Input[3,InputRow]=0.0
(*pstate).Parameter_Table_Input=Parameter_Table_Input
widget_control,(*pstate).Parameter_Table,set_value=Parameter_Table_Input
MagProp_Update_Droplist,event
ParameterInfoUpdate,event,/NewEntry
ParameterInfoUpdate,event,/Display
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SampleType_Events,event

widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
;t=(*pState).t
uname=widget_info(event.id,/uname)
case uname of
'SampleType':    $
begin
widget_control,(*pstate).Sample_Type,get_value=Sample_Type
widget_control,(*pstate).ModelBase_row1,sensitive=Sample_Type
end
'Accept':    $
begin
widget_control,(*pstate).Sample_Type,get_value=Sample_Type
(*pState1).Sample_Type=Sample_Type
widget_control,(*pstate).Theta_sc,get_value=Theta_sc
(*pState1).theta_sc=Theta_sc
widget_control,(*pstate).phi_sc,get_value=phi_sc
(*pState1).phi_sc=phi_sc
ptr_free,pState
widget_control,event.top,/destroy
return
end
'Cancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SampleType,main_event
widget_control,main_event.top,get_uvalue = pState

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Sample Type',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/base_align_center)


Sample_Type_Field = ['Powder','Single Crystal']

Sample_Type = cw_bgroup(tlb,Sample_Type_Field,/row, $
          /exclusive,set_value = (*pstate).Sample_Type,/return_index,/no_release,uname='SampleType')

ModelBase_row1=widget_base(tlb,/row,sensitive=(*pstate).Sample_Type)


Theta_sc=cw_field(ModelBase_row1,/col, $
                 title='Theta',value=(*pState).theta_sc,xsize=10)

Phi_sc=cw_field(ModelBase_row1,/col, $
                 title='Phi',value=(*pState).phi_sc,xsize=10)

ModelBase_row2=widget_base(tlb,/row)

void = widget_button(ModelBase_row2,value = 'Accept', uname='Accept')
void = widget_button(ModelBase_row2,value = 'Cancel', uname='Cancel')


state={Sample_Type:Sample_Type, $
       Theta_sc:Theta_sc, $
       Phi_sc:Phi_sc, $
       ModelBase_row1:ModelBase_row1, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'SampleType',tlb,event_handler = 'SampleType_Events' ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro GetMatrix,matrix,str,K
;get rid of comments
nocomments=where(strpos(str,'#') ne 0,count)
if count eq 0 then return
str=strlowcase(str[nocomments])
n=n_elements(str)
wherereal=where(strpos(str,'real') ne -1)
whereimaginary=where(strpos(str,'imaginary') ne -1)
rowind=-1
colind=-1

if (wherereal[0] eq -1) and (whereimaginary[0] eq -1) then begin ;new file format
    MateleString=''
    for i = 0, n-1 do begin
    reads,str[i],rowind,colind,matelestring
;print,''
;    print,'str[i] ',str[i]
;    print,'rowind ',rowind
;    print,'colind ',colind
;    print,'matelestring ',matelestring
    rowind-=1
    colind-=1
    if strpos(matelestring,'i') eq -1 then begin ;real
    matele=double(matelestring)
    matrix[k,colind,rowind]=matele
    matrix[k,rowind,colind]=matele ;even if diagonal it is quicker to program this way
;    print,'mateler ',matele
    endif else begin
       if strpos(matelestring,'+') eq -1 then begin ;purely imaginary
       matele=double((strsplit(matelestring,'i',/extract))[0])
       matrix[k,colind,rowind]=complex(0,matele)
       matrix[k,rowind,colind]=complex(0,-matele)
;    print,'matelei ',matele
       endif else begin  ;complex
       complexstr=strsplit(matelestring,'+',/extract)
;       print,'matelestring ',matelestring
       realpart=double(complexstr[0])
;       print,'realpart ',realpart
       imaginarypart=double((strsplit(complexstr[1],'i',/extract))[0])
;       print,'imaginarypart ',imaginarypart
       matrix[k,colind,rowind]=complex(realpart,imaginarypart)
       matrix[k,rowind,colind]=complex(realpart,-imaginarypart)
       endelse
    endelse
    endfor
endif else begin
matele=double(0)
numbertype=''
for i = 0, n-1 do begin
reads,str[i],rowind,colind,matele,numbertype
rowind-=1
colind-=1
numbertype=strlowcase(strtrim(numbertype,2))
if numbertype ne 'real' and numbertype ne 'imaginary' then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'Matrix elements in Hoegni''s old file format must be specified by keyword ''real'' or ''imaginary''')
return
endif
if numbertype eq 'real' then begin
matrix[k,colind,rowind]=matele
matrix[k,rowind,colind]=matele ;even if diagonal it is quicker to program this way
endif else begin
matrix[k,colind,rowind]=complex(0,matele)
matrix[k,rowind,colind]=complex(0,-matele)
endelse
endfor
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MatrixToMemory,Matrix,index,event
widget_control,event.top,get_uvalue = pState
designation=(*pstate).Parameter_Table_Input[0,index]
designation=designation[0]
if strlowcase(size(*(*pstate).MatricesInMemory,/tname)) eq 'struct' then begin
wheretag=where(strupcase(designation) eq tag_names(*(*pstate).MatricesInMemory),count)
if count ne 0 then return
*(*pstate).MatricesInMemory=create_struct(*(*pstate).MatricesInMemory,designation,matrix)
endif else begin
*(*pstate).MatricesInMemory=create_struct(designation,matrix)
endelse
(*pstate).Parameter_Table_Input[2,index]+='_m'
widget_control,(*pstate).Parameter_Table,set_value=(*pstate).Parameter_Table_Input
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ConstructMatrices,event,fail
widget_control,event.top,get_uvalue = pState
fail=0
Matrix_Dimension=(*pstate).Matrix_Dimension
beta=(*pstate).constants.beta
Source_Dir=(*pstate).Source_Dir
;first deal with the Zeeman matrices
;make sure that there are matrices entitled Bx, By and Bz
Parameter_Table_Input=(*pstate).Parameter_Table_Input
Entries=reform(Parameter_Table_Input[0,*])
WhereEntry=where(Entries ne '',Num_Entries)
if Num_Entries eq 0 then begin
fail=1
return
endif
if Matrix_Dimension lt 2 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Matrix Dimension Must be Greater Than Two')
fail=1
return
endif
Entries=Entries[WhereEntry]
*(*pstate).Entries=Entries
Type=reform(Parameter_Table_Input[2,*])
*(*pstate).Type=Type

indexf_x=where(Type eq 'Bx',countxf)
indexm_x=where(Type eq 'Bx_m',countxm)
if (countxf eq 0) and (countxm eq 0) then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'One or more Bx Matrix files must be specified')
fail=1
return
endif
sum=[indexf_x,indexm_x]
index=where(sum ne -1)
index=sum[index]
Zeeman_Pointers=index
countx=countxf+countxm
if countxf ne 0 then begin
    if countxf eq 1 then begin
    BxFileName=strarr(1)
    BxFileName[0]=Source_Dir+reform(Parameter_Table_Input[1,indexf_x])
    endif else begin
    BxFileName=Source_Dir+reform(Parameter_Table_Input[1,indexf_x[0]])
    for i = 1, countxf-1 do begin
    BxFileName=[BxFileName,Source_Dir+reform(Parameter_Table_Input[1,indexf_x[i]])]
    endfor
    endelse
endif
;
indexf_y=where(Type eq 'By',countyf)
indexm_y=where(Type eq 'By_m',countym)
if (countyf eq 0) and (countym eq 0) then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'One or more By Matrix files must be specified')
fail=1
return
endif
sum=[indexf_y,indexm_y]
index=where(sum ne -1)
index=sum[index]
Zeeman_Pointers=[Zeeman_Pointers,index]
county=countyf+countym
if countyf ne 0 then begin
    if countyf eq 1 then begin
    ByFileName=strarr(1)
    ByFileName[0]=Source_Dir+reform(Parameter_Table_Input[1,indexf_y])
    endif else begin
    ByFileName=Source_Dir+reform(Parameter_Table_Input[1,indexf_y[0]])
    for i = 1, countyf-1 do begin
    ByFileName=[ByFileName,Source_Dir+reform(Parameter_Table_Input[1,indexf_y[i]])]
    endfor
    endelse
endif
;

indexf_z=where(Type eq 'Bz',countzf)
indexm_z=where(Type eq 'Bz_m',countzm)
if (countzf eq 0) and (countzm eq 0) then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'One or more Bz Matrix files must be specified')
fail=1
return
endif
sum=[indexf_z,indexm_z]
index=where(sum ne -1)
index=sum[index]
Zeeman_Pointers=[Zeeman_Pointers,index]
countz=countzf+countzm
if countzf ne 0 then begin
    if countzf eq 1 then begin
    BzFileName=strarr(1)
    BzFileName[0]=Source_Dir+reform(Parameter_Table_Input[1,indexf_z])
    endif else begin
    BzFileName=Source_Dir+reform(Parameter_Table_Input[1,indexf_z[0]])
    for i = 1, countzf-1 do begin
    BzFileName=[BzFileName,Source_Dir+reform(Parameter_Table_Input[1,indexf_z[i]])]
    endfor
    endelse
endif



*(*pstate).Zeeman_Pointers=Zeeman_Pointers
(*pstate).Zeeman_Matrix_Counter=[countx,county,countz]
;
Bx=dcomplexarr(countx,Matrix_Dimension,Matrix_Dimension)
By=dcomplexarr(county,Matrix_Dimension,Matrix_Dimension)
Bz=dcomplexarr(countz,Matrix_Dimension,Matrix_Dimension)
;
line=''

if countxf ne 0 then begin
    FOR K = 0, countxf-1 DO BEGIN
    nlines=(file_lines(BxFileName[K]))[0]
    str=strarr(nlines)
    openr,lun,BxFileName[K],/get_lun
    for i = 0, nlines-1 do begin
    readf,lun,line
    str[i]=strtrim(line,2)
    endfor
    free_lun,lun,/force
    ;print,'str ',str
    ;
    GetMatrix,Bx,str,K
    matrix=reform(Bx[k,*,*])
    MatrixToMemory,matrix,indexf_x[k],event
    ENDFOR
endif
;
if countxm ne 0 then begin
    FOR K = 0, countxm-1 DO BEGIN
    designation=reform(Parameter_Table_Input[0,indexm_x[k]])
    designation=designation[0]
    wheredes=where(strupcase(designation) eq tag_names(*(*pstate).MatricesInMemory))
    matrix=(*(*pstate).MatricesInMemory).(wheredes)
    Bx[k+countxf,*,*]=matrix
    ENDFOR
endif
Bx*=beta


if countyf ne 0 then begin
    FOR K = 0, countyf-1 DO BEGIN
    nlines=(file_lines(ByFileName[K]))[0]
    str=strarr(nlines)
    openr,lun,ByFileName[K],/get_lun
    for i = 0, nlines-1 do begin
    readf,lun,line
    str[i]=strtrim(line,2)
    endfor
    free_lun,lun,/force
    ;print,'str ',str
    ;
    GetMatrix,By,str,K
    matrix=reform(By[k,*,*])
    MatrixToMemory,matrix,indexf_y[k],event
    ENDFOR
endif
;
if countym ne 0 then begin
    FOR K = 0, countym-1 DO BEGIN
    designation=reform(Parameter_Table_Input[0,indexm_y[k]])
    designation=designation[0]
    wheredes=where(strupcase(designation) eq tag_names(*(*pstate).MatricesInMemory))
    matrix=(*(*pstate).MatricesInMemory).(wheredes)
    By[k+countyf,*,*]=matrix
    ENDFOR
endif
By*=beta

;
if countzf ne 0 then begin
    FOR K = 0, countzf-1 DO BEGIN
    nlines=(file_lines(BzFileName[K]))[0]
    str=strarr(nlines)
    openr,lun,BzFileName[K],/get_lun
    for i = 0, nlines-1 do begin
    readf,lun,line
    str[i]=strtrim(line,2)
    endfor
    free_lun,lun,/force
    ;print,'str ',str
    ;
    GetMatrix,Bz,str,K
    matrix=reform(Bz[k,*,*])
    MatrixToMemory,matrix,indexf_z[k],event
    ENDFOR
endif
;
if countzm ne 0 then begin
    FOR K = 0, countzm-1 DO BEGIN
    designation=reform(Parameter_Table_Input[0,indexm_z[k]])
    designation=designation[0]
    wheredes=where(strupcase(designation) eq tag_names(*(*pstate).MatricesInMemory))
    matrix=(*(*pstate).MatricesInMemory).(wheredes)
    Bz[k+countzf,*,*]=matrix
    ENDFOR
endif

Bz*=beta
;
;print,'countx: ',countx
;
;print,'county: ',county
;
;print,'countz: ',countz
n_Zee=countx+county+countz

ZeemanMatrices=dcomplexarr(n_Zee,Matrix_Dimension,Matrix_Dimension)
ZeemanMatrices[0:countx-1,*,*]=Bx
ZeemanMatrices[countx:countx+county-1,*,*]=By
ZeemanMatrices[countx+county:countx+county+countz-1,*,*]=Bz
*(*pstate).ZeemanMatrices=ZeemanMatrices

;*(*pstate).Zeeman_Pointers=Zeeman_Pointers
;(*pstate).Zeeman_Matrix_Counter=[countx,county,countz]


;
;help,ZeemanMatrices
;print,reform(ZeemanMatrices[1,*,*])
;remaining matrices
;
;print,n_elements(Entries)
;print,Num_Entries
;print,n_Zee
if Num_Entries eq n_Zee then return
;ZeemanDesignations=['Bx','By','Bz']
;filter through

d=where(type eq 'Diamagnetism',countdia)

if countdia ne 0 then begin
(*pstate).Diamagnetism=[1,d]  ;the 1 means it should be included in model; the d is the index.
endif else begin
(*pstate).Diamagnetism=[0,0]
endelse

e=where(type eq 'ModelScale',countModelScale)

if countModelScale ne 0 then begin
(*pstate).ModelScaleFactor=[1,e]  ;the 1 means it should be included in model; the e is the index.
endif else begin
(*pstate).ModelScaleFactor=[0,0]
endelse

f=where(type eq 'MFT',countMFT)
if countMFT ne 0 then begin
(*pstate).MFTC_Pointers=[1,f]  ;the 1 means it should be included in model; the f is the index.
  if (*pState).MFT_Treatment eq 2 then begin
  MFTCSpin_Pointers=intarr(3)  
  f=where(Entries eq (*pState).SxMatrixName,countMFT)
     if countMFT eq 1 then begin
     MFTCSpin_Pointers[0]=f[0]
    endif else begin
    fail=1
    void=dialog_message(dialog_parent=event.top,/error, $
    'The designation + '+(*pState).SxMatrixName+' is not found or occurs more than once')
    return
    endelse
  f=where(Entries eq (*pState).SyMatrixName,countspins)
  f=f[0]
    if countspins eq 1 then begin
    MFTCSpin_Pointers[1]=f[0]
    endif else begin
    fail=1
    void=dialog_message(dialog_parent=event.top,/error, $
    'The designation + '+(*pState).SyMatrixName+' is not found or occurs more than once')
    return
    endelse
  f=where(Entries eq (*pState).SzMatrixName,countspins)
  f=f[0]
    if countspins eq 1 then begin
    MFTCSpin_Pointers[2]=f[0]
    endif else begin
    fail=1
    void=dialog_message(dialog_parent=event.top,/error, $
    'The designation + '+(*pState).SzMatrixName+' is not found or occurs more than once')
    return
    endelse 
  endif
endif else begin
(*pstate).MFTC_Pointers=[0,0]
endelse


if Num_Entries eq (n_Zee+countdia+countModelScale+countMFT) then return

jf=where(type eq 'Parameter',countf)
jm=where(type eq 'Parameter_m',countm)
sum=[jf,jm]
j=where(sum ne -1)
j=sum[j]
*(*pstate).AddMat_Pointers=j
;print,'j: ',j
AdditionalMatrices=dcomplexarr((Num_Entries-n_Zee-countdia-countModelScale-countMFT), $
          Matrix_Dimension,Matrix_Dimension)
if countf ne 0 then begin
    for k=0,countf-1 do begin
    index=j[k]
    MatFileName=Source_Dir+reform(Parameter_Table_Input[1,index])
    n=(file_lines(MatFileName))[0]
    str=strarr(n)
    openr,lun,MatFileName,/get_lun
        for i = 0, n-1 do begin
        readf,lun,line
        str[i]=strtrim(line,2)
        endfor
    free_lun,lun,/force

    GetMatrix,AdditionalMatrices,str,K
    matrix=reform(AdditionalMatrices[k,*,*])
    MatrixToMemory,matrix,index,event
    endfor
endif

if countm ne 0 then begin
    FOR K = 0, countm-1 DO BEGIN
    designation=reform(Parameter_Table_Input[0,jm[k]])
    designation=designation[0]
    wheredes=where(strupcase(designation) eq tag_names(*(*pstate).MatricesInMemory))
    matrix=(*(*pstate).MatricesInMemory).(wheredes)
    AdditionalMatrices[k+countf,*,*]=matrix
    ENDFOR
endif


*(*pstate).AdditionalMatrices=AdditionalMatrices
;everything is now in memory
;now write the spin matrices
;
IF (countMFT ne 0) and ((*pState).MFT_Treatment eq 2) THEN BEGIN
Spinmatrices=dcomplexarr(3,Matrix_Dimension,Matrix_Dimension)
FOR K = 0, 2 DO BEGIN
designation=reform(Parameter_Table_Input[0,MFTCSpin_Pointers[k]])
designation=designation[0]
wheredes=where(strupcase(designation) eq tag_names(*(*pstate).MatricesInMemory))
Spinmatrices[k,*,*]=(*(*pstate).MatricesInMemory).(wheredes)
ENDFOR
*(*pstate).Spinmatrices=Spinmatrices
ENDIF




;for i=0,4 do begin
;for j=10,14 do begin
;print,'row ',i
;print,'col ',j
;print,'AdditionalMatrices[1,j,i] ',reform(AdditionalMatrices[1,j,i])
;print,''
;endfor
;endfor

;print,reform(AdditionalMatrices[0,*,*])
;print,'n_elements(AdditionalMatrices) :',(Num_Entries-n_Zee-countdia-countModelScale-countMFT)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function ValueConvert,values,event
widget_control,event.top,get_uvalue = pState
;operators=['*','/','+','-']
operators=['*','/','*','/']
;
Designations=reform((*pstate).Parameter_Table_Input[0,*])
wheredes=where(Designations ne '',count)
if count eq 0 then return,{values:values}
Designations=Designations[wheredes]
;mDesignations='-'+Designations
n=n_elements(values)
value_dbl_array=dblarr(n)
TypeString_Array=strarr(n)
ExpressionString_Array=strarr(n)

for i = 0,n-1 do begin
void=where(strupcase(values[i]) eq strupcase(Designations), count)
if count ne 0 then values[i]+='*1.0'
;print,'mDesignations ',mDesignations
;void=where(strmid(values[i],0,1) eq '-', count)
;print,'values[i]: ',values[i]
;print,'void: ',void
;if count ne 0 then values[i]='-1.0*('+strmid(values[i],1)+')'
;if i lt 10 then print,'values[i] ',values[i]
endfor

expression=intarr(n,4)
for i = 0,3 do begin
expression[*,i]=strpos(values, operators[i])
endfor
;
for i = 0,n-1 do begin
type=reform(expression[i,*])
    if total(type) eq -4 then begin ;convert to double
    value_dbl_array[i]=double(values[i])
;         print,'value_dbl_array = ',value_dbl_array
    endif else begin
       if n_elements(stringexpressionindex) eq 0 then begin
       stringexpressionindex=i
       endif else begin
       stringexpressionindex=[stringexpressionindex,i]
       endelse
    endelse
endfor
m=n_elements(stringexpressionindex)
if m ne 0 then begin
ExpressionString_Array[stringexpressionindex]=values[stringexpressionindex]

    for i = 0,m-1 do begin
    ;split the string
    type=expression[stringexpressionindex[i],*]
;    print,'i: ',i
;    print,'stringexpressionindex[i]: ',stringexpressionindex[i]
;    print,'type: ',type
;    help,type
    whereoperator=where(type ne -1)
    operator=operators[whereoperator[0]]
;    print,'operator: ',operator
    components=strtrim(strsplit(values[stringexpressionindex[i]],operator,/extract),2)
    components_typestring=components
       found=0
       for j = 0,1 do begin
       wheredes=where(strmatch(Designations,components[j],/fold_case) ne 0,count)
         if count ne 0 then begin
         components[j]=value_dbl_array[wheredes[0]]
         components_typestring[j]='p('+strtrim(string(wheredes[0]),2)+')'
         found=1
         endif
       endfor
         if found eq 1 then begin
         expr=strjoin(components,operator)
         void=execute('value_dbl_array[stringexpressionindex[i]]='+expr)
         expr_string=strjoin(components_typestring,operator)
;         print,'expr_string ',expr_string 
         TypeString_Array[stringexpressionindex[i]]=expr_string
         endif else begin ;forget it
           value_dbl_array[stringexpressionindex[i]]=0.0
         endelse
    endfor
endif

;print,'values ',values
values=value_dbl_array
values_struc={values:values, $
           TypeString_Array:TypeString_Array, $
           ExpressionString_Array:ExpressionString_Array}

return,values_struc
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ReturnHamiltonian,event,field,theta,phi,H,refine=refine
widget_control,event.top,get_uvalue = pState
theta_rad=theta*!DTOR
phi_rad=phi*!DTOR
Parameter_Table_Input=(*pstate).Parameter_Table_Input

Matrix_Dimension=(*pstate).Matrix_Dimension
ZeemanMatrices=*(*pstate).ZeemanMatrices
Zeeman_Pointers=*(*pstate).Zeeman_Pointers
Counter=(*pstate).Zeeman_Matrix_Counter; [countx,county,countz]
;
BxMat=ZeemanMatrices[0:Counter[0]-1,*,*]
ByMat=ZeemanMatrices[Counter[0]:Counter[0]+Counter[1]-1,*,*]
BzMat=ZeemanMatrices[Counter[0]+Counter[1]:Counter[0]+Counter[1]+Counter[2]-1,*,*]
;
Bx_Value=make_array(Counter[0],/double)
By_Value=make_array(Counter[1],/double)
Bz_Value=make_array(Counter[2],/double)

if keyword_set(refine) eq 0 then begin
values=reform(Parameter_Table_Input[3,*])
values_struc=ValueConvert(values,event)
values=values_struc.values
endif else begin
values=*(*pState).Refine_vals
endelse
;help,values
Bx_Value[*]=values[Zeeman_Pointers[0:Counter[0]-1]]
By_Value[*]=values[Zeeman_Pointers[Counter[0]:Counter[0]+Counter[1]-1]]
Bz_Value[*]=values[Zeeman_Pointers[Counter[0]+Counter[1]:Counter[0]+Counter[1]+Counter[2]-1]]
;
;
Bz_Value*=cos(theta_rad)
Bx_Value*=(sin(theta_rad)*cos(phi_rad))
By_Value*=(sin(theta_rad)*sin(phi_rad))
;

N=(size(ZeemanMatrices))[1]
H=dcomplexarr(Matrix_Dimension,Matrix_Dimension)
dHdB=dcomplexarr(Matrix_Dimension,Matrix_Dimension)

for i = 0,counter[0]-1 do begin
H+=field*reform(BxMat[i,*,*])*Bx_Value[i]
dHdB+=reform(BxMat[i,*,*])*Bx_Value[i]
endfor
for i = 0,counter[1]-1 do begin
H+=field*reform(ByMat[i,*,*])*By_Value[i]
dHdB+=reform(ByMat[i,*,*])*By_Value[i]
;print,'Hy: ',H
endfor
for i = 0,counter[2]-1 do begin
H+=field*reform(BzMat[i,*,*])*Bz_Value[i]
dHdB+=reform(BzMat[i,*,*])*Bz_Value[i]
endfor
;print,'H: ',H
*(*pstate).dHdB=dHdB
;check for existence of additional matrices

n_AdditionalMatrices=n_elements(*(*pstate).entries)-N $
              -(*pstate).Diamagnetism[0] $
              -(*pstate).ModelScaleFactor[0] $
              -(*pstate).MFTC_Pointers[0]

if n_AdditionalMatrices gt 0 then begin
AdditionalMatrices=*(*pstate).AdditionalMatrices
AddMat_Pointers=*(*pstate).AddMat_Pointers
ParameterInfoStruc=*(*pState).ParameterInfoStruc
;
    for i = 0, n_AdditionalMatrices-1 do begin
    index=AddMat_Pointers[i]
        if reform(ParameterInfoStruc.limits[index,0]) eq 1 then begin
        mat=reform(AdditionalMatrices[i,*,*])
         mat_Value=values[index]
         H+=mat*mat_Value
        endif
    endfor
endif

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro CalculateEnergies,event,field,theta,phi, $
    eigenvalues,eigenvectors=eigenvectors,refine=refine,Addterm=Addterm
widget_control,event.top,get_uvalue = pState

theta_rad=theta*!DTOR
phi_rad=phi*!DTOR
Parameter_Table_Input=(*pstate).Parameter_Table_Input

Matrix_Dimension=(*pstate).Matrix_Dimension
ZeemanMatrices=*(*pstate).ZeemanMatrices
;print,'theta: ',theta
;print,'phi: ',phi
;help,ZeemanMatrices
;for i=0,4 do begin
;for j=0,4 do begin
;print,'row ',i
;print,'col ',j
;print,'ZeemanMatrices[0,j,i] ',reform(ZeemanMatrices[0,j,i])
;print,''
;endfor
;endfor
;print,ZeemanMatrices
Zeeman_Pointers=*(*pstate).Zeeman_Pointers
Counter=(*pstate).Zeeman_Matrix_Counter; [countx,county,countz]
;
BxMat=ZeemanMatrices[0:Counter[0]-1,*,*]
ByMat=ZeemanMatrices[Counter[0]:Counter[0]+Counter[1]-1,*,*]
BzMat=ZeemanMatrices[Counter[0]+Counter[1]:Counter[0]+Counter[1]+Counter[2]-1,*,*]
;
Bx_Value=make_array(Counter[0],/double)
By_Value=make_array(Counter[1],/double)
Bz_Value=make_array(Counter[2],/double)

if keyword_set(refine) eq 0 then begin
values=reform(Parameter_Table_Input[3,*])
values_struc=ValueConvert(values,event)
values=values_struc.values
endif else begin
values=*(*pState).Refine_vals
endelse
;help,values
Bx_Value[*]=values[Zeeman_Pointers[0:Counter[0]-1]]
By_Value[*]=values[Zeeman_Pointers[Counter[0]:Counter[0]+Counter[1]-1]]
Bz_Value[*]=values[Zeeman_Pointers[Counter[0]+Counter[1]:Counter[0]+Counter[1]+Counter[2]-1]]
;
;
;print,Bx_Value
;print,By_Value
;print,Bz_Value
;
;
Bz_Value*=cos(theta_rad)
Bx_Value*=(sin(theta_rad)*cos(phi_rad))
By_Value*=(sin(theta_rad)*sin(phi_rad))
;


N=(size(ZeemanMatrices))[1]
H=dcomplexarr(Matrix_Dimension,Matrix_Dimension)
dHdB=dcomplexarr(Matrix_Dimension,Matrix_Dimension)


for i = 0,counter[0]-1 do begin
H+=field*reform(BxMat[i,*,*])*Bx_Value[i]
dHdB+=reform(BxMat[i,*,*])*Bx_Value[i]
endfor
for i = 0,counter[1]-1 do begin
H+=field*reform(ByMat[i,*,*])*By_Value[i]
dHdB+=reform(ByMat[i,*,*])*By_Value[i]
;print,'Hy: ',H
endfor
for i = 0,counter[2]-1 do begin
H+=field*reform(BzMat[i,*,*])*Bz_Value[i]
dHdB+=reform(BzMat[i,*,*])*Bz_Value[i]
endfor
;print,'H: ',H
*(*pstate).dHdB=dHdB
;check for existence of additional matrices

n_AdditionalMatrices=n_elements(*(*pstate).entries)-N $
              -(*pstate).Diamagnetism[0] $
              -(*pstate).ModelScaleFactor[0] $
              -(*pstate).MFTC_Pointers[0]

if n_AdditionalMatrices gt 0 then begin
AdditionalMatrices=*(*pstate).AdditionalMatrices
AddMat_Pointers=*(*pstate).AddMat_Pointers
ParameterInfoStruc=*(*pState).ParameterInfoStruc
;    print, ''
    for i = 0, n_AdditionalMatrices-1 do begin
    index=AddMat_Pointers[i]
;    print, 'ParameterInfoStruc.limits[0] ',ParameterInfoStruc.limits[index,0]
        if reform(ParameterInfoStruc.limits[index,0]) eq 1 then begin
        mat=reform(AdditionalMatrices[i,*,*])
;        mat_Value=(double(reform(Parameter_Table_Input[3,index])))[0]
;         print,'index: ',index
;         print,'values[6]: ',values[6]
;         print,''
         mat_Value=values[index]
         H+=mat*mat_Value
        endif
    endfor
endif


if keyword_set(AddTerm) then H+=Addterm

; (*pState).Algorithm_type=Method_Field_Type
; (*pState).EigenvalueRange_type=Range_Field_Type
; (*pState).EigenvalueTolerance_Value=Tolerance_field
; *(*pState).EigenvalueRange_Value=Range_field


if (*pstate).DerivOption eq 0 then begin
tstart=systime(/seconds)

  case (*pState).EigenvalueRange_type of
  0:   $
  begin
  eigenvalues=LA_EIGENQL(H,/double, $
      eigenvectors=eigenvectors,$
      method=(*pState).Algorithm_type,$
      tolerance=(*pState).EigenvalueTolerance_Value)
  end
  1:   $
  begin
  eigenvalues=LA_EIGENQL(H,/double, $
      eigenvectors=eigenvectors,$
      method=(*pState).Algorithm_type,$
      range=*(*pState).EigenvalueRange_Value,$
      tolerance=(*pState).EigenvalueTolerance_Value)
  end
  2:   $
  begin
  eigenvalues=LA_EIGENQL(H,/double, $
      eigenvectors=eigenvectors,$
      method=(*pState).Algorithm_type,$
      search_range=*(*pState).EigenvalueRange_Value,$
      tolerance=(*pState).EigenvalueTolerance_Value)
  end
  else:
  endcase

telapsed=systime(/seconds)-tstart
;print,'Time Taken for diagonalisation with eigenvectors = ',strtrim(string(telapsed),2),' seconds.'
endif else begin
;tstart=systime(/seconds)
  case (*pState).EigenvalueRange_type of
  0:   $
  begin
  eigenvalues=LA_EIGENQL(H,/double, $
      method=(*pState).Algorithm_type,$
      tolerance=(*pState).EigenvalueTolerance_Value)
  end
  1:   $
  begin
  eigenvalues=LA_EIGENQL(H,/double, $
      method=(*pState).Algorithm_type,$
      range=*(*pState).EigenvalueRange_Value,$
      tolerance=(*pState).EigenvalueTolerance_Value)
  end
  2:   $
  begin
  eigenvalues=LA_EIGENQL(H,/double, $
      method=(*pState).Algorithm_type,$
      search_range=*(*pState).EigenvalueRange_Value,$
      tolerance=(*pState).EigenvalueTolerance_Value)
  end
  else:
  endcase
;telapsed=systime(/seconds)-tstart
;print,'Time Taken for diagonalisation without eigenvectors = ',strtrim(string(telapsed),2),' seconds.'
endelse

;MINEIG=MIN(eigenvalues)
;eigenvalues-=MINEIG
;print,'eigenvalues routine',eigenvalues-mineig
;print,'eigenvalues routine',eigenvalues
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
widget_control,event.top,get_uvalue = pState
;Matrix_Dimension=(*pstate).Matrix_Dimension
if n_elements(field) eq 0 then field=*(*pstate).field
;print,'theta: ',theta
;print,'phi: ',phi
theta_rad=theta*!DTOR
phi_rad=phi*!DTOR
beta=(*pstate).constants.beta
;print,'theta: ',theta
;print,'phi: ',phi

IF (*pstate).DerivOption EQ 0 THEN BEGIN


dHdB=*(*pstate).dHdB/beta

MatMult=conj(eigenvectors)##dHdB##transpose(eigenvectors)

;help,MatMult
;Matrix_Dimension
n_eig=(size(eigenvectors))[2]
mome=dblarr(n_eig)
for i = 0, n_eig-1 do begin
mome[i]=-reform(MatMult[i,i])
endfor
mome=real_part(mome)
;print,'HF ',mome
;print,''
ENDIF ELSE BEGIN
FieldWidth=(*pstate).FieldWidth
FieldWidth=(double(FieldWidth))[0]
    if (field-fieldwidth) lt 0.0 then begin
    FieldWidth=2.0*field
    if fieldwidth lt 0 then fieldwidth=0.01
    (*pstate).FieldWidth=FieldWidth
    endif
Field2=Field+(FieldWidth/2.0)
;print,'Field2: ',Field2
CalculateEnergies,event,Field2,theta,phi,eigenvalues,refine=refine
E2=eigenvalues
;print,'E2: ',E2
Field1=Field-(FieldWidth/2.0)
;print,'Field1: ',Field1
CalculateEnergies,event,Field1,theta,phi,eigenvalues,refine=refine
;print,'E1: ',eigenvalues
mome=-(E2-eigenvalues)/(FieldWidth*beta)

;print,'3diag ',mome
;print,''

ENDELSE

if (*pstate).ModelScaleFactor[0] eq 1 and $
(reform((*(*pState).ParameterInfoStruc).limits[(*pstate).ModelScaleFactor[1],0]) eq 1) then begin
index=(*pstate).ModelScaleFactor[1]
    if keyword_set(refine) eq 0 then begin
    mome*=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    mome*=(*(*pState).Refine_vals)[index]
    endelse
endif
;
;
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calculate_MagCurve_SelfConsistent_1,event,refine=refine
widget_control,event.top,get_uvalue = pState
    index=(*pstate).MFTC_Pointers[1]
    if keyword_set(refine) eq 0 then begin
    lambda=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    lambda=(*(*pState).Refine_vals)[index]
    endelse

kb=(*pstate).constants.kb
conv=(*pstate).constants.conv
Matrix_Dimension=(*pstate).Matrix_Dimension
if Matrix_Dimension lt 2 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Matrix Dimension Must be Greater Than Two')
return
endif

temperature=*(*pState).temperature
fieldarr=*(*pState).field
n_temperature=n_elements(temperature)
MagMom=dblarr(n_temperature)
Sample_Type=(*pstate).Sample_Type
if ((*pstate).Diamagnetism[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).Diamagnetism[1],0]) eq 1) then begin
    index=(*pstate).Diamagnetism[1]
    if keyword_set(refine) eq 0 then begin
    DiamagVal=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    DiamagVal=(*(*pState).Refine_vals)[index]
    endelse
endif
;
MA=0.0
MB=0.0
Iterations=0
Criterion=(*pState).MFT_Criterion
Test=0.0
fieldarr/=1e4


IF Sample_Type EQ 1 THEN BEGIN ; single crystal
theta=(*pstate).Theta_sc
phi=(*pstate).phi_sc
;
;the magnetic moments in the two sublattices
;print,'temperaturearr ',temperaturearr
for i = 0, n_temperature-1 do begin
while Test lt Criterion do begin
;Iterations+=1
MA_Last=MA
;sublattice A
field=fieldarr[i]+lambda*MB
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'eigenvalues: ',eigenvalues
if lambda gt 0 then begin
MB=MA
endif else begin
;sublattice B
field=fieldarr[i]+lambda*MA
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors;
MB=total(MOM)
endelse
Test=MA_Last/MA
if Test gt 1.0 then Test=1/Test
endwhile
;print,'Test: ',Test
;print,'MA: ',MA
;print,'MB: ',MB
;print,'Temperature: ',temperature
;print,'fieldarr[i]: ',fieldarr[i]
;print,'Iterations: ',Iterations
;print,' '
;Iterations=0
Test=0.0
MagMom[i]=(MA+MB)/2.0
endfor
  if n_elements(DiamagVal) ne 0 then begin
  MagMom+=DiamagVal*fieldarr*1e4/conv
  endif
;


*(*pState).yt=MagMom
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event
;print,'MagMom: ',MagMom
return
ENDIF

theta_start=(*pState).theta_start
theta_end=(*pState).theta_end
theta_nsteps=(*pState).theta_nsteps
phi_start=(*pState).phi_start
phi_end=(*pState).phi_end
phi_nsteps=(*pState).phi_nsteps
if theta_nsteps eq 1 then begin
thetavals=make_array(1)
thetavals[0]=theta_start
endif else begin
dx=(theta_end-theta_start)/(theta_nsteps-1)
thetavals=theta_start+dx*dindgen(theta_nsteps)
endelse
if phi_nsteps eq 1 then begin
phivals=make_array(1)
phivals[0]=phi_start
endif else begin
dx=(phi_end-phi_start)/(phi_nsteps-1)
phivals=phi_start+dx*dindgen(phi_nsteps)
endelse
sintharr=sin(thetavals*!DTOR)
sinthsum=total(sintharr*phi_nsteps)
MagMom=dblarr(n_temperature)
;
Test=0.0
Iterations=0
        MA=0.1
        MB=0.1
for i = 0, n_temperature-1 do begin
MagMom_sum=0.0
         for j = 0, theta_nsteps-1 do begin
        theta=thetavals[j]
        sinth=sintharr[j]
        for k = 0, phi_nsteps-1 do begin
        phi=phivals[k]
        MA_Test=0.01
       while Test lt Criterion and (iterations lt 100) do begin
        MA_LastTest=MA_Test
        Iterations+=1
        ;sublattice A
         field=fieldarr[i]+lambda*MB

         CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
        MINEIG=MIN(eigenvalues)
       eigenvalues-=MINEIG
       eigenvalues-=5
        CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
       BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
       BoltzFactors/=total(BoltzFactors)
       mome*=BoltzFactors
       MA_sum=total(mome)
       MA_Test=MA_sum
       MA=MA_sum*sinth
       MA_sum=0.0
;
if lambda gt 0 then begin
MB=MA
endif else begin
       ;sublattice B
         field=fieldarr[i]+lambda*MA
         CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
        MINEIG=MIN(eigenvalues)
       eigenvalues-=MINEIG
       eigenvalues-=5
        CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
       BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
       BoltzFactors/=total(BoltzFactors)
       mome*=BoltzFactors
       MB_sum=total(mome)
       MB=MB_sum*sinth
       MB_sum=0.0
endelse
Test=MA_LastTest/MA_Test
if Test gt 1.0 then Test=1/Test
;print,'MA: ',MA

          endwhile
MagMom_sum+=(MA+MB)/2.0
test=0.0
iterations=0
        endfor
    endfor
MagMom[i]=MagMom_sum/sinthsum
;
;print,'MagMom[i]: ',MagMom[i]
;print,'MA: ',MA
;print,'MB: ',MB
;print,'temperature[i]: ',temperature[i]
;print,' '


endfor
  if n_elements(DiamagVal) ne 0 then begin
   MagMom+=DiamagVal*fieldarr*1e4/conv
  endif

;
;
*(*pState).yt=MagMom
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calculate_MagCurve_SelfConsistent_2,event,refine=refine
widget_control,event.top,get_uvalue = pState

    index=(*pstate).MFTC_Pointers[1]
    if keyword_set(refine) eq 0 then begin
    Jint=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    Jint=(*(*pState).Refine_vals)[index]
    endelse

kb=(*pstate).constants.kb
conv=(*pstate).constants.conv
Matrix_Dimension=(*pstate).Matrix_Dimension
if Matrix_Dimension lt 2 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Matrix Dimension Must be Greater Than Two')
return
endif

temperature=*(*pState).temperature
fieldarr=*(*pState).field
n_temperature=n_elements(temperature)
MagMom=dblarr(n_temperature)
Sample_Type=(*pstate).Sample_Type
if ((*pstate).Diamagnetism[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).Diamagnetism[1],0]) eq 1) then begin
    index=(*pstate).Diamagnetism[1]
    if keyword_set(refine) eq 0 then begin
    DiamagVal=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    DiamagVal=(*(*pState).Refine_vals)[index]
    endelse
endif
;
fieldarr/=1e4




Iterations=0
Criterion=(*pState).MFT_Criterion
Test=0.0
Chi=dblarr(n_temperature)

Sample_Type=(*pstate).Sample_Type

Sx=reform((*(*pstate).SpinMatrices)[0,*,*])
Sy=reform((*(*pstate).SpinMatrices)[1,*,*])
Sz=reform((*(*pstate).SpinMatrices)[2,*,*])

IF Sample_Type EQ 1 THEN BEGIN
theta=(*pstate).Theta_sc
phi=(*pstate).phi_sc
;print,'eigenvalues :',eigenvalues
;
for i = 0, n_temperature-1 do begin
field=fieldarr[i]
Iterations=0
Test=0.0
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
;print,'iterations: ',iterations
;print,'test ',test
Iterations=0
Test=0.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'temperature[i] ',temperature[i]  
;print,'field ',field  
;print,'MA: ',MA
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MB=total(MOM)
;print,'MB: ',MB
MagMom[i]=(MA+MB)/2.0
;print,'MagMom ',MagMom
;print,''
endfor
;
  if n_elements(DiamagVal) ne 0 then begin
   MagMom+=DiamagVal*fieldarr*1e4/conv
  endif

*(*pState).yt=MagMom
return
ENDIF

theta_start=(*pState).theta_start
theta_end=(*pState).theta_end
theta_nsteps=(*pState).theta_nsteps
phi_start=(*pState).phi_start
phi_end=(*pState).phi_end
phi_nsteps=(*pState).phi_nsteps
if theta_nsteps eq 1 then begin
thetavals=make_array(1)
thetavals[0]=theta_start
endif else begin
dx=(theta_end-theta_start)/(theta_nsteps-1)
thetavals=theta_start+dx*dindgen(theta_nsteps)
endelse
if phi_nsteps eq 1 then begin
phivals=make_array(1)
phivals[0]=phi_start
endif else begin
dx=(phi_end-phi_start)/(phi_nsteps-1)
phivals=phi_start+dx*dindgen(phi_nsteps)
endelse

sintharr=sin(thetavals*!DTOR)
;print,'total(sintharr) ',total(sintharr)
sinthsum=total(sintharr*phi_nsteps)
MagMom=dblarr(n_temperature)
;
 ;   print,'theta_nsteps ',theta_nsteps 

for i = 0, n_temperature-1 do begin
field=fieldarr[i]
MA=0.0
MagMom_sum=0.0
MB=0.0
     for j = 0, theta_nsteps-1 do begin
     theta=thetavals[j]
     sinth=sintharr[j]
 ;    print,'sinth ',sinth 
  ;  print,'theta ',theta 
     
        for k = 0, phi_nsteps-1 do begin
        phi=phivals[k]
;
        Iterations=0
         Test=0.0
         Szex=0.1d
         Sxex=0.1d
         Syex=0.1d
         AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
         AddTermA_Last=AddTermA
         AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
         AddTermB_Last=AddTermB
;
          while (Test lt Criterion) and (iterations lt 100) do begin
          Iterations+=1
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for l = 0, n_eigenvalues-1 do begin
Szex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for l = 0, n_eigenvalues-1 do begin
Syex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for l = 0, n_eigenvalues-1 do begin
Sxex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for l = 0, n_eigenvalues-1 do begin
Szex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for l = 0, n_eigenvalues-1 do begin
Syex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for l = 0, n_eigenvalues-1 do begin
Sxex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
;print,'iterations: ',iterations
;print,'test ',test
          endwhile
Iterations=0
Test=0.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'temperature[i] ',temperature[i]  
;print,'MA: ',MA
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MB=total(MOM)
;print,'MB: ',MB
Mom=(MA+MB)/2.0
Mom*=sinth
MagMom_sum+=Mom
        endfor
    endfor
MagMom[i]=MagMom_sum/sinthsum
;
;
;print,'MagMom[i]: ',MagMom[i]
;print,'MA: ',MA
;print,'MB: ',MB
;print,'temperature[i]: ',temperature[i]
;print,' '


endfor
  if n_elements(DiamagVal) ne 0 then begin
   MagMom+=DiamagVal*fieldarr*1e4/conv
  endif

*(*pState).yt=MagMom

if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calculate_MagCurve,event,refine=refine
widget_control,event.top,get_uvalue = pState

fail=0
ConstructMatrices,event,fail
if fail eq 1 then return

;print,(*pstate).MFTC_Pointers[0]
;print,(*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]

if ((*pstate).MFTC_Pointers[0] eq 1) and $
   (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) and $
    (*pstate).MFT_Treatment ne 0 then begin
    index=(*pstate).MFTC_Pointers[1]
    if keyword_set(refine) eq 0 then begin
    lambda=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
      if lambda eq 0.0 then begin
      msg=strarr(3)
      msg[0]='Initial Value of lambda/Jint should be non zero'
      msg[1]='to indicate whether a ferromagnetic or '
      msg[2]='antiferromagnetic interaction is to be expected.'
      void=dialog_message(dialog_parent=event.top,/error, msg)
      return
      endif
    endif else begin
    lambda=(*(*pState).Refine_vals)[index]
   endelse
    if (*pstate).MFT_Treatment eq 1 then Calculate_MagCurve_SelfConsistent_1,event,refine=refine
    if (*pstate).MFT_Treatment eq 2 then Calculate_MagCurve_SelfConsistent_2,event,refine=refine
    return
 endif

kb=(*pstate).constants.kb
conv=(*pstate).constants.conv
Matrix_Dimension=(*pstate).Matrix_Dimension
if Matrix_Dimension lt 2 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Matrix Dimension Must be Greater Than Two')
return
endif

temperature=*(*pState).temperature
fieldarr=*(*pState).field
n_temperature=n_elements(temperature)
Sample_Type=(*pstate).Sample_Type



if ((*pstate).Diamagnetism[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).Diamagnetism[1],0]) eq 1) then begin
    index=(*pstate).Diamagnetism[1]
    if keyword_set(refine) eq 0 then begin
    DiamagVal=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    DiamagVal=(*(*pState).Refine_vals)[index]
    endelse
endif



;Determine number of unique fields, their values and locations in the fieldarr
UniqueIndices=uniq(fieldarr)
UniqueValues=fieldarr[UniqueIndices]/1e4
NUniqueValues=n_elements(UniqueValues)
;;
;print,'fieldarr: ',fieldarr
;print,'UniqueValues: ',UniqueValues
;
IF Sample_Type EQ 1 THEN BEGIN ; single crystal
theta=(*pstate).Theta_sc
phi=(*pstate).phi_sc
;
EigenvalArr=dblarr(NUniqueValues,Matrix_Dimension)
MagMomArr=dblarr(NUniqueValues,Matrix_Dimension)
MagMom=dblarr(n_temperature)
;
for i = 0, NUniqueValues-1 do begin
field=UniqueValues[i]
;print,'field: ',field
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
  if (i eq 0) and (n_elements(eigenvalues) ne Matrix_Dimension) then begin ;redefine array size
  n_eig=n_elements(eigenvalues)
  EigenvalArr=dblarr(NUniqueValues,n_eig)
  MagMomArr=dblarr(NUniqueValues,n_eig)
  endif
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
;print,'eigenvalues: ',eigenvalues
EigenvalArr[i,*]=eigenvalues
MagMomArr[i,*]=mome
endfor
;print,'eigenvalues: ',EigenvalArr[0,*]
;print,'MagMom: ',MagMomArr[0,*]
;print,'mome :',mome
;
for i = 0, n_temperature-1 do begin
t=temperature[i]
;which set of eigenvalues to select
EigsetIndex=where(i le UniqueIndices)
EigsetIndex=EigsetIndex[0]
;help,EigenvalArr
;print,'EigsetIndex ',EigsetIndex

eigenvalues=reform(EigenvalArr[EigsetIndex,*])
mome=reform(MagMomArr[EigsetIndex,*])
BoltzFactors=exp(-eigenvalues/(kb*t))
BoltzFactors/=total(BoltzFactors)
field=UniqueValues[EigsetIndex]
;
MOM=mome*BoltzFactors
;print,'field: ',field
;print,'t: ',t
;print,'Mom: ',mom
;print,'mome: ',mome
;print,'BoltzFactors: ',BoltzFactors
;
;MOM_SUM=total(MOM)
;
MagMom[i]=total(MOM)
if n_elements(DiamagVal) ne 0 then begin
MagMom[i]+=DiamagVal*field*1e4/conv
endif
endfor



*(*pState).yt=MagMom
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event
;print,'MagMom: ',MagMom
return
ENDIF
theta_start=(*pState).theta_start
theta_end=(*pState).theta_end
theta_nsteps=(*pState).theta_nsteps
phi_start=(*pState).phi_start
phi_end=(*pState).phi_end
phi_nsteps=(*pState).phi_nsteps
if theta_nsteps eq 1 then begin
thetavals=make_array(1)
thetavals[0]=theta_start
endif else begin
dx=(theta_end-theta_start)/(theta_nsteps-1)
thetavals=theta_start+dx*dindgen(theta_nsteps)
endelse
if phi_nsteps eq 1 then begin
phivals=make_array(1)
phivals[0]=phi_start
endif else begin
dx=(phi_end-phi_start)/(phi_nsteps-1)
phivals=phi_start+dx*dindgen(phi_nsteps)
endelse
sintharr=sin(thetavals*!DTOR)
sinthsum=total(sintharr*phi_nsteps)


EigenvalArr=dblarr(NUniqueValues,theta_nsteps,phi_nsteps,Matrix_Dimension)
MagMomArr=dblarr(NUniqueValues,theta_nsteps,phi_nsteps,Matrix_Dimension)
n_eig=Matrix_Dimension
for i = 0, NUniqueValues-1 do begin
        field=UniqueValues[i]
    for j = 0, theta_nsteps-1 do begin
        theta=thetavals[j]
        for k = 0, phi_nsteps-1 do begin
        phi=phivals[k]
        CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
        if (i+j+k eq 0) and (n_elements(eigenvalues) ne Matrix_Dimension) then begin ;redefine array size
    n_eig=n_elements(eigenvalues)
    EigenvalArr=dblarr(NUniqueValues,theta_nsteps,phi_nsteps,n_eig)
    MagMomArr=dblarr(NUniqueValues,theta_nsteps,phi_nsteps,n_eig)
    endif

        if (*pState).EigenvalueRange_type eq 2 then begin
        ; if searching for eignevalues in a certain range then there is a possibilty
        ; that a different number of eignenvalues are delivered for different
    ; fields and orientations
      if (i+j+k ne 0) and (n_eig ne n_elements(eigenvalues)) then begin
        if n_eig gt n_elements(eigenvalues) then begin ;redefine array
        n_eig = n_elements(eigenvalues)
        EigenvalArr_Temp=dblarr(NUniqueValues,theta_nsteps,phi_nsteps,n_eig)
        MagMomArr_Temp=dblarr(NUniqueValues,theta_nsteps,phi_nsteps,n_eig)
        EigenvalArr_Temp=EigenvalArr[*,*,*,0:n_eig-1]
        MagMomArr_Temp=MagMomArr[*,*,*,0:n_eig-1]
        EigenvalArr=EigenvalArr_Temp
        MagMomArr=MagMomArr_Temp
        endif else begin
        eigenvalues=eigenvalues[0:n_eig-1]
        eigenvectors=eigenvectors[*,0:n_eig-1]
        endelse
      endif
        endif


        MINEIG=MIN(eigenvalues)
       eigenvalues-=MINEIG
       eigenvalues-=5
        CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
        EigenvalArr[i,j,k,*]=eigenvalues
        MagMomArr[i,j,k,*]=mome
        endfor
    endfor
endfor
;
moment_arr=dblarr(n_temperature)


for i = 0, n_temperature-1 do begin
t=temperature[i]
EigsetIndex=where(i le UniqueIndices)
EigsetIndex=EigsetIndex[0]
field=UniqueValues[EigsetIndex]
;
    for j = 0, theta_nsteps-1 do begin
       sinth=sintharr[j]
       for k = 0, phi_nsteps-1 do begin
       Eigenvalues=reform(EigenvalArr[EigsetIndex,j,k,*])
       moment_master=reform(MagMomArr[EigsetIndex,j,k,*])
       mome=moment_master
       BoltzFactors=exp(-eigenvalues/(kb*t))
       BoltzFactors/=total(BoltzFactors)
       mome*=(BoltzFactors*sinth)
       moment_arr[i]+=total(mome)
       endfor
    endfor
moment_arr[i]/=sinthsum
if n_elements(DiamagVal) ne 0 then begin
moment_arr[i]+=DiamagVal*field*1e4/conv
endif

endfor



*(*pState).yt=moment_arr
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calculate_ChiCurve_SelfConsistent_1,event,refine=refine
widget_control,event.top,get_uvalue = pState
fail=0
if keyword_set(refine) eq 0 then ConstructMatrices,event,fail
if fail eq 1 then return
kb=(*pstate).constants.kb
conv=(*pstate).constants.conv
Matrix_Dimension=(*pstate).Matrix_Dimension
if Matrix_Dimension lt 2 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Matrix Dimension Must be Greater Than Two')
return
endif
field=(*pstate).MagFieldTheoryValue
if Field le 0.0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Specified Field Must be Greater Than Zero')
return
endif

*(*pstate).field=field
if ((*pstate).MFTC_Pointers[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) then begin
    index=(*pstate).MFTC_Pointers[1]
    if keyword_set(refine) eq 0 then begin
    lambda=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    lambda=(*(*pState).Refine_vals)[index]
    endelse
endif
temperature=*(*pState).x
if keyword_set(refine) eq 1 then begin
    if (*pState).TempLims[0] ne -1 then begin
    temperature=temperature[sort(temperature)]
    temperature=temperature[(*pState).TempLims[0]:(*pState).TempLims[1]]
    endif
endif

n_temperature=n_elements(temperature)
ordinate=(*pstate).quantities[1]
;print,ordinate

if ((*pstate).Diamagnetism[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).Diamagnetism[1],0]) eq 1) then begin
    index=(*pstate).Diamagnetism[1]
    if keyword_set(refine) eq 0 then begin
    DiamagVal=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    DiamagVal=(*(*pState).Refine_vals)[index]
    endelse
endif
MA=0.0
MB=0.0
Iterations=0
Criterion=(*pState).MFT_Criterion
Test=0.0
Chi=dblarr(n_temperature)
Sample_Type=(*pstate).Sample_Type
IF Sample_Type EQ 1 THEN BEGIN
theta=(*pstate).Theta_sc
phi=(*pstate).phi_sc

;print,'eigenvalues :',eigenvalues
;
;
for i = 0, n_temperature-1 do begin
Iterations=0
Test=0.0
while Test lt Criterion do begin
Iterations+=1
MA_Last=MA
;sublattice A
field=*(*pstate).field+lambda*MB
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'eigenvalues: ',eigenvalues
if lambda gt 0 then begin
MB=MA
endif else begin
;sublattice B
field=*(*pstate).field+lambda*MA
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors;
MB=total(MOM)
endelse
Test=MA_Last/MA
if Test gt 1.0 then Test=1/Test
endwhile
Iterations=0
Test=0.0
MagMom=(MA+MB)/2.0
;MagMom=MA
;print,'MagMom: ',MagMom
;print,'MA: ',MA
;print,'MB: ',MB
;print,'temperature[i]: ',temperature[i]
;print,' '
Chi[i]=(MagMom*conv)/(*(*pstate).field*1e4)
endfor
if n_elements(DiamagVal) ne 0 then Chi+=DiamagVal
;
ChiT=Chi*temperature
ueff=2.82788*sqrt(ChiT)
if ordinate eq 'chi' then *(*pState).yt=Chi
if ordinate eq 'chit' then *(*pState).yt=ChiT
if ordinate eq 'ueff' then *(*pState).yt=ueff
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event
;print,ordinate
return
ENDIF
;


IF (*pstate).SusPowderMethod EQ 0 THEN BEGIN
Chix=dblarr(n_temperature)
Chiy=dblarr(n_temperature)
Chiz=dblarr(n_temperature)
;Z Axis
theta=0.0
phi=0.0
for i = 0, n_temperature-1 do begin
while Test lt Criterion do begin
Iterations+=1
MA_Last=MA
;sublattice A
field=*(*pstate).field+lambda*MB
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'eigenvalues: ',eigenvalues
if lambda gt 0 then begin
MB=MA
endif else begin
;sublattice B
field=*(*pstate).field+lambda*MA
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors;
MB=total(MOM)
endelse
Test=MA_Last/MA
if Test gt 1.0 then Test=1/Test
endwhile
Iterations=0
Test=0.0
MagMom=(MA+MB)/2.0
Chiz[i]=(MagMom*conv)/(*(*pstate).field*1e4)
endfor
;X Axis
theta=90.0
phi=0.0
for i = 0, n_temperature-1 do begin
t=temperature[i]
while Test lt Criterion do begin
Iterations+=1
MA_Last=MA
;sublattice A
field=*(*pstate).field+lambda*MB
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'eigenvalues: ',eigenvalues
if lambda gt 0 then begin
MB=MA
endif else begin
;sublattice B
field=*(*pstate).field+lambda*MA
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors;
MB=total(MOM)
endelse
Test=MA_Last/MA
if Test gt 1.0 then Test=1/Test
endwhile
Iterations=0
Test=0.0
MagMom=(MA+MB)/2.0
Chix[i]=(MagMom*conv)/(*(*pstate).field*1e4)
endfor
;Y Axis
theta=90.0
phi=90.0
for i = 0, n_temperature-1 do begin
t=temperature[i]
while Test lt Criterion do begin
Iterations+=1
MA_Last=MA
;sublattice A
field=*(*pstate).field+lambda*MB
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'eigenvalues: ',eigenvalues
if lambda gt 0 then begin
MB=MA
endif else begin
;sublattice B
field=*(*pstate).field+lambda*MA
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors;
MB=total(MOM)
endelse
Test=MA_Last/MA
if Test gt 1.0 then Test=1/Test
endwhile
Iterations=0
Test=0.0
MagMom=(MA+MB)/2.0
Chiy[i]=(MagMom*conv)/(*(*pstate).field*1e4)
endfor
;
Chi=(Chix+Chiy+Chiz)/3.0
if n_elements(DiamagVal) ne 0 then Chi+=DiamagVal
;
;
ChiT=Chi*temperature
ueff=2.82788*sqrt(ChiT)
if ordinate eq 'chi' then *(*pState).yt=Chi
if ordinate eq 'chit' then *(*pState).yt=ChiT
if ordinate eq 'ueff' then *(*pState).yt=ueff
ENDIF ELSE BEGIN
theta_start=(*pState).theta_start
theta_end=(*pState).theta_end
theta_nsteps=(*pState).theta_nsteps
phi_start=(*pState).phi_start
phi_end=(*pState).phi_end
phi_nsteps=(*pState).phi_nsteps
if theta_nsteps eq 1 then begin
thetavals=make_array(1)
thetavals[0]=theta_start
endif else begin
dx=(theta_end-theta_start)/(theta_nsteps-1)
thetavals=theta_start+dx*dindgen(theta_nsteps)
endelse
if phi_nsteps eq 1 then begin
phivals=make_array(1)
phivals[0]=phi_start
endif else begin
dx=(phi_end-phi_start)/(phi_nsteps-1)
phivals=phi_start+dx*dindgen(phi_nsteps)
endelse

sintharr=sin(thetavals*!DTOR)
sinthsum=total(sintharr*phi_nsteps)
MagMom=dblarr(n_temperature)
;
Test=0.0
Iterations=0
        MA=0.1
        MB=0.1
for i = 0, n_temperature-1 do begin
MagMom_sum=0.0
         for j = 0, theta_nsteps-1 do begin
        theta=thetavals[j]
        sinth=sintharr[j]
        for k = 0, phi_nsteps-1 do begin
        phi=phivals[k]
        MA_Test=0.01
       while Test lt Criterion and (iterations lt 100) do begin
        MA_LastTest=MA_Test
        Iterations+=1
        ;sublattice A
         field=*(*pstate).field+lambda*MB

         CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
        MINEIG=MIN(eigenvalues)
       eigenvalues-=MINEIG
       eigenvalues-=5
        CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
       BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
       BoltzFactors/=total(BoltzFactors)
       mome*=BoltzFactors
       MA_sum=total(mome)
       MA_Test=MA_sum
       MA=MA_sum*sinth
       MA_sum=0.0
;
if lambda gt 0 then begin
MB=MA
endif else begin
       ;sublattice B
         field=*(*pstate).field+lambda*MA
         CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
        MINEIG=MIN(eigenvalues)
       eigenvalues-=MINEIG
       eigenvalues-=5
        CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
       BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
       BoltzFactors/=total(BoltzFactors)
       mome*=BoltzFactors
       MB_sum=total(mome)
       MB=MB_sum*sinth
       MB_sum=0.0
endelse
Test=MA_LastTest/MA_Test
if Test gt 1.0 then Test=1/Test
;print,'MA: ',MA

          endwhile
MagMom_sum+=(MA+MB)/2.0
test=0.0
iterations=0
        endfor
    endfor
MagMom[i]=MagMom_sum/sinthsum
;
;print,'MagMom[i]: ',MagMom[i]
;print,'MA: ',MA
;print,'MB: ',MB
;print,'temperature[i]: ',temperature[i]
;print,' '


endfor
Chi=(MagMom*conv)/(*(*pstate).field*1e4)
if n_elements(DiamagVal) ne 0 then Chi+=DiamagVal
;
ChiT=Chi*temperature
ueff=2.82788*sqrt(ChiT)
if ordinate eq 'chi' then *(*pState).yt=Chi
if ordinate eq 'chit' then *(*pState).yt=ChiT
if ordinate eq 'ueff' then *(*pState).yt=ueff
ENDELSE
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event
;

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calculate_ChiCurve_SelfConsistent_2,event,refine=refine
widget_control,event.top,get_uvalue = pState
fail=0
if keyword_set(refine) eq 0 then ConstructMatrices,event,fail
if fail eq 1 then return
kb=(*pstate).constants.kb
conv=(*pstate).constants.conv
Matrix_Dimension=(*pstate).Matrix_Dimension
if Matrix_Dimension lt 2 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Matrix Dimension Must be Greater Than Two')
return
endif
field=(*pstate).MagFieldTheoryValue
if Field le 0.0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Specified Field Must be Greater Than Zero')
return
endif

*(*pstate).field=field
if ((*pstate).MFTC_Pointers[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) then begin
    index=(*pstate).MFTC_Pointers[1]
    if keyword_set(refine) eq 0 then begin
    Jint=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    Jint=(*(*pState).Refine_vals)[index]
    endelse
endif
temperature=*(*pState).x
if keyword_set(refine) eq 1 then begin
    if (*pState).TempLims[0] ne -1 then begin
    temperature=temperature[sort(temperature)]
    temperature=temperature[(*pState).TempLims[0]:(*pState).TempLims[1]]
    endif
endif

n_temperature=n_elements(temperature)
ordinate=(*pstate).quantities[1]
;print,ordinate

if ((*pstate).Diamagnetism[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).Diamagnetism[1],0]) eq 1) then begin
    index=(*pstate).Diamagnetism[1]
    if keyword_set(refine) eq 0 then begin
    DiamagVal=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    DiamagVal=(*(*pState).Refine_vals)[index]
    endelse
endif
Iterations=0
Criterion=(*pState).MFT_Criterion
Test=0.0
Chi=dblarr(n_temperature)

Sample_Type=(*pstate).Sample_Type

Sx=reform((*(*pstate).SpinMatrices)[0,*,*])
Sy=reform((*(*pstate).SpinMatrices)[1,*,*])
Sz=reform((*(*pstate).SpinMatrices)[2,*,*])

field=*(*pstate).field

IF Sample_Type EQ 1 THEN BEGIN
theta=(*pstate).Theta_sc
phi=(*pstate).phi_sc
;print,'eigenvalues :',eigenvalues
;
PrintOption=0
;
if PrintOption eq 1 then begin
filename=(*pstate).Source_Dir+'SpinExpectationValues.txt'
print,'filename: ',filename
format_float = '(7f-12.5,2x)'
openw,lun,filename,/get_lun
endif
for i = 0, n_temperature-1 do begin
Iterations=0
Test=0.0
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
if PrintOption eq 1 then begin
SBZ=Szex[0]
SBX=Sxex[0]
SBY=Syex[0]
endif


AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
if PrintOption eq 1 then begin
SAZ=Szex[0]
SAX=Sxex[0]
SAY=Syex[0]
endif

AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
;print,'iterations: ',iterations
;print,'test ',test
;print,'Szex[0] ',Szex[0]
;print,'Sxex[0] ',Sxex[0]
;print,'Syex[0] ',Syex[0]
Iterations=0
Test=0.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'temperature[i] ',temperature[i]  
;print,'MA: ',MA
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MB=total(MOM)
;print,'MB: ',MB
MagMom=(MA+MB)/2.0
Chi[i]=(MagMom*conv)/(*(*pstate).field*1e4)
;;print,'MagMom ',MagMom
;print,''
if PrintOption eq 1 then begin
printf,lun,temperature[i],SAX,SAY,SAZ,SBX,SBY,SBZ,format=format_float
endif
endfor
if PrintOption eq 1 then  free_lun,lun,/force
if n_elements(DiamagVal) ne 0 then Chi+=DiamagVal
;
ChiT=Chi*temperature
ueff=2.82788*sqrt(ChiT)
if ordinate eq 'chi' then *(*pState).yt=Chi
if ordinate eq 'chit' then *(*pState).yt=ChiT
if ordinate eq 'ueff' then *(*pState).yt=ueff
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event
;print,ordinate
return
ENDIF



IF (*pstate).SusPowderMethod EQ 0 THEN BEGIN
Chix=dblarr(n_temperature)
Chiy=dblarr(n_temperature)
Chiz=dblarr(n_temperature)
;Z Axis
theta=0.0
phi=0.0
for i = 0, n_temperature-1 do begin
Iterations=0
Test=0.0
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
;print,'iterations: ',iterations
;print,'test ',test
Iterations=0
Test=0.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'temperature[i] ',temperature[i]  
;print,'MA: ',MA
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MB=total(MOM)
;print,'MB: ',MB
MagMom=(MA+MB)/2.0
Chiz[i]=(MagMom*conv)/(*(*pstate).field*1e4)
endfor
;X Axis
theta=90.0
phi=0.0
for i = 0, n_temperature-1 do begin
Iterations=0
Test=0.0
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
;print,'iterations: ',iterations
;print,'test ',test
Iterations=0
Test=0.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'temperature[i] ',temperature[i]  
;print,'MA: ',MA
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MB=total(MOM)
;print,'MB: ',MB
MagMom=(MA+MB)/2.0
Chix[i]=(MagMom*conv)/(*(*pstate).field*1e4)
endfor
;Y Axis
theta=90.0
phi=90.0
for i = 0, n_temperature-1 do begin
Iterations=0
Test=0.0
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
;print,'iterations: ',iterations
;print,'test ',test
Iterations=0
Test=0.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'temperature[i] ',temperature[i]  
;print,'MA: ',MA
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MB=total(MOM)
;print,'MB: ',MB
MagMom=(MA+MB)/2.0
Chiy[i]=(MagMom*conv)/(*(*pstate).field*1e4)
endfor
;
Chi=(Chix+Chiy+Chiz)/3.0
if n_elements(DiamagVal) ne 0 then Chi+=DiamagVal
;
;
ChiT=Chi*temperature
ueff=2.82788*sqrt(ChiT)
if ordinate eq 'chi' then *(*pState).yt=Chi
if ordinate eq 'chit' then *(*pState).yt=ChiT
if ordinate eq 'ueff' then *(*pState).yt=ueff
ENDIF ELSE BEGIN
theta_start=(*pState).theta_start
theta_end=(*pState).theta_end
theta_nsteps=(*pState).theta_nsteps
phi_start=(*pState).phi_start
phi_end=(*pState).phi_end
phi_nsteps=(*pState).phi_nsteps
if theta_nsteps eq 1 then begin
thetavals=make_array(1)
thetavals[0]=theta_start
endif else begin
dx=(theta_end-theta_start)/(theta_nsteps-1)
thetavals=theta_start+dx*dindgen(theta_nsteps)
endelse
if phi_nsteps eq 1 then begin
phivals=make_array(1)
phivals[0]=phi_start
endif else begin
dx=(phi_end-phi_start)/(phi_nsteps-1)
phivals=phi_start+dx*dindgen(phi_nsteps)
endelse

sintharr=sin(thetavals*!DTOR)
;print,'total(sintharr) ',total(sintharr)
sinthsum=total(sintharr*phi_nsteps)
MagMom=dblarr(n_temperature)
;
 ;   print,'theta_nsteps ',theta_nsteps 

for i = 0, n_temperature-1 do begin
MA=0.0
MagMom_sum=0.0
MB=0.0
     for j = 0, theta_nsteps-1 do begin
     theta=thetavals[j]
     sinth=sintharr[j]
 ;    print,'sinth ',sinth 
  ;  print,'theta ',theta 
     
        for k = 0, phi_nsteps-1 do begin
        phi=phivals[k]
;
        Iterations=0
         Test=0.0
         Szex=0.1d
         Sxex=0.1d
         Syex=0.1d
         AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
         AddTermA_Last=AddTermA
         AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
         AddTermB_Last=AddTermB
;
          while (Test lt Criterion) and (iterations lt 100) do begin
          Iterations+=1
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for l = 0, n_eigenvalues-1 do begin
Szex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for l = 0, n_eigenvalues-1 do begin
Syex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for l = 0, n_eigenvalues-1 do begin
Sxex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*temperature[i])))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for l = 0, n_eigenvalues-1 do begin
Szex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for l = 0, n_eigenvalues-1 do begin
Syex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for l = 0, n_eigenvalues-1 do begin
Sxex+=exponent[l]*real_part(reform(Strans[l,l]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
;print,'iterations: ',iterations
;print,'test ',test
          endwhile
Iterations=0
Test=0.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MA=total(MOM)
;print,'temperature[i] ',temperature[i]  
;print,'MA: ',MA
;
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine,field=field
BoltzFactors=exp(-eigenvalues/(kb*temperature[i]))
BoltzFactors/=total(BoltzFactors)
MOM=mome*BoltzFactors
MB=total(MOM)
;print,'MB: ',MB
Mom=(MA+MB)/2.0
Mom*=sinth
MagMom_sum+=Mom
        endfor
    endfor
MagMom[i]=MagMom_sum/sinthsum
;
;
;print,'MagMom[i]: ',MagMom[i]
;print,'MA: ',MA
;print,'MB: ',MB
;print,'temperature[i]: ',temperature[i]
;print,' '


endfor
Chi=(MagMom*conv)/(*(*pstate).field*1e4)
if n_elements(DiamagVal) ne 0 then Chi+=DiamagVal
;
ChiT=Chi*temperature
ueff=2.82788*sqrt(ChiT)
if ordinate eq 'chi' then *(*pState).yt=Chi
if ordinate eq 'chit' then *(*pState).yt=ChiT
if ordinate eq 'ueff' then *(*pState).yt=ueff
ENDELSE
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event
;

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calculate_ChiCurve,event,refine=refine
widget_control,event.top,get_uvalue = pState
fail=0
if keyword_set(refine) eq 0 then ConstructMatrices,event,fail
if fail eq 1 then return


if ((*pstate).MFTC_Pointers[0] eq 1) and $
   (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) and $
    (*pstate).MFT_Treatment ne 0 then begin
    index=(*pstate).MFTC_Pointers[1]
    if keyword_set(refine) eq 0 then begin
    lambda=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
      if lambda eq 0.0 then begin
      msg=strarr(3)
      msg[0]='Initial Value of lambda/Jint should be non zero'
      msg[1]='to indicate whether a ferromagnetic or '
      msg[2]='antiferromagnetic interaction is to be expected.'
      void=dialog_message(dialog_parent=event.top,/error, msg)
      return
      endif
    endif else begin
    lambda=(*(*pState).Refine_vals)[index]
   endelse
    if (*pstate).MFT_Treatment eq 1 then Calculate_ChiCurve_SelfConsistent_1,event,refine=refine
    if (*pstate).MFT_Treatment eq 2 then Calculate_ChiCurve_SelfConsistent_2,event,refine=refine
    return
 endif

kb=(*pstate).constants.kb
conv=(*pstate).constants.conv
Matrix_Dimension=(*pstate).Matrix_Dimension
if Matrix_Dimension lt 2 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Matrix Dimension Must be Greater Than Two')
return
endif
field=(*pstate).MagFieldTheoryValue
if Field le 0.0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Specified Field Must be Greater Than Zero')
return
endif

*(*pstate).field=field
lambda=0.0
if ((*pstate).MFTC_Pointers[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) then begin
    index=(*pstate).MFTC_Pointers[1]
    if keyword_set(refine) eq 0 then begin
    lambda=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    lambda=(*(*pState).Refine_vals)[index]
    endelse
endif
temperature=*(*pState).x
if keyword_set(refine) eq 1 then begin
    if (*pState).TempLims[0] ne -1 then begin
    temperature=temperature[sort(temperature)]
    temperature=temperature[(*pState).TempLims[0]:(*pState).TempLims[1]]
    endif
endif

n_temperature=n_elements(temperature)
ordinate=(*pstate).quantities[1]
;print,ordinate
Sample_Type=(*pstate).Sample_Type
IF Sample_Type EQ 1 THEN BEGIN
theta=(*pstate).Theta_sc
phi=(*pstate).phi_sc
Chi=dblarr(n_temperature)
;  if (*pstate).Magnetisation_Method eq 0 then begin
    CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
    MINEIG=MIN(eigenvalues)
    eigenvalues-=MINEIG
    eigenvalues-=5
    CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine
      for i = 0, n_temperature-1 do begin
      t=temperature[i]
      BoltzFactors=exp(-eigenvalues/(kb*t))
      BoltzFactors/=total(BoltzFactors)
      MOM=mome*BoltzFactors
      MOM_SUM=total(MOM)
      Chi[i]=(MOM_SUM*conv)/(field*1e4)
      endfor

;
if ((*pstate).Diamagnetism[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).Diamagnetism[1],0]) eq 1) then begin
    index=(*pstate).Diamagnetism[1]
    if keyword_set(refine) eq 0 then begin
    DiamagVal=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    DiamagVal=(*(*pState).Refine_vals)[index]
    endelse
Chi+=DiamagVal
endif

if lambda ne 0.0 then Chi=1/(1/(temporary(Chi))-lambda)

ChiT=Chi*temperature
ueff=2.82788*sqrt(ChiT)
if ordinate eq 'chi' then *(*pState).yt=Chi
if ordinate eq 'chit' then *(*pState).yt=ChiT
if ordinate eq 'ueff' then *(*pState).yt=ueff
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event
;print,ordinate
return
ENDIF
;
IF (*pstate).SusPowderMethod EQ 0 THEN BEGIN
theta=0.0
phi=0.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
;print,'eigenvalues :',eigenvalues
z_eigenvalues=eigenvalues
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine
z_moments=mome
;print,'z ',eigenvalues
theta=90.0
phi=0.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
;print,'eigenvalues :',eigenvalues
x_eigenvalues=eigenvalues
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine
x_moments=mome
;print,'x_moments ',x_moments
;print,'x ',eigenvalues
theta=90.0
phi=90.0
CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
;print,'eigenvalues :',eigenvalues
y_eigenvalues=eigenvalues
CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,mome,refine=refine
y_moments=mome
;print,'y ',eigenvalues
Chi=dblarr(n_temperature)
;
for i = 0, n_temperature-1 do begin
t=temperature[i]
x_BoltzFactors=exp(-x_eigenvalues/(kb*t))
x_BoltzFactors/=total(x_BoltzFactors)
y_BoltzFactors=exp(-y_eigenvalues/(kb*t))
y_BoltzFactors/=total(y_BoltzFactors)
z_BoltzFactors=exp(-z_eigenvalues/(kb*t))
z_BoltzFactors/=total(z_BoltzFactors)
;print,'x_BoltzFactors ',x_BoltzFactors
;
XMOM=x_moments*x_BoltzFactors
YMOM=y_moments*y_BoltzFactors
ZMOM=z_moments*z_BoltzFactors
;
XMOM_SUM=total(XMOM)
YMOM_SUM=total(YMOM)
ZMOM_SUM=total(ZMOM)
;
Chi_x=(XMOM_SUM*conv)/(field*1e4)
Chi_y=(YMOM_SUM*conv)/(field*1e4)
Chi_z=(ZMOM_SUM*conv)/(field*1e4)

Chi[i]=(Chi_x+Chi_y+Chi_z)/3.0

endfor
;

if ((*pstate).Diamagnetism[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).Diamagnetism[1],0]) eq 1) then begin
    index=(*pstate).Diamagnetism[1]
    if keyword_set(refine) eq 0 then begin
    DiamagVal=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    DiamagVal=(*(*pState).Refine_vals)[index]
    endelse
Chi+=DiamagVal
endif
;
if lambda ne 0.0 then Chi=1/(1/(temporary(Chi))-lambda)

ChiT=Chi*temperature
ueff=2.82788*sqrt(ChiT)
if ordinate eq 'chi' then *(*pState).yt=Chi
if ordinate eq 'chit' then *(*pState).yt=ChiT
if ordinate eq 'ueff' then *(*pState).yt=ueff
ENDIF ELSE BEGIN
theta_start=(*pState).theta_start
theta_end=(*pState).theta_end
theta_nsteps=(*pState).theta_nsteps
phi_start=(*pState).phi_start
phi_end=(*pState).phi_end
phi_nsteps=(*pState).phi_nsteps
if theta_nsteps eq 1 then begin
thetavals=make_array(1)
thetavals[0]=theta_start
endif else begin
dx=(theta_end-theta_start)/(theta_nsteps-1)
thetavals=theta_start+dx*dindgen(theta_nsteps)
endelse
if phi_nsteps eq 1 then begin
phivals=make_array(1)
phivals[0]=phi_start
endif else begin
dx=(phi_end-phi_start)/(phi_nsteps-1)
phivals=phi_start+dx*dindgen(phi_nsteps)
endelse

sintharr=sin(thetavals*!DTOR)
sinthsum=total(sintharr*phi_nsteps)
moment_arr=dblarr(n_temperature)
;
    for i = 0, theta_nsteps-1 do begin
       for j = 0, phi_nsteps-1 do begin
       theta=thetavals[i]
       sinth=sintharr[i]
       phi=phivals[j]
       CalculateEnergies,event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,refine=refine
       MINEIG=MIN(eigenvalues)
       eigenvalues-=MINEIG
       eigenvalues-=5
        ;print,'eigenvalues :',eigenvalues
        CalculateMoments,event,theta,phi,eigenvectors=eigenvectors,moment_master,refine=refine
         for k = 0, n_temperature-1 do begin
         mome=moment_master
         BoltzFactors=exp(-eigenvalues/(kb*temperature[k]))
         BoltzFactors/=total(BoltzFactors)
         mome*=(BoltzFactors*sinth)
         moment_arr[k]+=total(mome)
         endfor
       endfor
    endfor
moment_arr/=sinthsum
Chi=(moment_arr*conv)/(field*1e4)
;
if ((*pstate).Diamagnetism[0] eq 1) and $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).Diamagnetism[1],0]) eq 1) then begin
    index=(*pstate).Diamagnetism[1]
    if keyword_set(refine) eq 0 then begin
    DiamagVal=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
    endif else begin
    DiamagVal=(*(*pState).Refine_vals)[index]
    endelse
Chi+=DiamagVal
endif
if lambda ne 0.0 then Chi=1/(1/(temporary(Chi))-lambda)

ChiT=Chi*temperature
ueff=2.82788*sqrt(ChiT)
if ordinate eq 'chi' then *(*pState).yt=Chi
if ordinate eq 'chit' then *(*pState).yt=ChiT
if ordinate eq 'ueff' then *(*pState).yt=ueff
ENDELSE
if keyword_set(refine) eq 0 then MagProp_Plot_Experimental_Data,event
;

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calc_Chi_Wrapper,x,p,yfit,_Extra = extra
event=extra.event
nlines=extra.nlines
trans=extra.trans
widget_control,event.top,get_uvalue = pState
*(*pState).Refine_vals=p
case (*pstate).Energy_Refine of
0:  $
begin
Calculate_ChiCurve,event,/refine
yfit=*(*pState).yt
end
1:  $
begin
yfit=dblarr(nlines)
OldDerivOption=(*pState).DerivOption
IF ((*pstate).MFTC_Pointers[0] eq 1) AND $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) AND $
    ((*pState).MFT_Treatment eq 2) THEN BEGIN
(*pState).DerivOption=0
Matrix_Dimension=(*pstate).Matrix_Dimension
kb=(*pstate).constants.kb
t=(*pstate).RefineEnergyTemperature
    index=(*pstate).MFTC_Pointers[1]
    Jint=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
Iterations=0
Criterion=(*pState).MFT_Criterion
Test=0.0
Sx=reform((*(*pstate).SpinMatrices)[0,*,*])
Sy=reform((*(*pstate).SpinMatrices)[1,*,*])
Sz=reform((*(*pstate).SpinMatrices)[2,*,*])
;
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  eigenvectors=eigenvectors,AddTerm=AddTermA,/refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  eigenvectors=eigenvectors,AddTerm=AddTermB,/refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
(*pState).DerivOption=1
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  AddTerm=AddTermA,/refine
ENDIF ELSE BEGIN
(*pState).DerivOption=1
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues,/refine
ENDELSE

for i = 0, nlines-1 do begin
;print,trans[0,i]
;print,trans[1,i]
;print,eigenvalues[trans[0,i]]
yfit[i]=abs(eigenvalues[trans[0,i]]-eigenvalues[trans[1,i]])
endfor
;
(*pState).DerivOption=OldDerivOption
end
2:  $
begin
Calculate_ChiCurve,event,/refine
yfit=*(*pState).yt
OldDerivOption=(*pState).DerivOption
IF ((*pstate).MFTC_Pointers[0] eq 1) AND $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) AND $
    ((*pState).MFT_Treatment eq 2) THEN BEGIN
(*pState).DerivOption=0
Matrix_Dimension=(*pstate).Matrix_Dimension
kb=(*pstate).constants.kb
t=(*pstate).RefineEnergyTemperature
    index=(*pstate).MFTC_Pointers[1]
    Jint=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
Iterations=0
Criterion=(*pState).MFT_Criterion
Test=0.0
Sx=reform((*(*pstate).SpinMatrices)[0,*,*])
Sy=reform((*(*pstate).SpinMatrices)[1,*,*])
Sz=reform((*(*pstate).SpinMatrices)[2,*,*])
;
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  eigenvectors=eigenvectors,AddTerm=AddTermA,/refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  eigenvectors=eigenvectors,AddTerm=AddTermB,/refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
(*pState).DerivOption=1
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  AddTerm=AddTermA,/refine
ENDIF ELSE BEGIN
(*pState).DerivOption=1
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues,/refine
ENDELSE
for i = 0, nlines-1 do begin
yfit=[yfit,abs(eigenvalues[trans[0,i]]-eigenvalues[trans[1,i]])]
endfor
(*pState).DerivOption=OldDerivOption
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Calc_Mag_Wrapper,x,p,yfit,_Extra = extra
event=extra.event
nlines=extra.nlines
trans=extra.trans
widget_control,event.top,get_uvalue = pState
*(*pState).Refine_vals=p
case (*pstate).Energy_Refine of
0:  $
begin
Calculate_MagCurve,event,/refine
yfit=*(*pState).yt
end
1:  $
begin
yfit=dblarr(nlines)
OldDerivOption=(*pState).DerivOption
IF ((*pstate).MFTC_Pointers[0] eq 1) AND $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) AND $
    ((*pState).MFT_Treatment eq 2) THEN BEGIN
(*pState).DerivOption=0
Matrix_Dimension=(*pstate).Matrix_Dimension
kb=(*pstate).constants.kb
t=(*pstate).RefineEnergyTemperature
    index=(*pstate).MFTC_Pointers[1]
    Jint=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
Iterations=0
Criterion=(*pState).MFT_Criterion
Test=0.0
Sx=reform((*(*pstate).SpinMatrices)[0,*,*])
Sy=reform((*(*pstate).SpinMatrices)[1,*,*])
Sz=reform((*(*pstate).SpinMatrices)[2,*,*])
;
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  eigenvectors=eigenvectors,AddTerm=AddTermA,/refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  eigenvectors=eigenvectors,AddTerm=AddTermB,/refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
(*pState).DerivOption=1
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  AddTerm=AddTermA,/refine
ENDIF ELSE BEGIN
(*pState).DerivOption=1
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues,/refine
ENDELSE

for i = 0, nlines-1 do begin
;print,trans[0,i]
;print,trans[1,i]
;print,eigenvalues[trans[0,i]]
yfit[i]=abs(eigenvalues[trans[0,i]]-eigenvalues[trans[1,i]])
endfor
;
(*pState).DerivOption=OldDerivOption
end
2:  $
begin
Calculate_MagCurve,event,/refine
yfit=*(*pState).yt
OldDerivOption=(*pState).DerivOption
IF ((*pstate).MFTC_Pointers[0] eq 1) AND $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) AND $
    ((*pState).MFT_Treatment eq 2) THEN BEGIN
(*pState).DerivOption=0
Matrix_Dimension=(*pstate).Matrix_Dimension
kb=(*pstate).constants.kb
t=(*pstate).RefineEnergyTemperature
    index=(*pstate).MFTC_Pointers[1]
    Jint=(double(reform((*pstate).Parameter_Table_Input[3,index])))[0]
Iterations=0
Criterion=(*pState).MFT_Criterion
Test=0.0
Sx=reform((*(*pstate).SpinMatrices)[0,*,*])
Sy=reform((*(*pstate).SpinMatrices)[1,*,*])
Sz=reform((*(*pstate).SpinMatrices)[2,*,*])
;
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  eigenvectors=eigenvectors,AddTerm=AddTermA,/refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  eigenvectors=eigenvectors,AddTerm=AddTermB,/refine
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, Matrix_Dimension-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
(*pState).DerivOption=1
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues, $
                  AddTerm=AddTermA,/refine
ENDIF ELSE BEGIN
(*pState).DerivOption=1
CalculateEnergies,event,(*pState).ER_Field,(*pState).ER_theta,(*pState).ER_phi,eigenvalues,/refine
ENDELSE
for i = 0, nlines-1 do begin
yfit=[yfit,abs(eigenvalues[trans[0,i]]-eigenvalues[trans[1,i]])]
endfor
(*pState).DerivOption=OldDerivOption
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagProp_iterproc, fnc,p,iter,fnorm, $
           dof = dof,        $
           quiet = quiet, $
           parinfo = parinfo, $
           _Extra = extra

widget_control,extra.event.top,get_uvalue = pState
if (*pstate).Energy_Refine eq 1 then return


MagProp_Plot_Experimental_Data,extra.event,/fitting
string_array=strarr(1,100)

p_string=strtrim(string(p),2)

whereentry=where(extra.ExpressionString_Array ne '', count)
if count ne 0 then begin
p_string[whereentry]=extra.ExpressionString_Array[whereentry]
endif

string_array[0,0:n_elements(p)-1]=p_string

(*pstate).Parameter_Table_Input[3,*]=string_array
string_array[0,*]=' '
(*pstate).Parameter_Table_Input[4,*]=string_array
widget_control,(*pstate).Parameter_Table,set_value=(*pstate).Parameter_Table_Input

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

xyouts,xpos,ypos1,"Iteration: "+strtrim(string(iter),2),color=9
xyouts,xpos,ypos2,"Chisq: "+strtrim(string(fnorm),2),color=9


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Refine_Data,event,mome=mome,chi=chi
widget_control,event.top,get_uvalue = pState

   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)
widget_control,(*pstate).RefineButton,sensitive=1
return
endif


fail=0
tstart=systime(/seconds)
;

Matrix_Dimension=(*pstate).Matrix_Dimension
if Matrix_Dimension lt 2 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The Matrix Dimension Must be Greater Than Two')
return
endif
;
;
Parameter_Table_Input=(*pstate).Parameter_Table_Input
Entries=reform(Parameter_Table_Input[0,*])
WhereEntry=where(Entries ne '',Num_Entries)
if Num_Entries eq 0 then return
ConstructMatrices,event,fail
if fail eq 1 then return
widget_control,(*pstate).RefineButton,sensitive=0
nlines=0
;What is the nature of the data?

case (*pstate).Energy_Refine of
0:  $  ;magnetic data
begin
x=*(*pState).x
y=*(*pState).y
if (*pState).weighting eq 0 then begin
    if strlowcase(size(*(*pstate).dy,/tname)) ne 'undefined' and $
    strlowcase(size(*(*pstate).dy,/tname)) ne 'string' then begin
    dy=*(*pstate).dy
    weights=1d/dy^2
    endif else begin
    weights=1d
    endelse
endif else begin
weights=1d
endelse
;
if (*pState).quantities[0] eq 't' then begin
    if (*pState).TempLims[0] ne -1 then begin
    indices=sort(x)
    x=x[indices]
    *(*pState).x=x
    y=y[indices]
    *(*pState).y=y
    x=x[(*pState).TempLims[0]:(*pState).TempLims[1]]
    y=y[(*pState).TempLims[0]:(*pState).TempLims[1]]
    endif
endif
Trans=''
end
1:  $  ;energies
begin
InputEnergies=*(*pstate).InputEnergies
;
whereneblank=where(InputEnergies ne '',count)
if count ne 0 then InputEnergies=InputEnergies[whereneblank]
InputEnergies=strtrim(InputEnergies,2)
whereentry1=where(strpos(InputEnergies, ';') ne 0, count)
if count ne 0 then InputEnergies=InputEnergies[whereentry1]
;
nlines=n_elements(InputEnergies)
y=dblarr(nlines)
dy=dblarr(nlines)
Trans=intarr(2,nlines)
x=indgen(nlines)
Energy=0d
EnergyErr=0d
IS=0
FS=0
for i = 0,nlines-1 do begin
reads,InputEnergies[i],Energy,EnergyErr,IS,FS
y[i]=Energy
dy[i]=EnergyErr
Trans[0,i]=IS
Trans[1,i]=FS
endfor
weights=1d/dy^2
trans-=1
y=abs(y)
end
2:  $  ;magnetic data and energies
begin
x=*(*pState).x
y=*(*pState).y
if (*pState).weighting eq 0 then begin
    if strlowcase(size(*(*pstate).dy,/tname)) ne 'undefined' and $
    strlowcase(size(*(*pstate).dy,/tname)) ne 'string' then begin
    dy=*(*pstate).dy
    weights=1d/dy^2
    endif else begin
    weights=dblarr(n_elements(x))+1
    endelse
endif else begin
weights=dblarr(n_elements(x))+1
endelse
;
if (*pState).quantities[0] eq 't' then begin
    if (*pState).TempLims[0] ne -1 then begin
    indices=sort(x)
    x=x[indices]
    *(*pState).x=x
    y=y[indices]
    *(*pState).y=y
    x=x[(*pState).TempLims[0]:(*pState).TempLims[1]]
    y=y[(*pState).TempLims[0]:(*pState).TempLims[1]]
    endif
endif
;;
InputEnergies=*(*pstate).InputEnergies
;
whereneblank=where(InputEnergies ne '',count)
if count ne 0 then InputEnergies=InputEnergies[whereneblank]
InputEnergies=strtrim(InputEnergies,2)
whereentry1=where(strpos(InputEnergies, ';') ne 0, count)
if count ne 0 then InputEnergies=InputEnergies[whereentry1]
;
;
nlines=n_elements(InputEnergies)
ey=dblarr(nlines)
dey=dblarr(nlines)
Trans=intarr(2,nlines)
;x=indgen(nlines)
Energy=0d
EnergyErr=0d
IS=0
FS=0
for i = 0,nlines-1 do begin
reads,InputEnergies[i],Energy,EnergyErr,IS,FS
ey[i]=Energy
dey[i]=EnergyErr
Trans[0,i]=IS
Trans[1,i]=FS
endfor
ey=abs(ey)
trans-=1
dey/=(*pState).Energy_Weights
eweights=1d/dey^2
;
x=[x,indgen(nlines)]
y=[y,ey]
weights=[weights,eweights]
end
else:
endcase

ParameterInfoStruc=*(*pState).ParameterInfoStruc
;get starting values from table
;
values=reform((*pstate).Parameter_Table_Input[3,*])

values_struc=ValueConvert(values,event)
p=values_struc.values
p=p[WhereEntry]
np=n_elements(p)
functargs={event:event,nlines:nlines,Trans:Trans}

parinfo=replicate({fixed:[0],limited:[0,0],limits:[0D,0D],tied:''},np)



for i = 0, np-1 do begin
parinfo[i].fixed[0]=reform(ParameterInfoStruc.limits[i,1])
parinfo[i].limited[0]=reform(ParameterInfoStruc.limits[i,2])
parinfo[i].limited[1]=reform(ParameterInfoStruc.limits[i,3])
parinfo[i].limits[0]=reform(ParameterInfoStruc.Fields[i,1])
parinfo[i].limits[1]=reform(ParameterInfoStruc.Fields[i,2])
parinfo[i].tied[0]=values_struc.TypeString_Array[i]
endfor

includearr=reform(ParameterInfoStruc.limits[*,0])

exclude=where(includearr eq 0,count) ; bad programming
if count ne 0 then begin ;keep old values
keepvalues=dblarr(np)
keepvalues[exclude]=p[exclude]
p[exclude]=0.0
parinfo[exclude].fixed[0]=0.0
endif

iterargs = {event:event,ExpressionString_Array:values_struc.ExpressionString_Array}
;print,'x: ',x
;print,'y: ',y
if keyword_set(chi) eq 1 then begin
yfit = mpcurvefit(x,y,weights,p,sigma,itmax=(*pState).MaxIterations,function_name = 'Calc_Chi_Wrapper', $
   /noderivative,parinfo = parinfo,functargs = functargs,/quiet, errmsg=errmsg, STATUS=status,$
   iterargs = iterargs, iterproc = 'MagProp_iterproc', chisq = chisq)
endif else begin
yfit = mpcurvefit(x,y,weights,p,sigma,itmax=(*pState).MaxIterations,function_name = 'Calc_Mag_Wrapper', $
   /noderivative,parinfo = parinfo,functargs = functargs,/quiet, errmsg=errmsg, STATUS=status,$
   iterargs = iterargs, iterproc = 'MagProp_iterproc', chisq = chisq)
endelse


if (errmsg ne '') then begin
    void=dialog_message(dialog_parent=event.top,/error,errmsg)
widget_control,(*pstate).RefineButton,sensitive=1
return
endif


if (status eq 0) then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'Refinement has not been successful '+!ERROR_STATE.MSG)
widget_control,(*pstate).RefineButton,sensitive=1
return
endif




if n_elements(keepvalues) ne 0 then begin
p[exclude]=keepvalues[exclude]
endif



string_array=strarr(1,100)

p_string=strtrim(string(p),2)
whereentry=where(values_struc.ExpressionString_Array ne '', count)
if count ne 0 then begin
p_string[whereentry]=values_struc.ExpressionString_Array[whereentry]
endif



string_array[0,0:n_elements(p)-1]=p_string
(*pstate).Parameter_Table_Input[3,*]=string_array
string_array[0,0:n_elements(sigma)-1]=strtrim(string(sigma),2)
(*pstate).Parameter_Table_Input[4,*]=string_array


widget_control,(*pstate).Parameter_Table,set_value=(*pstate).Parameter_Table_Input

ParameterInfoStruc.fields[*,0]=p
*(*pState).ParameterInfoStruc=ParameterInfoStruc
;MagProp_Update_Droplist,event
ParameterInfoUpdate,event,/DisplayEntry

if (*pState).quantities[0] eq 't' then begin
    if (*pState).TempLims[0] ne -1 then begin
        Calculate_ChiCurve,event    ;plots over the whole temperature range
    endif
endif

MagProp_Plot_Experimental_Data,event


if (*pstate).Energy_Refine eq 1 then begin
*(*pState).OutputEnergies=strtrim(string(yfit),2)
endif
if (*pstate).Energy_Refine eq 2 then begin
;print,'yfit :',yfit
;print,'n_elements(*(*pState).x) :',n_elements(*(*pState).x)
ny=n_elements(y)
ney=n_elements(ey)
*(*pState).OutputEnergies=strtrim(string(yfit[(ny-ney):*]),2)
endif

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

xyouts,xpos,ypos,"Chisq = "+strtrim(string(chisq),2),color=7
;print,'Chisq: ',chisq
;print,xpos
;print,ylims[1]
(*pstate).chisq=chisq

telapsed=systime(/seconds)-tstart

print,'Time Taken for Refinement = ',strtrim(string(telapsed),2),' seconds.'
widget_control,(*pstate).RefineButton,sensitive=1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TempRange_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
;t=(*pState).t
uname=widget_info(event.id,/uname)
case uname of
'LowTSlider':    $
begin
widget_control,(*pState).LowTSlider,get_value = slider
slider=long(slider[0])-1
widget_control,(*pState).LowTField,set_value = (*pState).t[slider]

;widget_control,(*pstate).Calculation_Method,get_value=Calculation_Method
;if Calculation_Method eq 0 then begin
;widget_control,(*pstate).MagFieldTheoryWidth_Base,sensitive=0
;endif else begin
;widget_control,(*pstate).MagFieldTheoryWidth_Base,sensitive=1
;endelse
;return
end
'HighTSlider':    $
begin
widget_control,(*pState).HighTSlider,get_value = slider
slider=long(slider[0])-1
widget_control,(*pState).HighTField,set_value = (*pState).t[slider]
;widget_control,(*pstate).Calculation_Method,get_value=Calculation_Method
;if Calculation_Method eq 0 then begin
;widget_control,(*pstate).MagFieldTheoryWidth_Base,sensitive=0
;endif else begin
;widget_control,(*pstate).MagFieldTheoryWidth_Base,sensitive=1
;endelse
;return
end
'TempRangeAccept':    $
begin
widget_control,(*pState).LowTField,get_value = LowT
LowT=float(LowT[0])
widget_control,(*pState).HighTField,get_value = HighT
HighT=float(HighT[0])
if LowT ge HighT then begin
void=dialog_message(dialog_parent=event.top,/error, $
'Low Temperature Limit Cannot be Greater or Equal to High Temperature Limit')
return
endif
widget_control,(*pState).LowTSlider,get_value = slider
LowTIndex=long(slider[0])-1
widget_control,(*pState).HighTSlider,get_value = slider
HighTIndex=long(slider[0])-1
(*pState1).TempLims=[LowTIndex,HighTIndex]
widget_control,(*pState).PlotFullRange_Value,get_value = PlotFullRange
(*pState1).PlotFullRange=PlotFullRange
ptr_free,pState
widget_control,event.top,/destroy
return
end
'TempRangeCancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TempRange,main_event
widget_control,main_event.top,get_uvalue = pState_main

;get temperature values

t=*(*pState_main).x
t=t[sort(t)]
nt=n_elements(t)

if ((*pState_main).TempLims[0] ne -1) then begin
tmin=t[(*pState_main).TempLims[0]]
tmax=t[(*pState_main).TempLims[1]]
sliderlow=(*pState_main).TempLims[0]+1
sliderhigh=(*pState_main).TempLims[1]+1
endif else begin
tmin=t[0]
tmax=t[nt-1]
sliderlow=1
sliderhigh=nt
endelse
geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Temperature Range for Fit',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center,xsize=180)



Col_Base1=widget_base(tlb,/col,/align_center)


LowTField=cw_field(Col_Base1,/col, $
                 title='Low Temperature Value',value=tmin,/noedit)
LowTSlider=widget_slider(Col_Base1,$
              value=sliderlow,min=1,max=nt,uname='LowTSlider',/suppress_value)


Col_Base2=widget_base(tlb,/col,/align_center)


HighTField=cw_field(Col_Base1,/col, $
                 title='High Temperature Value',value=tmax,/noedit)

HighTSlider=widget_slider(Col_Base1,$
              value=sliderhigh,min=1,max=nt,uname='HighTSlider',/suppress_value)


Col_Base3=widget_base(tlb,/col,/align_center,/frame)


void = widget_label(Col_Base3,value = 'Plot Full Range?')

PlotFullRange_Field = ['Yes','No']

PlotFullRange_Value = cw_bgroup(Col_Base3,PlotFullRange_Field,/row, $
          /exclusive,set_value = (*pState_main).PlotFullRange, $
          /return_index,/no_release)



void = widget_button(tlb,value = 'Accept', uname='TempRangeAccept')
void = widget_button(tlb,value = 'Cancel', uname='TempRangeCancel')




state={LowTSlider:LowTSlider, $
       LowTField:LowTField, $
       HighTSlider:HighTSlider, $
       HighTField:HighTField, $
       t:t, $
       PlotFullRange_Value:PlotFullRange_Value, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'TempRange',tlb,event_handler = 'TempRange_Events' ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ChangeWorkingDirectory_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
case uname of

'Specify_Source_Dir':    $
begin
Source_Dir = DIALOG_PICKFILE(title = 'Select directory',/directory)
widget_control,(*pstate).WDField,set_value=Source_Dir
end
'Accept':    $
begin
widget_control,(*pstate).WDField,get_value=Source_Dir
(*pstate1).Source_Dir=Source_Dir
ptr_free,pState
widget_control,event.top,/destroy
return
end
'Cancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ChangeWorkingDirectory,main_event
widget_control,main_event.top,get_uvalue = pState_main

;get title

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Change Local Working Directoy',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)


WDField=cw_field(tlb,/col,value=(*pState_main).Source_Dir,title='',xsize=30)

void = widget_button(tlb,value = 'Browse', uname='Specify_Source_Dir')


void = widget_button(tlb,value = 'Accept', uname='Accept')
void = widget_button(tlb,value = 'Cancel', uname='Cancel')


state={WDField:WDField, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'ChangeWorkingDirectory',tlb,event_handler = 'ChangeWorkingDirectory_Events' ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ChangeTitle_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
case uname of

'TitleAccept':    $
begin
widget_control,(*pState).TitleField,get_value = Title
(*pState1).title=title
if strlowcase(size(*(*pstate1).x,/tname)) ne 'undefined' then begin
MagProp_Plot_Experimental_Data,main_event
endif
ptr_free,pState
widget_control,event.top,/destroy
return
end
'TitleCancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ChangeTitle,main_event
widget_control,main_event.top,get_uvalue = pState_main

;get title


geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50




tlb = widget_base(title='Change Title',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)



TitleField=cw_field(tlb,/col,value=(*pState_main).Title,title='')



void = widget_button(tlb,value = 'Accept', uname='TitleAccept')
void = widget_button(tlb,value = 'Cancel', uname='TitleCancel')


state={TitleField:TitleField, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'ChangeTitle',tlb,event_handler = 'ChangeTitle_Events' ;register with the xmanager
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;pro DataScale_Events,event
;widget_control,event.top,get_uvalue = pState
;main_event=(*pState).main_event
;widget_control,main_event.top,get_uvalue = pState1
;uname=widget_info(event.id,/uname)
;case uname of
;
;'SFAccept':    $
;begin
;widget_control,(*pState).SF_Field,get_value = SF
;SF=float(SF[0])
;(*pState1).DataScaleFactor=SF
;if strlowcase(size(*(*pstate1).y_original,/tname)) ne 'undefined' then begin
;*(*pstate1).y=(*(*pstate1).y_original)*SF
;MagProp_Plot_Experimental_Data,main_event
;endif
;ptr_free,pState
;widget_control,event.top,/destroy
;return
;end
;'SFCancel':    $
;begin
;ptr_free,pState
;widget_control,event.top,/destroy
;return
;end
;endcase
;end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;pro DataScale,main_event
;widget_control,main_event.top,get_uvalue = pState_main
;
;
;
;tlb = widget_base(title='Data Scaling Factor',/col,group_leader=main_event.top, $
;       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)
;
;
;
;SF_Field=cw_field(tlb,/col,value=(*pState_main).DataScaleFactor,title='')
;
;
;
;void = widget_button(tlb,value = 'Accept', uname='SFAccept')
;void = widget_button(tlb,value = 'Cancel', uname='SFCancel')
;
;
;state={SF_Field:SF_Field, $
;       main_event:main_event}
;
;
;widget_control,tlb,/realize
;
;pState = ptr_new(state,/no_copy)
;widget_control,tlb,set_uvalue = pState
;xmanager, 'DataScale',tlb,event_handler = 'DataScale_Events' ;register with the xmanager
;end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro RefinementOptions_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
case uname of
'MaxIterationsSlider':    $
begin
widget_control,(*pState).MaxIterationsSlider,get_value = slider
widget_control,(*pState).MaxIterationsField,set_value = slider
end
'RefinementOptionsAccept':    $
begin
widget_control,(*pState).MaxIterationsField,get_value = MaxIterations
(*pState1).MaxIterations=MaxIterations[0]
widget_control,(*pState).Weights_Value,get_value = Weights_Value
(*pState1).weighting=Weights_Value[0]
widget_control,event.top,/destroy
return
end
'RefinementOptionsCancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro RefinementOptions,main_event
widget_control,main_event.top,get_uvalue = pState_main

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Refinement Options',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)



Col_Base1=widget_base(tlb,/col,/align_center)


MaxIterationsField=cw_field(Col_Base1,/col, $
                 title='Maximum Number of Iterations',value=(*pState_main).MaxIterations,/noedit)
MaxIterationsSlider=widget_slider(Col_Base1,$
              value=(*pState_main).MaxIterations,min=1,max=100,uname='MaxIterationsSlider',/suppress_value)


Col_Base2=widget_base(tlb,/col,/align_center)

void = widget_label(Col_Base2,value = 'Weighting Scheme')


Weights_Field = ['1 / dy^2 (when defined)','Unity']

Weights_Value = cw_bgroup(Col_Base2,Weights_Field,/col, $
          /exclusive,set_value = (*pState_main).weighting, $
          /return_index,/no_release,/frame,uname='WeightsOption')

void = widget_button(tlb,value = 'Accept', uname='RefinementOptionsAccept')
void = widget_button(tlb,value = 'Cancel', uname='RefinementOptionsCancel')




state={MaxIterationsField:MaxIterationsField, $
       MaxIterationsSlider:MaxIterationsSlider, $
       Weights_Value:Weights_Value, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'RefinementOptions',tlb,event_handler = 'RefinementOptions_Events' ;register with the xmanager


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ErrorBars,event
widget_control,event.top,get_uvalue = pstate
Source_Dir=(*pstate).Source_Dir
file = DIALOG_PICKFILE(title = 'Select File Containing Error Bars',/read,path=Source_Dir)
  if file eq '' then return


line=''
LinesToSkip=0
    finished=0
    openr,lun,file,/get_lun
    while finished eq 0 do begin
    readf,lun,line
    if (strpos(line, '/'))[0] ne -1 and $
    (strpos(strlowcase(line), 't'))[0] ne -1 or $
    (strpos(strlowcase(line), 'a'))[0] ne -1 or $
    (strpos(strlowcase(line), 'e'))[0] ne -1 or $
    (strpos(strlowcase(line), 'i'))[0] ne -1 or $
    (strpos(strlowcase(line), 'o'))[0] ne -1 or $
    (strpos(strlowcase(line), 'u'))[0] ne -1 then begin
    LinesToSkip+=1
    endif else begin
    finished=1
    endelse
    endwhile
    free_lun,lun,/force

;print,'LinesToSkip ', LinesToSkip


data = read_ascii(file,DATA_START=LinesToSkip)


dy = double(reform(data.field1))

n=n_elements(*(*pstate).y)
str=strarr(2)
if n_elements(dy) ne n then begin
str[0]='The file is expected to contain an array of '+strtrim(string(n),2)+' numbers '
str[1]='formatted in one column and '+strtrim(string(n),2)+' rows.'
void=dialog_message(dialog_parent=event.top,/error, str)
return
endif

*(*pstate).dy=dy


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro DerivativeCalcOption_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1

uname=widget_info(event.id,/uname)
case uname of
'Deriv_Choice':    $
begin
widget_control,(*pstate).Calculation_Method,get_value=Calculation_Method
if Calculation_Method eq 0 then begin
widget_control,(*pstate).MagFieldTheoryWidth_Base,sensitive=0
endif else begin
widget_control,(*pstate).MagFieldTheoryWidth_Base,sensitive=1
endelse
return
end
'DerivativeCalcOptionAccept':    $
begin
widget_control,(*pstate).Calculation_Method,get_value=Calculation_Method
(*pState1).DerivOption=Calculation_Method
if Calculation_Method eq 1 then begin
widget_control,(*pstate).MagFieldTheoryWidth,get_value=MagFieldTheoryWidth
(*pState1).FieldWidth=MagFieldTheoryWidth
endif
ptr_free,pState
widget_control,event.top,/destroy
return
end
'DerivativeCalcOptionCancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro DerivativeCalcOption,main_event
widget_control,main_event.top,get_uvalue = pState_main

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Derivative Method',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)


Calculation_Method_Field = ['Hellmann-Feymann','Three Diagonalisations']

Calculation_Method = cw_bgroup(tlb,Calculation_Method_Field,/col, $
          /exclusive,set_value = (*pState_main).DerivOption, $
          /return_index,/no_release,uname='Deriv_Choice')

MagFieldTheoryWidth_Base=widget_base(tlb,/col,/align_center,sensitive=(*pState_main).DerivOption)


MagFieldTheoryWidth=cw_field(MagFieldTheoryWidth_Base,/col,title='B Width (Tesla)', $
       value=(*pState_main).FieldWidth)

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


void = widget_button(Row_Base,value = 'Accept', uname='DerivativeCalcOptionAccept')
void = widget_button(Row_Base,value = 'Cancel', uname='DerivativeCalcOptionCancel')

state={Calculation_Method:Calculation_Method, $
       MagFieldTheoryWidth_Base:MagFieldTheoryWidth_Base, $
       MagFieldTheoryWidth:MagFieldTheoryWidth, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'DerivativeCalcOption',tlb,event_handler = 'DerivativeCalcOption_Events' ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;pro MagMomentMethod_Events,event
;widget_control,event.top,get_uvalue = pState
;main_event=(*pState).main_event
;widget_control,main_event.top,get_uvalue = pState1
;uname=widget_info(event.id,/uname)
;case uname of
;'Accept':    $
;begin
;widget_control,(*pstate).Magnetisation_Method,get_value=Magnetisation_Method
;(*pState1).Magnetisation_Method=Magnetisation_Method
;ptr_free,pState
;widget_control,event.top,/destroy
;return
;end
;'Cancel':    $
;begin
;ptr_free,pState
;widget_control,event.top,/destroy
;return
;end
;else:
;endcase
;end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;pro MagMomentMethod,main_event
;widget_control,main_event.top,get_uvalue = pState_main
;
;geom = widget_info(main_event.top, /geometry)
;xpos = geom.xoffset + geom.xsize/2 - 100
;ypos = geom.yoffset + geom.ysize/2 - 50
;
;tlb = widget_base(title='Method to Calculate Moment',/col,group_leader=main_event.top, $
;       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)
;
;
;Magnetisation_Method_Field = ['Matrix Diagonalisaton at Each Field','Matrix Multiplication at Each Temperature']
;
;Magnetisation_Method = cw_bgroup(tlb,Magnetisation_Method_Field,/col, $
;          /exclusive,set_value = (*pState_main).Magnetisation_Method, $
;          /return_index,/no_release)
;
;
;Row_Base=widget_base(tlb,/row,/align_center)
;
;
;void = widget_button(Row_Base,value = 'Accept', uname='Accept')
;void = widget_button(Row_Base,value = 'Cancel', uname='Cancel')
;
;state={Magnetisation_Method:Magnetisation_Method, $
;       main_event:main_event}
;
;
;widget_control,tlb,/realize
;
;pState = ptr_new(state,/no_copy)
;widget_control,tlb,set_uvalue = pState
;xmanager, 'MagMomentMethod',tlb,event_handler = 'MagMomentMethod_Events' ;register with the xmanager
;end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro DefaultQuantity_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1

uname=widget_info(event.id,/uname)

case uname of
'QuantityDefine':    $
begin
widget_control,(*pState).Quantities_Value,get_value = Quantities_Value
if Quantities_Value eq 3 then begin
widget_control,(*pState).row_Base2,sensitive = 1
endif else begin
widget_control,(*pState).row_Base2,sensitive = 0
endelse

end
'DefaultQuantityAccept':    $
begin
widget_control,(*pState).LowTField,get_value = LowT
LowT=float(LowT[0])
widget_control,(*pState).HighTField,get_value = HighT
HighT=float(HighT[0])
if LowT ge HighT then begin
void=dialog_message(dialog_parent=event.top,/error, $
'Low Temperature Limit Cannot be Greater or Equal to High Temperature Limit')
return
endif
widget_control,(*pState).TpointsField,get_value = Tpoints
Tpoints=fix(Tpoints[0])
if Tpoints lt 2 then begin
void=dialog_message(dialog_parent=event.top,/error, $
'Number of Temperature Points Must be Greater than Two')
return
endif
;
widget_control,(*pState).LowBField,get_value = LowB
LowB=float(LowB[0])
widget_control,(*pState).HighBField,get_value = HighB
HighB=float(HighB[0])
if LowB ge HighB then begin
void=dialog_message(dialog_parent=event.top,/error, $
'Low Field Limit Cannot be Greater or Equal to High Field Limit')
return
endif
widget_control,(*pState).BpointsField,get_value = Bpoints
Bpoints=fix(Bpoints[0])
if Bpoints lt 2 then begin
void=dialog_message(dialog_parent=event.top,/error, $
'Number of Field Points Must be Greater than Two')
return
endif
widget_control,(*pState).Quantities_Value,get_value = Quantities_Value

dv={DefQuant:Quantities_Value, $
    Tmin:LowT,    $
    Tmax:HighT,  $
    Tpoints:Tpoints,   $
    Bmin:LowB,    $
    Bmax:HighB,    $
    Bpoints:Bpoints}

(*pState1).dv=dv


(*pState1).chisq=-10.0
if (*pState1).data eq 0 then begin
GetDefaultValues,main_event
endif
if (*pState1).quantities[1] eq 'Moment' then begin
Calculate_MagCurve,main_event
endif else begin
Calculate_ChiCurve,main_event
endelse


ptr_free,pState
widget_control,event.top,/destroy
return
end
'DefaultQuantityCancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
else:
endcase

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro DefaultQuantity,main_event
widget_control,main_event.top,get_uvalue = pState_main

dv=(*pState_main).dv

DefQuant=dv.DefQuant

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Default Model Quantity',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)


Col_Base1=widget_base(tlb,/col,/base_align_center,/align_center)

Quantities_Field = ['ChiT','Chi','ueff','Magnetisation']

Quantities_Value = cw_bgroup(Col_Base1,Quantities_Field,/row, $
          /exclusive,set_value = DefQuant,/return_index,/no_release,/frame,uname='QuantityDefine')

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

LowTField=cw_field(row_Base1,/col, $
                 title='Low T Value',value=dv.tmin)

HighTField=cw_field(row_Base1,/col, $
                 title='High T Value',value=dv.tmax)

TPointsField=cw_field(row_Base1,/col, $
                 title='Number T Points',value=dv.tpoints)


if dv.DefQuant eq 3 then begin
sens=1
endif else begin
sens=0
endelse


row_Base2=widget_base(tlb,/row,/align_center,sensitive=sens)


LowBField=cw_field(row_Base2,/col, $
                 title='Low B Value',value=dv.bmin)

HighBField=cw_field(row_Base2,/col, $
                 title='High B Value',value=dv.bmax)

BPointsField=cw_field(row_Base2,/col, $
                 title='Number B Points',value=dv.bpoints)


void = widget_button(tlb,value = 'Accept', uname='DefaultQuantityAccept')
void = widget_button(tlb,value = 'Cancel', uname='DefaultQuantityCancel')


state={ LowTField:LowTField, $
       HighTField:HighTField, $
       TPointsField:TPointsField, $
       LowBField:LowBField, $
       HighBField:HighBField, $
       BPointsField:BPointsField, $
       Quantities_Value:Quantities_Value, $
       row_Base2:row_Base2, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'DefaultQuantity',tlb,event_handler = 'DefaultQuantity_Events' ;register with the xmanager




end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro GetDefaultValues,event
widget_control,event.top,get_uvalue = pState
DefQuant=(*pState).DV.DefQuant
;print,'(*pState).quantities[1] ',(*pState).quantities[1]
Tmin=(*pState).DV.Tmin
Tmax=(*pState).DV.Tmax
Tpoints=(*pState).DV.Tpoints
dT = (Tmax-Tmin)/(Tpoints - 1.0)
T=Tmin+dT*findgen(Tpoints)
Tpoints=n_elements(T)
if DefQuant eq 3 then begin
Bmin=(*pState).DV.Bmin
Bmax=(*pState).DV.Bmax
Bpoints=(*pState).DV.Bpoints
dB = (Bmax-Bmin)/(Bpoints - 1.0)
B=Bmin+dB*findgen(Bpoints)
Bpoints=n_elements(B)
Tarr=fltarr(Tpoints*Bpoints)
Barr=fltarr(Tpoints*Bpoints)
N=n_elements(Tarr)
for i=0,Bpoints-1 do begin
Tarr[i*Tpoints]=T
Barr[i*Tpoints]=replicate(B[i],Tpoints)
endfor
BoT=Barr/(Tarr*1e3)
*(*pState).y=fltarr(N)
*(*pState).x=BoT
*(*pState).field=Barr
*(*pState).temperature=Tarr
endif else begin
*(*pState).x=T
*(*pState).y=fltarr(Tpoints)
endelse


Quantities=strarr(3)

    case DefQuant of
    0:    $
    begin
    Quantities[0]='t'
    Quantities[1]='chit'
    end
    1:    $
    begin
    Quantities[0]='t'
    Quantities[1]='chi'
    end
    2:    $
    begin
    Quantities[0]='t'
    Quantities[1]='ueff'
    end
    3:    $
    begin
    Quantities[0]='t'
    Quantities[1]='Moment'
    Quantities[2]='b'
    end
    else:
    endcase

(*pState).Quantities=Quantities


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SusPowderCalcMethod_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1

uname=widget_info(event.id,/uname)
case uname of
'SusPowder_Choice':    $
begin
widget_control,(*pstate).Calculation_Method,get_value=Calculation_Method
if Calculation_Method eq 0 then begin
widget_control,(*pstate).SphereAverage_Base,sensitive=0
endif else begin
widget_control,(*pstate).SphereAverage_Base,sensitive=1
endelse
return
end
'SusPowderCalcMethodAccept':    $
begin
widget_control,(*pstate).Calculation_Method,get_value=Calculation_Method
(*pState1).SusPowderMethod=Calculation_Method
if Calculation_Method eq 1 then begin
widget_control,(*pstate).theta_start,get_value=theta_start
(*pState1).theta_start=theta_start
widget_control,(*pstate).theta_end,get_value=theta_end
(*pState1).theta_end=theta_end
widget_control,(*pstate).theta_nsteps,get_value=theta_nsteps
(*pState1).theta_nsteps=theta_nsteps
widget_control,(*pstate).phi_start,get_value=phi_start
(*pState1).phi_start=phi_start
widget_control,(*pstate).phi_end,get_value=phi_end
(*pState1).phi_end=phi_end
widget_control,(*pstate).phi_nsteps,get_value=phi_nsteps
(*pState1).phi_nsteps=phi_nsteps
endif
ptr_free,pState
widget_control,event.top,/destroy
return
end
'SusPowderCalcMethodCancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SusPowderCalcMethod,main_event
widget_control,main_event.top,get_uvalue = pState_main

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Powder Susceptibility',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)


Calculation_Method_Field = ['ChiAv = (Chix + Chiy + Chiz)/3','Multiple Diagonalisations']

Calculation_Method = cw_bgroup(tlb,Calculation_Method_Field,/col, $
          /exclusive,set_value = (*pState_main).SusPowderMethod, $
          /return_index,/no_release,uname='SusPowder_Choice')

SphereAverage_Base=widget_base(tlb,/col,/align_center,/base_align_center, $
    sensitive=(*pState_main).SusPowderMethod)


SphereAverage_Base_col1=widget_base(SphereAverage_Base,/col,/align_center, $
       /base_align_center)

void=widget_label(SphereAverage_Base_col1,/align_center,value='Theta Angle')

SphereAverage_Base_row1=widget_base(SphereAverage_Base_col1,/row,/align_center, $
       /base_align_center)

theta_start=cw_field(SphereAverage_Base_row1,/col,title='Start',xsize=5, $
       value=(*pState_main).theta_start)
theta_end=cw_field(SphereAverage_Base_row1,/col,title='End',xsize=5, $
       value=(*pState_main).theta_end)
theta_nsteps=cw_field(SphereAverage_Base_row1,/col,title='Step',xsize=5, $
       value=(*pState_main).theta_nsteps)


void=widget_label(SphereAverage_Base_col1,/align_center,value='Phi Angle')

SphereAverage_Base_row2=widget_base(SphereAverage_Base_col1,/row,/align_center, $
       /base_align_center)

phi_start=cw_field(SphereAverage_Base_row2,/col,title='Start',xsize=5, $
       value=(*pState_main).phi_start)
phi_end=cw_field(SphereAverage_Base_row2,/col,title='End',xsize=5, $
       value=(*pState_main).phi_end)
phi_nsteps=cw_field(SphereAverage_Base_row2,/col,title='Step',xsize=5, $
       value=(*pState_main).phi_nsteps)


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


void = widget_button(Row_Base,value = 'Accept', uname='SusPowderCalcMethodAccept')
void = widget_button(Row_Base,value = 'Cancel', uname='SusPowderCalcMethodCancel')

state={Calculation_Method:Calculation_Method, $
       SphereAverage_Base:SphereAverage_Base, $
       theta_start:theta_start, $
       theta_end:theta_end, $
       theta_nsteps:theta_nsteps, $
       phi_start:phi_start, $
       phi_end:phi_end, $
       phi_nsteps:phi_nsteps, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'SusPowderCalcMethod',tlb,event_handler = 'SusPowderCalcMethod_Events' ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagnetisationPowderCalcMethod_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1

uname=widget_info(event.id,/uname)
case uname of
'MagnetisationPowderCalcMethodAccept':    $
begin
widget_control,(*pstate).theta_start,get_value=theta_start
(*pState1).theta_start=theta_start
widget_control,(*pstate).theta_end,get_value=theta_end
(*pState1).theta_end=theta_end
widget_control,(*pstate).theta_nsteps,get_value=theta_nsteps
(*pState1).theta_nsteps=theta_nsteps
widget_control,(*pstate).phi_start,get_value=phi_start
(*pState1).phi_start=phi_start
widget_control,(*pstate).phi_end,get_value=phi_end
(*pState1).phi_end=phi_end
widget_control,(*pstate).phi_nsteps,get_value=phi_nsteps
(*pState1).phi_nsteps=phi_nsteps
ptr_free,pState
widget_control,event.top,/destroy
return
end
'MagnetisationPowderCalcMethodCancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagnetisationPowderCalcMethod,main_event
widget_control,main_event.top,get_uvalue = pState_main

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Powder Magnetisation',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)


SphereAverage_Base_col1=widget_base(tlb,/col,/align_center, $
       /base_align_center)

void=widget_label(SphereAverage_Base_col1,/align_center,value='Theta Angle')

SphereAverage_Base_row1=widget_base(SphereAverage_Base_col1,/row,/align_center, $
       /base_align_center)

theta_start=cw_field(SphereAverage_Base_row1,/col,title='Start',xsize=5, $
       value=(*pState_main).theta_start)
theta_end=cw_field(SphereAverage_Base_row1,/col,title='End',xsize=5, $
       value=(*pState_main).theta_end)
theta_nsteps=cw_field(SphereAverage_Base_row1,/col,title='Step',xsize=5, $
       value=(*pState_main).theta_nsteps)


void=widget_label(SphereAverage_Base_col1,/align_center,value='Phi Angle')

SphereAverage_Base_row2=widget_base(SphereAverage_Base_col1,/row,/align_center, $
       /base_align_center)

phi_start=cw_field(SphereAverage_Base_row2,/col,title='Start',xsize=5, $
       value=(*pState_main).phi_start)
phi_end=cw_field(SphereAverage_Base_row2,/col,title='End',xsize=5, $
       value=(*pState_main).phi_end)
phi_nsteps=cw_field(SphereAverage_Base_row2,/col,title='Step',xsize=5, $
       value=(*pState_main).phi_nsteps)


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


void = widget_button(Row_Base,value = 'Accept', uname='MagnetisationPowderCalcMethodAccept')
void = widget_button(Row_Base,value = 'Cancel', uname='MagnetisationPowderCalcMethodCancel')

state={theta_start:theta_start, $
       theta_end:theta_end, $
       theta_nsteps:theta_nsteps, $
       phi_start:phi_start, $
       phi_end:phi_end, $
       phi_nsteps:phi_nsteps, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'MagnetisationPowderCalcMethod',tlb,event_handler = 'MagnetisationPowderCalcMethod_Events' ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro magprop_SaveImage,event,tiff=tiff,jpeg=jpeg,gif=gif
widget_control,event.top,get_uvalue = pState
Source_Dir=(*pstate).Source_Dir
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=Source_Dir)
endif

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

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagProp_Save_ps,event
widget_control,event.top,get_uvalue = pState
Source_Dir=(*pstate).Source_Dir
directory=Source_Dir
if directory eq '' then begin
directory = DIALOG_PICKFILE(title = 'Select directory',/directory)
endif
thisDevice = !d.name
deviceKeywords = PSConfig(Cancel=canceled,directory = directory,group_leader = event.top)
if canceled ne 1 then begin
  SET_PLOT, 'PS'
  DEVICE, _Extra = deviceKeywords
   MagProp_Plot_Experimental_Data,event,/to_window
  DEVICE, /CLOSE_FILE
  set_plot,thisDevice
endif

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

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

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Read_Ligfield_File,event
widget_control,event.top,get_uvalue = pState
delim=(*pstate).delim
Source_Dir=(*pstate).Source_Dir
filename=dialog_pickfile(path=Source_Dir,/read)
if filename eq '' then return

LigFieldFileStruc=read_jesper(filename,event)
       ;for matrix file enter the chopped down filename
       textLen = strlen(filename)
       pos=strpos(filename,delim,/reverse_Search)
       textLen-=pos
       FileTitle = strmid(filename,textLen-2,/reverse_offset)
;print,'LigFieldFileStruc.fail: ',LigFieldFileStruc.fail
if LigFieldFileStruc.fail eq 2 then return
if LigFieldFileStruc.fail eq 1 then begin
msg=strarr(1)
msg[0]='Unable to Read File'
    void=dialog_message(dialog_parent=event.top,/error,msg)
return
endif
;
;print,tag_names(LigFieldFileStruc)

;LigFieldFileStruc={fail:0, $
;              Matrices:Matrices, $
;              MatrixNames:MatrixNames, $
;              Type:Type, $
;              MatrixDimension:MatrixDimension, $
;              InitialValues:InitialValues}
;commit to memory

n=n_elements(LigFieldFileStruc.MatrixNames)
for i = 0, n-1 do begin
if i ne 0 then begin
MatricesInMemory=create_struct(MatricesInMemory, $
          LigFieldFileStruc.MatrixNames[i],reform(LigFieldFileStruc.Matrices[i,*,*]))
endif else begin
MatricesInMemory=create_struct(LigFieldFileStruc.MatrixNames[0],reform(LigFieldFileStruc.Matrices[0,*,*]))
endelse
endfor
newtags=tag_names(MatricesInMemory)

if strlowcase(size(*(*pstate).MatricesInMemory,/tname)) eq 'struct' then begin
;avoid duplication of tag names
currenttags=tag_names(*(*pstate).MatricesInMemory)
    for i = 0, n-1 do begin
    wheretag=where(newtags eq currenttags,count)
       if count eq 0 then begin
       *(*pstate).MatricesInMemory=create_struct(*(*pstate).MatricesInMemory, $
       newtags[i],MatricesInMemory.(i))
       endif else begin ;overwrite current value
       (*(*pstate).MatricesInMemory).(i)=MatricesInMemory.(i)
        endelse
   endfor
endif else begin
*(*pstate).MatricesInMemory=MatricesInMemory
endelse
;update fields
(*pstate).Matrix_Dimension=LigFieldFileStruc.MatrixDimension
;
;update table and fields
;
;see if there are entries with the same designation to update
;
;establish how many entries there are
Entries=reform((*pstate).Parameter_Table_Input[0,*])
whereentry=where(Entries ne '',Num_Entries)
;if Num_Entries ne 0 then begin
;Entries=Entries[whereentry]
    for i = 0,n-1 do begin ;still valid to use MatricesInMemory structure
    tag=newtags[i]
    index=where(tag eq strupcase(Entries), count)
       if count ne 0 then begin
       (*pstate).Parameter_Table_Input[1,index]=FileTitle
;
;      determine the type
       case LigFieldFileStruc.type[i] of
       0:   $
       begin
       type='Parameter_m'
       end
       1:   $
       begin
       type='Bx_m'
       end
       2:   $
       begin
       type='By_m'
       end
       3:   $
       begin
       type='Bz_m'
       end
       endcase
       (*pstate).Parameter_Table_Input[2,index]=type
       ;inital value
       (*pstate).Parameter_Table_Input[3,index]=LigFieldFileStruc.InitialValues[i]
       ;
       ;gives an indication that this parameter should be fixed
           if (tag eq 'MY_X') or (tag eq 'MY_Y') or (tag eq 'MY_Z') then begin
           (*(*pState).ParameterInfoStruc).limits[index,1]=1
            endif
       endif else begin ; here come the new entries


if Num_Entries eq 0 then begin ;first entry
(*pstate).Parameter_Table_Input[1,0]=FileTitle
;      determine the type
       case LigFieldFileStruc.type[i] of
       0:   $
       begin
       type='Parameter_m'
       end
       1:   $
       begin
       type='Bx_m'
       end
       2:   $
       begin
       type='By_m'
       end
       3:   $
       begin
       type='Bz_m'
       end
       endcase
       (*pstate).Parameter_Table_Input[2,0]=type
       ;inital value
       (*pstate).Parameter_Table_Input[3,0]=LigFieldFileStruc.InitialValues[i]
       (*pstate).Parameter_Table_Input[1,0]=FileTitle
       (*pstate).Parameter_Table_Input[0,0]=tag

widget_control,(*pstate).Parameter_Table,set_value=(*pstate).Parameter_Table_Input

ParameterInfoUpdate,event,/NewEntry

;gives an indication that this parameter should be fixed
if (tag eq 'MY_X') or (tag eq 'MY_Y') or (tag eq 'MY_Z') then begin
(*(*pState).ParameterInfoStruc).limits[0,1]=1
endif

Num_Entries+=1
endif else begin
;get old values
index=Num_Entries

       (*pstate).Parameter_Table_Input[1,index]=FileTitle
;
;      determine the type
       case LigFieldFileStruc.type[i] of
       0:   $
       begin
       type='Parameter_m'
       end
       1:   $
       begin
       type='Bx_m'
       end
       2:   $
       begin
       type='By_m'
       end
       3:   $
       begin
       type='Bz_m'
       end
       endcase
       (*pstate).Parameter_Table_Input[2,index]=type
       ;inital value
       (*pstate).Parameter_Table_Input[3,index]=LigFieldFileStruc.InitialValues[i]
       (*pstate).Parameter_Table_Input[1,index]=FileTitle
       (*pstate).Parameter_Table_Input[0,index]=tag

;




Num_Entries+=1
widget_control,(*pstate).Parameter_Table,set_value=(*pstate).Parameter_Table_Input

ParameterInfoUpdate,event,/NewEntry

       ;gives an indication that this parameter should be fixed
           if (tag eq 'MY_X') or (tag eq 'MY_Y') or (tag eq 'MY_Z') then begin
           (*(*pState).ParameterInfoStruc).limits[index,1]=1
            endif

endelse


       endelse

    endfor

;endif

MagProp_Update_Droplist,event
index=widget_info((*pstate).Parameter_Droplist,/droplist_select)
Parameter_Value=(*(*pState).ParameterInfoStruc).fields[index,0]
LowLimit_Value=(*(*pState).ParameterInfoStruc).fields[index,1]
UpperLimit_Value=(*(*pState).ParameterInfoStruc).fields[index,2]
Parameters_Fix_Value=(*(*pState).ParameterInfoStruc).limits[index,*]
widget_control,(*pstate).Parameter_Value,set_value=Parameter_Value[0]
widget_control,(*pstate).LowLimit_Value,set_value=LowLimit_Value[0]
widget_control,(*pstate).UpperLimit_Value,set_value=UpperLimit_Value[0]
widget_control,(*pstate).Parameters_Fix_Value,set_value=Parameters_Fix_Value
widget_control,(*pstate).Parameter_Table,set_value=(*pstate).Parameter_Table_Input

end



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ImportSquidFile,event
widget_control,event.top,get_uvalue = pState

Source_Dir=(*pstate).Source_Dir

mag_workup_MagProp,tlb,ExternalEvent=event, $
                 ExternalProgramName=(*pstate).register_name, $
                 group_leader = event.top, $
                 workDir = Source_Dir
;
;daveSensitizeButtons,event
if n_elements(tlb) ne 0 then (*pState).MagWorkupTlb=tlb


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro CursorPositionType,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pstate).CursorPosition_Type,get_value = CursorPosition_Type

if CursorPosition_Type eq 0 then begin
(*pstate).CursorPosition=0
endif else begin
        if strlowcase(size(*(*pstate).yt,/tname)) eq 'double' then begin
        (*pstate).CursorPosition=1
        endif else begin
        (*pstate).CursorPosition=0
        widget_control,(*pstate).CursorPosition_Type,set_value = 0
       endelse
endelse

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ExperimentalQuantity_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
Quantities_Field = ['chit','chi','ueff']
case uname of
'ExperimentalQuantityDefine':    $
begin
widget_control,(*pstate).Quantities_Value,get_value = Quantities_Value
if Quantities_Value eq (*pstate).DefQuant then begin
*(*pState1).y=(*pstate).y
*(*pState1).yt=(*pstate).yt
if n_elements((*pstate).dy) ne 1 then *(*pState1).dy=(*pstate).dy
(*pState1).quantities[1]=Quantities_Field[(*pstate).DefQuant]
MagProp_Plot_Experimental_Data,main_event
return
endif

;print,'(*pState1).quantities[1]  ',(*pState1).quantities[1]
;print,'(*pstate).DefQuant  ',(*pstate).DefQuant
;print,'Quantities_Value  ',Quantities_Value

;convert quantity
case (*pstate).DefQuant of
0:  $   ;chit
begin
    if Quantities_Value eq 1 then begin ;convert to chi
    *(*pState1).y=(*pstate).y/(*pstate).x
        if n_elements((*pstate).yt) ne 1 then *(*pState1).yt=(*pstate).yt/(*pstate).x
      if n_elements((*pstate).dy) ne 1 then *(*pState1).dy=(*pstate).dy/(*pstate).x
    (*pState1).quantities[1]=Quantities_Field[Quantities_Value]
    MagProp_Plot_Experimental_Data,main_event
    endif else begin ; convert to ueff
    *(*pState1).y=2.82788*sqrt((*pstate).y)
    if n_elements((*pstate).yt) ne 1 then *(*pState1).yt=2.82788*sqrt((*pstate).yt)
    if n_elements((*pstate).dy) ne 1 then *(*pState1).dy=2.82788*sqrt((*pstate).dy)
    (*pState1).quantities[1]=Quantities_Field[Quantities_Value]
    MagProp_Plot_Experimental_Data,main_event
    endelse
end
1:  $ ;chi
begin
    if Quantities_Value eq 0 then begin ;convert to chit
    *(*pState1).y=(*pstate).y*(*pstate).x
    if n_elements((*pstate).dy) ne 1 then *(*pState1).dy=(*pstate).dy*(*pstate).x
    if n_elements((*pstate).yt) ne 1 then *(*pState1).yt=(*pstate).yt*(*pstate).x
    (*pState1).quantities[1]=Quantities_Field[Quantities_Value]
    MagProp_Plot_Experimental_Data,main_event
    endif else begin ; convert to ueff
    *(*pState1).y=(*pstate).y*(*pstate).x
    *(*pState1).y=2.82788*sqrt(*(*pState1).y)
        if n_elements((*pstate).yt) ne 1 then begin
        *(*pState1).yt=(*pstate).yt*(*pstate).x
        *(*pState1).yt=2.82788*sqrt(*(*pState1).yt)
        endif
    if n_elements((*pstate).dy) ne 1 then begin
    *(*pState1).dy=(*pstate).dy*(*pstate).x
    *(*pState1).dy=2.82788*sqrt(*(*pState1).dy)
    endif
    (*pState1).quantities[1]=Quantities_Field[Quantities_Value]
    MagProp_Plot_Experimental_Data,main_event
    endelse
end
2:  $ ;ueff
begin
    if Quantities_Value eq 0 then begin ;convert to chit
     *(*pState1).y=((*pstate).y)^2/7.9969053
     if n_elements((*pstate).yt) ne 1 then *(*pState1).yt=((*pstate).yt)^2/7.9969053
if n_elements((*pstate).dy) ne 1 then *(*pState1).dy=((*pstate).dy)^2/7.9969053
;*(*pstate).dy
    (*pState1).quantities[1]=Quantities_Field[Quantities_Value]
    MagProp_Plot_Experimental_Data,main_event
    endif else begin ; convert to chi
    *(*pState1).y=((*pstate).y)^2/7.9969053
    *(*pState1).y/=(*pstate).x
if n_elements((*pstate).dy) ne 1 then begin
    *(*pState1).dy=((*pstate).dy)^2/7.9969053
    *(*pState1).dy/=(*pstate).x
endif
        if n_elements((*pstate).yt) ne 1 then begin
        *(*pState1).yt=((*pstate).yt)^2/7.9969053
        *(*pState1).yt/=(*pstate).x
        endif
    (*pState1).quantities[1]=Quantities_Field[Quantities_Value]
    MagProp_Plot_Experimental_Data,main_event
    endelse
end
else:
endcase
end
'ExperimentalQuantityAccept':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
'ExperimentalQuantityCancel':    $
begin
*(*pState1).y=(*pstate).y
*(*pState1).yt=(*pstate).yt
if n_elements((*pstate).dy) ne 1 then *(*pState1).dy=(*pstate).dy
(*pState1).quantities[1]=Quantities_Field[(*pstate).DefQuant]
MagProp_Plot_Experimental_Data,main_event
ptr_free,pState
widget_control,event.top,/destroy
return
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ExperimentalQuantity,main_event
widget_control,main_event.top,get_uvalue = pState


quantities=(*pState).quantities
ytitle=strlowcase(quantities[1])
x=*(*pState).x
y=*(*pState).y
if strlowcase(size(*(*pstate).yt,/tname)) eq 'double' then begin
yt=*(*pstate).yt
endif else begin
yt=0
endelse
if (strlowcase(size(*(*pstate).dy,/tname)) eq 'double') OR $
(strlowcase(size(*(*pstate).dy,/tname)) eq 'float') then begin
dy=*(*pstate).dy
endif else begin
dy=0
endelse
;print,strlowcase(size(*(*pstate).dy,/tname))
Quantities_Field = ['ChiT','Chi','ueff']

DefQuant=(where(ytitle eq strlowcase(Quantities_Field)))[0]

;print,'ytitle  ',ytitle
;print,'DefQuant  ',DefQuant

if DefQuant eq -1 then return

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Change Experimental Quantity',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)


Col_Base1=widget_base(tlb,/col,/base_align_center,/align_center)

Quantities_Field = ['ChiT','Chi','ueff']

Quantities_Value = cw_bgroup(Col_Base1,Quantities_Field,/row, $
          /exclusive,set_value = DefQuant,/return_index,/no_release,/frame,uname='ExperimentalQuantityDefine')

void = widget_button(tlb,value = 'Accept', uname='ExperimentalQuantityAccept')
void = widget_button(tlb,value = 'Cancel', uname='ExperimentalQuantityCancel')


state={ y:y, $
       dy:dy, $
       yt:yt, $
       x:x, $
       DefQuant:DefQuant, $
       Quantities_Value:Quantities_Value, $
       main_event:main_event}

widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'ExperimentalQuantity',tlb,event_handler = 'ExperimentalQuantity_Events' ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro HamMatGen,event
widget_control,event.top,get_uvalue = pState
;daveDeSensitizeButtons,event
;print,'woof'
Source_Dir=(*pstate).Source_Dir

HamiltonianGenerator,tlb,ExternalEvent=event, $
                 ExternalProgramName=(*pstate).register_name, $
                 group_leader = event.top, $
                 workDir = Source_Dir
;
;daveSensitizeButtons,event
if n_elements(tlb) ne 0 then (*pState).HamGenTlb=tlb
;print,'tlb: ',tlb
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MFT_events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
case uname of
'SusPowder_Choice':  $
begin
widget_control,(*pState).MFT_Method,get_value = MFT_Method
case MFT_Method of
0:  $
begin
widget_control,(*pState).MFTCField,sensitive = 1
widget_control,(*pState).MFTCFieldJint,sensitive = 0
widget_control,(*pState).CriterionField,sensitive = 0
widget_control,(*pState).SzField,sensitive = 0
widget_control,(*pState).SxField,sensitive = 0
widget_control,(*pState).SyField,sensitive = 0
widget_control,(*pState).MFTEqText,set_value = (*pState).MFTEquation0
end
1:  $
begin
widget_control,(*pState).MFTCField,sensitive = 1
widget_control,(*pState).MFTCFieldJint,sensitive = 0
widget_control,(*pState).CriterionField,sensitive = 1
widget_control,(*pState).SzField,sensitive = 0
widget_control,(*pState).SxField,sensitive = 0
widget_control,(*pState).SyField,sensitive = 0
widget_control,(*pState).MFTEqText,set_value = (*pState).MFTEquation1
end
2:  $
begin
widget_control,(*pState).MFTCField,sensitive = 0
widget_control,(*pState).MFTCFieldJint,sensitive = 1
widget_control,(*pState).CriterionField,sensitive = 1
widget_control,(*pState).SzField,sensitive = 1
widget_control,(*pState).SxField,sensitive = 1
widget_control,(*pState).SyField,sensitive = 1
widget_control,(*pState).MFTEqText,set_value = (*pState).MFTEquation2
end
else:
endcase
end
'MFTCAccept':    $
begin
widget_control,(*pState).MFT_Method,get_value = MFT_Method
widget_control,(*pState).CriterionField,get_value = CriterionField
widget_control,(*pState).MFTCField,get_value = MFTC
(*pState1).MFTC=float(MFTC[0])
(*pState1).MFT_Treatment=MFT_Method
(*pState1).MFT_Criterion=CriterionField


if MFT_Method eq 2 then begin
widget_control,(*pState).SzField,get_value = SzMatName
widget_control,(*pState).SxField,get_value = SxMatName
widget_control,(*pState).SyField,get_value = SyMatName
;check that matrix file names are valid

if SzMatName eq '' then begin
      void=dialog_message(dialog_parent=event.top,/error, $
    'A valid designation must be entered for Sz')
  return
 endif
if SxMatName eq '' then begin
      void=dialog_message(dialog_parent=event.top,/error, $
    'A valid designation must be entered for Sx')
  return
 endif
if SyMatName eq '' then begin
      void=dialog_message(dialog_parent=event.top,/error, $
    'A valid designation must be entered for Sy')
  return
 endif
MatrixDesignations=reform((*pstate1).Parameter_Table_Input[0,*])
woof=strmatch(MatrixDesignations,SzMatName)
void=where(woof eq 1,count)
  if count eq 0 then begin
      void=dialog_message(dialog_parent=event.top,/error, $
    'The Designation '+SzMatName+' is not recognised')
  return
  endif
woof=strmatch(MatrixDesignations,SxMatName)
void=where(woof eq 1,count)
  if count eq 0 then begin
      void=dialog_message(dialog_parent=event.top,/error, $
    'The Designation '+SxMatName+' is not recognised')
  return
  endif
woof=strmatch(MatrixDesignations,SyMatName)
void=where(woof eq 1,count)
  if count eq 0 then begin
      void=dialog_message(dialog_parent=event.top,/error, $
    'The Designation '+SyMatName+' is not recognised')
  return
  endif
SpinMatrixNames=1
(*pState1).SzMatrixName=SzMatName
(*pState1).SxMatrixName=SxMatName
(*pState1).SyMatrixName=SyMatName
widget_control,(*pState).MFTCFieldJint,get_value = Jint
(*pState1).Jint=float(Jint[0])
endif
;
MFT_Entry,main_event,SpinMatrixNames=SpinMatrixNames
ptr_free,pState
widget_control,event.top,/destroy
return
end
'MFTCCancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
else:
endcase

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MFT,main_event
widget_control,main_event.top,get_uvalue = pState_main



Parameter_Table_Input=(*pState_main).Parameter_Table_Input
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries eq 'lambda' or Entries eq 'Jint',count)
if count ne 0 then begin
msg=strarr(3)
msg[0]='The molecular field interaction has already been defined.'
msg[1]='If you wish to change the definition, then first delete '
msg[2]='the current model.'
 void=dialog_message(dialog_parent=main_event.top,/information,msg)
return
end


courier_font = get_font_name(/large, /courier)

;H(int) = lambda*M
;H(total) = H(internal) + H(external)
;M = Chi(p)*(H(external) + lambda*M)
;Chi= (Chi(p)*(H(external) + lambda*M))/H(external)
;Chi= Chi(p) + lambda*Chi*Chi(p)
;Chi(1 - lambda*Chi(p)) = Chi(p)
;Chi = Chi(p) / (1 - lambda*Chi(p))
;1/ Chi = 1 / Chi(p) - lambda





geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50




tlb = widget_base(title='Molecular Field Theory',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)

;get curent mftc


MFTEquation0 = strarr(11)
MFTEquation0[0]= 'H(int) = lambda*M'
MFTEquation0[1]= 'H(total) = H(internal) + H(external)'
MFTEquation0[2]= 'M = Chi(p)*(H(external) + lambda*M)'
MFTEquation0[3]= 'Chi= (Chi(p)*(H(external) + lambda*M))/H(external)'
MFTEquation0[4]= 'Chi= Chi(p) + lambda*Chi*Chi(p)'
MFTEquation0[5]= 'Chi(1 - lambda*Chi(p)) = Chi(p)'
MFTEquation0[6]= 'Chi = Chi(p) / (1 - lambda*Chi(p))'
MFTEquation0[7]= '1/ Chi = 1 / Chi(p) - lambda'
MFTEquation0[8] = 'The parameter ''lambda'' is related to the'
MFTEquation0[9]= 'interexchange coupling constant by'
MFTEquation0[10]= 'lambda = Jint/(g^2*beta^2)'
;
MFTEquation1 = strarr(14)
MFTEquation1[0]= 'The magnetisation is calculated by'
MFTEquation1[1]= 'solving two self-consistent equations.'
MFTEquation1[2]= 'For the two sublattices A and B:'
MFTEquation1[3]= 'MA = f(B + lambda*MB, T)'
MFTEquation1[4]= 'MB = f(B + lambda*MA, T)'
MFTEquation1[5]= 'If lambda is positive, the exchange interaction'
MFTEquation1[6]= 'is assumed to be feromagnetic and '
MFTEquation1[7]= 'MA is set to MB.  The initial choice of'
MFTEquation1[8]= 'lambda must be nonzero.  The calculation is assumed'
MFTEquation1[9]= 'to have converged when the fractional change in MA'
MFTEquation1[10]= 'is greater than the number ''criterion'''
MFTEquation1[11] = 'The parameter ''lambda'' is related to the'
MFTEquation1[12]= 'interexchange coupling constant by'
MFTEquation1[13]= 'lambda = Jint/(g^2*beta^2)'
;
MFTEquation2 = strarr(11)
MFTEquation2[0]= 'The magnetisation is calculated by'
MFTEquation2[1]= 'solving six self-consistent equations.'
MFTEquation2[2]= 'The inter-exchange Hamiltonian for the'
MFTEquation2[3]= 'two sublattices are written as'
MFTEquation2[4]= 'HA = -Jint*(SzA*|SzB|+SxA*|SxB|+SyA*|SyB|),'
MFTEquation2[5]= 'HB = -Jint*(SzB*|SzA|+SxB*|SxA|+SyB*|SyA|),'
MFTEquation2[6]= 'where |SzB| is the Bolzmann weighted'
MFTEquation2[7]= 'expectation value of SZ over the eigenstates of HB.'
MFTEquation2[8]= 'The calculation is assumed to have'
MFTEquation2[9]= 'converged when the fractional change in all the spin  '
MFTEquation2[10]= 'spin values is greater than the number ''criterion'''


;
basecol1=widget_base(tlb,/col,/base_align_center,/frame)


;MFTEquation = strarr(3)
;
;MFTEquation[0]= 'Method to Calculate Magnetic Properties in a Mean Field'
;MFTEquation[1]= 'Note that the self-consistent field equations are always'
;MFTEquation[2]= 'solved for the calculation of the magnetisation.'

MFTEqText = widget_text(basecol1,value = '',ysize=14,xsize=60,font = courier_font)

MFT_MethodField = ['1/ Chi = 1 / Chi(p) - lambda',$
    'Self-Consistent Field Equations 1','Self-Consistent Field Equations 2']



MFT_Method = cw_bgroup(basecol1,MFT_MethodField,/row, $
          /exclusive,set_value = (*pState_main).MFT_Treatment, $
          /return_index,/no_release,uname='SusPowder_Choice')

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


MFTCField=cw_field(baserow2,/col,value=(*pState_main).MFTC,title='lambda',xsize=12)
MFTCFieldJint=cw_field(baserow2,/col,value=(*pState_main).Jint,title='Jint',xsize=12)
CriterionField=cw_field(baserow2,/col,value=(*pState_main).MFT_Criterion,title='Criterion',xsize=12)
SzField=cw_field(baserow2,/col,value=(*pState_main).SzMatrixName,title='Sz Designation',xsize=12)
SxField=cw_field(baserow2,/col,value=(*pState_main).SxMatrixName,title='Sx Designation',xsize=12)
SyField=cw_field(baserow2,/col,value=(*pState_main).SyMatrixName,title='Sy Designation',xsize=12)


case (*pState_main).MFT_Treatment of
0:  $
begin
widget_control,MFTCField,sensitive = 1
widget_control,MFTCFieldJint,sensitive = 0
widget_control,CriterionField,sensitive = 0
widget_control,SzField,sensitive = 0
widget_control,SxField,sensitive = 0
widget_control,SyField,sensitive = 0
widget_control,MFTEqText,set_value = MFTEquation0
end
1:  $
begin
widget_control,MFTCField,sensitive = 1
widget_control,MFTCFieldJint,sensitive = 0
widget_control,CriterionField,sensitive = 1
widget_control,SzField,sensitive = 0
widget_control,SxField,sensitive = 0
widget_control,SyField,sensitive = 0
widget_control,MFTEqText,set_value = MFTEquation1
end
2:  $
begin
widget_control,MFTCField,sensitive = 0
widget_control,MFTCFieldJint,sensitive = 1
widget_control,CriterionField,sensitive = 1
widget_control,SzField,sensitive = 1
widget_control,SxField,sensitive = 1
widget_control,SyField,sensitive = 1
widget_control,MFTEqText,set_value = MFTEquation2
end
else:
endcase




;MFT_Criterion

void = widget_button(tlb,value = 'Accept', uname='MFTCAccept')
void = widget_button(tlb,value = 'Cancel', uname='MFTCCancel')


state={MFTCField:MFTCField, $
       MFT_Method:MFT_Method, $
       MFTCFieldJint:MFTCFieldJint, $
       CriterionField:CriterionField, $
       MFTEquation0:MFTEquation0, $
       MFTEquation1:MFTEquation1, $
       MFTEquation2:MFTEquation2, $
       MFTEqText:MFTEqText, $
       SzField:SzField, $
       SxField:SxField, $
       SyField:SyField, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'MFT',tlb,event_handler = 'MFT_Events' ;register with the xmanager

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MP_SetField_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
case uname of

'Accept':    $
begin
widget_control,(*pState).FieldValue,get_value = FieldValue
(*pState1).MagFieldTheoryValue=double(FieldValue[0])
ptr_free,pState
widget_control,event.top,/destroy
return
end
'Cancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MP_SetField,main_event

widget_control,main_event.top,get_uvalue = pState_main

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50


tlb = widget_base(title='Set Magnetic Field',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)

;
Base1=widget_base(tlb,/row)

FieldValue=cw_field(Base1,/row,value=(*pState_main).MagFieldTheoryValue,title='Value / Tesla = ',xsize=10)


void = widget_button(tlb,value = 'Accept', uname='Accept')
void = widget_button(tlb,value = 'Cancel', uname='Cancel')


state={FieldValue:FieldValue, $
       main_event:main_event}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'MP_SetField',tlb,event_handler = 'MP_SetField_Events' ;register with the xmanager

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro UpdateMatrixDimension,filename,event
widget_control,event.top,get_uvalue = pState
NewValue=0
;
line=''
nlines=(file_lines(filename))[0]
str=strarr(nlines)
openr,lun,filename,/get_lun
for i = 0, nlines-1 do begin
readf,lun,line
str[i]=strtrim(line,2)
endfor
free_lun,lun,/force
;
nocomments=where(strpos(str,'#') ne 0,count)
if count eq 0 then return
str=strlowcase(str[nocomments])
    MateleString=''
row=-1
col=-1
for i = 0, count-1 do begin
reads,str[i],rowind,colind,matelestring
if rowind gt NewValue then NewValue=rowind
if colind gt NewValue then NewValue=rowind
endfor
if NewValue gt (*pState).matrix_dimension then (*pState).matrix_dimension=NewValue
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MP_InputMatrices_Events,event
widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
case uname of

'Accept':    $
begin
;widget_control,(*pState).FieldValue,get_value = FieldValue
;(*pState1).MagFieldTheoryValue=double(FieldValue[0])
ptr_free,pState
widget_control,event.top,/destroy
return
end
'Specify_Zeeman_mat':   $
begin
;Specify_Zeeman_mat,main_event
Source_Dir=(*pstate1).Source_Dir
delim=(*pstate1).delim
file = DIALOG_PICKFILE(title = 'Select File Containing Coefficient Zeeman Matrix',/read,path=Source_Dir)
  if file ne '' then begin
  textLen = strlen(file)
    pos=strpos(file,delim,/reverse_Search)
textLen-=pos
  FileTitle = strmid(file,textLen-2,/reverse_offset)
    endif else begin
    return
    endelse
widget_control,(*pstate).Zeeman_Mat_FileName,set_value=FileTitle
end
'Specify_add_mat':   $
begin
;Specify_add_mat,main_event
Source_Dir=(*pstate1).Source_Dir
delim=(*pstate1).delim
file = DIALOG_PICKFILE(title = 'Select File Containing Coefficient Matrix',/read,path=Source_Dir)
  if file ne '' then begin
  textLen = strlen(file)
    pos=strpos(file,delim,/reverse_Search)
textLen-=pos
  FileTitle = strmid(file,textLen-2,/reverse_offset)
    endif else begin
    return
    endelse
widget_control,(*pstate).Additional_mat_FileName,set_value=FileTitle
end
'Enter_Zeeman_mat':   $
begin
;Enter_Zeeman_mat,main_event
Parameter_Table_Input=(*pstate1).Parameter_Table_Input
Entries=reform(Parameter_Table_Input[0,*])
widget_control,(*pstate).Zeeman_Mat_FileName,get_value=zee_mat
if zee_mat eq '' then return
Source_Dir=(*pstate1).Source_Dir
filename=Source_Dir+zee_mat
if file_test(filename) eq 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The file '+filename+' is not valid')
return
endif
void=where(Entries ne '',Num_Entries)
InputRow=Num_Entries
widget_control,(*pstate).Zeeman_Mat_Designation,get_value=Zeeman_Mat_Designation
if Zeeman_Mat_Designation eq '' then return
Zeeman_Mat_Designation=strtrim(Zeeman_Mat_Designation[0],2)
whereentry=where(Zeeman_Mat_Designation eq Entries, count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The parameter designation '+''+Zeeman_Mat_Designation+''+' is already in use')
    return
endif
widget_control,(*pstate).Zeeman_Mat_StartVal,get_value=Zeeman_Mat_StartVal
widget_control,(*pstate).Zeeman_Field_Direction,get_value=Zeeman_Field_Direction
Zeeman_Field = ['Bx','By','Bz']
ZeemanDir=Zeeman_Field[Zeeman_Field_Direction]
Parameter_Table_Input[0,InputRow]=Zeeman_Mat_Designation
Parameter_Table_Input[1,InputRow]=zee_mat
Parameter_Table_Input[2,InputRow]=ZeemanDir
Parameter_Table_Input[3,InputRow]=Zeeman_Mat_StartVal
(*pstate1).Parameter_Table_Input=Parameter_Table_Input
widget_control,(*pstate1).Parameter_Table,set_value=Parameter_Table_Input
UpdateMatrixDimension,filename,main_event
MagProp_Update_Droplist,main_event
ParameterInfoUpdate,main_event,/NewEntry
ParameterInfoUpdate,main_event,/Display
end
'Enter_add_mat':   $
begin
;Enter_add_mat,main_event
widget_control,(*pstate).Additional_mat_Designation,get_value=Designation
Designation=strtrim(Designation[0],2)
if Designation eq ''  then return
;
if designation eq 'lambda' then designation = 'Lambda'
Parameter_Table_Input=(*pstate1).Parameter_Table_Input
Entries=reform(Parameter_Table_Input[0,*])
void=where(Entries eq Designation,count)
if count ne 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The parameter designation '+''+Designation+''+' is already in use')
    return
endif
widget_control,(*pstate).Additional_mat_FileName,get_value=File
Source_Dir=(*pstate1).Source_Dir
filename=Source_Dir+File
if file_test(filename) eq 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The file '+filename+' is not valid')
return
endif
void=where(Entries ne '',Num_Entries)
InputRow=Num_Entries
widget_control,(*pstate).Additional_mat_StartVal,get_value=Value
Parameter_Table_Input[0,InputRow]=Designation
Parameter_Table_Input[1,InputRow]=File
Parameter_Table_Input[2,InputRow]='Parameter'
Parameter_Table_Input[3,InputRow]=Value
(*pstate1).Parameter_Table_Input=Parameter_Table_Input
widget_control,(*pstate1).Parameter_Table,set_value=Parameter_Table_Input
UpdateMatrixDimension,filename,main_event
MagProp_Update_Droplist,main_event
ParameterInfoUpdate,main_event,/NewEntry
ParameterInfoUpdate,main_event,/Display
end
'Exit':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MP_InputMatrices,main_event

widget_control,main_event.top,get_uvalue = pState_main

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50


tlb = widget_base(title='Input Matrix Files',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)


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



Model_Basea=widget_base(Model_Base,/col,/align_center,/frame)


void=widget_label(Model_Basea,/align_center,value='Zeeman Matrices')


Model_Basea1=widget_base(Model_Basea,/row,/align_center)


Model_Basea1_row1=widget_base(Model_Basea1,/row,/align_center)

Model_Basea1_row1col1=widget_base(Model_Basea1_row1,/col,/align_center)


Zeeman_Mat_FileName=cw_field(Model_Basea1_row1col1,/col,title='Matrix File',xsize=10, $
       value='')

void = widget_button(Model_Basea1_row1col1,value = 'Browse', uname='Specify_Zeeman_mat')

void = widget_button(Model_Basea1_row1col1,value = 'Add to Model', uname='Enter_Zeeman_mat')

Model_Basea1_row1col2=widget_base(Model_Basea1_row1,/col,/align_center)

Zeeman_Mat_Designation=cw_field(Model_Basea1_row1col2,/col,title='Designation',xsize=10, $
       value='')

Zeeman_Mat_StartVal=cw_field(Model_Basea1_row1col2,/col,title='Value',xsize=10, $
       value='2.0')

Model_Basea1_row1col3=widget_base(Model_Basea1_row1,/col,/align_center)

Zeeman_Field = ['Bx','By','Bz']

Zeeman_Field_Direction = cw_bgroup(Model_Basea1_row1col3,Zeeman_Field,/col, $
          /exclusive,set_value = 0,/return_index,/no_release,/frame)


Model_Baseb=widget_base(Model_Base,/col,/align_center,/frame)


void=widget_label(Model_Baseb,/align_center,value='Additional Input Matrices')

Model_Baseb_row1=widget_base(Model_Baseb,/row,/align_center)

Model_Baseb_row1col1=widget_base(Model_Baseb_row1,/col,/align_center)


Additional_mat_FileName=cw_field(Model_Baseb_row1col1,/col,title='Matrix File',xsize=10, $
       value='')

void = widget_button(Model_Baseb_row1col1,value = 'Browse', uname='Specify_add_mat')

void = widget_button(Model_Baseb_row1col1,value = 'Add to Model', uname='Enter_add_mat')

Model_Baseb_row1col2=widget_base(Model_Baseb_row1,/col,/align_center)

Additional_mat_Designation=cw_field(Model_Baseb_row1col2,/col,title='Designation',xsize=10, $
       value='')

Additional_mat_StartVal=cw_field(Model_Baseb_row1col2,/col,title='Value',xsize=10, $
       value='0')

void = widget_button(tlb,value = 'Exit', uname='Exit')


state={Zeeman_Mat_FileName:Zeeman_Mat_FileName, $
       Zeeman_Mat_Designation:Zeeman_Mat_Designation, $
       Zeeman_Mat_StartVal:Zeeman_Mat_StartVal, $
       Zeeman_Field_Direction:Zeeman_Field_Direction, $
       Additional_mat_FileName:Additional_mat_FileName, $
       Additional_mat_Designation:Additional_mat_Designation, $
       Additional_mat_StartVal:Additional_mat_StartVal, $
       main_event:main_event}

widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'MP_InputMatrices',tlb,event_handler = 'MP_InputMatrices_Events' ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Diagonalisation_Method_Events,event


   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
msg=strarr(1)
msg[0]='Input Error'
    void=dialog_message(dialog_parent=event.top,/error,msg)
return
endif


widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
case uname of

'Accept':    $
begin
	widget_control,(*pState).Method_Field_Type,get_value=Method_Field_Type
	widget_control,(*pState).Range_Field_Type,get_value=Range_Field_Type
	widget_control,(*pState).Range_field,get_value=Range_field_str
	widget_control,(*pState).Tolerance_Field_Type,get_value=Tolerance_Field_Type
	widget_control,(*pState).Tolerance_field,get_value=Tolerance_field
if Range_field_str ne '' then begin
if (Range_Field_Type eq 1)   then begin
Range_field=lonarr(2)
reads,Range_field_str,Range_field
*(*pState1).EigenvalueRange_Value=Range_field
endif else begin
Range_field=dblarr(2)
reads,Range_field_str,Range_field
*(*pState1).EigenvalueRange_Value=Range_field
endelse
endif

	(*pState1).Algorithm_type=Method_Field_Type
	(*pState1).EigenvalueTolerance_type=Tolerance_Field_Type
	(*pState1).EigenvalueRange_type=Range_Field_Type
	(*pState1).EigenvalueRange_Value_str=Range_field_str
if Tolerance_Field_Type eq 0 then begin
(*pState1).EigenvalueTolerance_Value=0
endif else begin
(*pState1).EigenvalueTolerance_Value=Tolerance_field
endelse
ptr_free,pState
widget_control,event.top,/destroy
return
end
'Cancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
'ChooseMethod':    $
begin
	widget_control,(*pState).Method_Field_Type,get_value=Method_Field_Type
	if Method_Field_Type ne 2 then begin
	widget_control,(*pstate).Base_Col3,sensitive=1
	widget_control,(*pstate).Base_Col4,sensitive=1
	endif else begin
	widget_control,(*pstate).Base_Col3,sensitive=0
	widget_control,(*pstate).Base_Col4,sensitive=0
	endelse
end
'ChooseTolerance':    $
begin
	widget_control,(*pState).Tolerance_Field_Type,get_value=Tolerance_Field_Type
	widget_control,(*pstate).Base_Col4_Row2,sensitive=Tolerance_Field_Type
end
'ChooseRange':    $
begin
	widget_control,(*pState).Range_Field_Type,get_value=Range_Field_Type
	widget_control,(*pstate).Base_Col3_Row2,sensitive=Range_Field_Type
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Diagonalisation_Method,main_event
widget_control,main_event.top,get_uvalue = pState

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50


tlb = widget_base(title='Diagonalisation Method',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)


Base_Col2=widget_base(tlb,/col,/align_center,/frame)

void = widget_label(Base_Col2,value = 'Diagonalisation Algorithm')


Method_Field = ['Tridiagonal Decomposition','Relatively Robust Representation','Divide-and-Conquer']

Method_Field_Type = cw_bgroup(Base_Col2,Method_Field,/row, $
          /exclusive,set_value = (*pstate).Algorithm_type,/return_index,/no_release,uname='ChooseMethod')


Base_Col3=widget_base(tlb,/col,/align_center,/frame,sensitive=1-fix((*pstate).Algorithm_type/2.0))

void = widget_label(Base_Col3,value = 'Specify Range')

Base_Col3_Row1=widget_base(Base_Col3,/row,/align_center)


Range_Field = ['All Eigenvalues','Eigenvalue Indices ( Format = Low,High )','Lower and Upper Bounds']

Range_Field_Type = cw_bgroup(Base_Col3_Row1,Range_Field,/row, $
          /exclusive,set_value = (*pstate).EigenvalueRange_type,/return_index,/no_release,uname='ChooseRange')


Base_Col3_Row2=widget_base(Base_Col3_Row1,/row,/align_center,sensitive=(*pstate).EigenvalueRange_type)



Range_field=cw_field(Base_Col3_Row2,/row,title=' ',value=(*pstate).EigenvalueRange_Value_str)


Base_Col4=widget_base(tlb,/col,/align_center,/frame,sensitive=1-fix((*pstate).Algorithm_type/2.0))

void = widget_label(Base_Col4,value = 'Define Tolerance.  Minimum Value = '+strtrim(string(2*(machar()).xmin),2))


Base_Col4_Row1=widget_base(Base_Col4,/row,/align_center)


Tolerance_Field = ['Use Default','Define Value']

Tolerance_Field_Type = cw_bgroup(Base_Col4_Row1,Tolerance_Field,/row, $
          /exclusive,set_value = (*pstate).EigenvalueTolerance_type,/return_index,/no_release,uname='ChooseTolerance')



Base_Col4_Row2=widget_base(Base_Col4_Row1,/row,/align_left,sensitive=(*pstate).EigenvalueTolerance_type)


Tolerance_field=cw_field(Base_Col4_Row2,/row,title=' ',value=(*pstate).EigenvalueTolerance_value)


void = widget_button(tlb,value = 'Accept and Exit', uname='Accept')
void = widget_button(tlb,value = 'Cancel and Exit', uname='Cancel')


state={main_event:main_event ,$
	   Base_Col3:Base_Col3 ,$
	   Base_Col4:Base_Col4 ,$
	   Base_Col3_Row2:Base_Col3_Row2 ,$
	   Base_Col4_Row2:Base_Col4_Row2 ,$
	   Method_Field_Type:Method_Field_Type ,$
	   Range_Field_Type:Range_Field_Type ,$
	   Range_field:Range_field ,$
	   Tolerance_Field_Type:Tolerance_Field_Type ,$
	   Tolerance_field:Tolerance_field}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'Diagonalisation_Method',tlb,event_handler = 'Diagonalisation_Method_Events' ;register with the xmanager



end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MP_RefineEnergies_Events,event


   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
msg=strarr(1)
msg[0]='Input Error'
    void=dialog_message(dialog_parent=event.top,/error,msg)
return
endif


widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1
uname=widget_info(event.id,/uname)
case uname of
'Accept':    $
begin
widget_control,(*pState).RE_Option_Type,get_value = RE_Option_Type
(*pState1).Energy_Refine=RE_Option_Type
widget_control,(*pState).Experimental_Energies,get_value = Experimental_Energies
;whereneblank=where(Experimental_Energies ne '',count)
;if count ne 0 then Experimental_Energies=Experimental_Energies[whereneblank]
;Experimental_Energies=strtrim(Experimental_Energies,2)
;whereentry=where(strpos(Experimental_Energies, ';') ne 0, count)
;if count ne 0 then Experimental_Energies=Experimental_Energies[whereentry]
*(*pstate1).InputEnergies=Experimental_Energies
widget_control,(*pState).Temperature_field,get_value = RefineEnergyTemperature
RefineEnergyTemperature=float(RefineEnergyTemperature)
widget_control,(*pState).EW_field,get_value = EW_field
Energy_Weights=float(EW_field)
widget_control,(*pState).MagField_field,get_value = MagField
MagField=float(MagField)
widget_control,(*pState).Theta_field,get_value = Theta
Theta=float(Theta)
widget_control,(*pState).Phi_field,get_value = Phi
Phi=float(Phi)
(*pstate1).Energy_Weights=Energy_Weights
(*pstate1).RefineEnergyTemperature=RefineEnergyTemperature
(*pstate1).ER_Field=MagField
(*pstate1).ER_Theta=Theta
(*pstate1).ER_Phi=Phi
ptr_free,pState
widget_control,event.top,/destroy
return
end
'Cancel':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
'RE_Option':    $
begin
widget_control,(*pState).RE_Option_Type,get_value = RE_Option_Type
if RE_Option_Type eq 2 then begin
widget_control,(*pState).Base_Col1_Row3,sensitive = 1
endif else begin
widget_control,(*pState).Base_Col1_Row3,sensitive = 0
endelse
;
if (RE_Option_Type eq 0) or $
((*pstate1).MFT_Treatment ne 2) or $
((*pState).MFPresent eq 0) then begin $
widget_control,(*pState).Base_Col1_Row4,sensitive = 0
endif else begin
widget_control,(*pState).Base_Col1_Row4,sensitive = 1
;
endelse
;
end
else:
endcase

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MP_RefineEnergies,main_event
widget_control,main_event.top,get_uvalue = pState

fail=0
if keyword_set(refine) eq 0 then ConstructMatrices,main_event,fail
if fail eq 1 then return
MFPresent=0
if ((*pstate).MFTC_Pointers[0] eq 1) and $
   (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) then $
MFPresent=1


courier_font = get_font_name(/large, /courier)

geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50


tlb = widget_base(title='Choose Quantity to Refine On',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)
;


Base_Row3=widget_base(tlb,/row,/align_center,/frame)

Base_Row1=widget_base(Base_Row3,/row,/align_center)

Option_Field = ['Magnetic Data','Energy Spectrum','Magnetic Data and Energy Spectrum ']

RE_Option_Type = cw_bgroup(Base_Row1,Option_Field,/col, $
          /exclusive,set_value = (*pstate).Energy_Refine,/return_index,/no_release,uname='RE_Option')


Base_Col1=widget_base(Base_Row3,/col,/align_center)

Base_Col1_Row1=widget_base(Base_Col1,/col,/align_center)
;
void = widget_label(Base_Col1_Row1,value = 'Input Variables')
;
;
Base_Col1_Row2=widget_base(Base_Col1_Row1,/row,/align_center)


MagField_field=cw_field(Base_Col1_Row2,/col,title='B (Tesla)',xsize=10, $
       value=(*pstate).ER_Field)

Theta_field=cw_field(Base_Col1_Row2,/col,title='Theta / Deg.',xsize=10, $
       value=strtrim(string(float((*pstate).ER_Theta)),2))

Phi_field=cw_field(Base_Col1_Row2,/col,title='Phi / Deg.',xsize=10, $
       value=strtrim(string(float((*pstate).ER_Phi)),2))

Base_Col1_Row4=widget_base(Base_Col1_Row2,/row,/align_center)

if ((*pstate).Energy_Refine eq 0) or $
((*pstate).MFT_Treatment ne 2) or $
(MFPresent eq 0) then $
widget_control,Base_Col1_Row4,sensitive = 0

Temperature_field=cw_field(Base_Col1_Row4,/col,title='Temperature',xsize=10, $
       value=strtrim(string(float((*pstate).RefineEnergyTemperature)),2))

Base_Col1_Row3=widget_base(Base_Col1_Row2,/row,/align_center)

if (*pstate).Energy_Refine ne 2 then widget_control,Base_Col1_Row3,sensitive = 0


EW_field=cw_field(Base_Col1_Row3,/col,title='Energy Weights',xsize=10, $
       value=strtrim(string(float((*pstate).Energy_Weights)),2))


void=widget_label(tlb, font = courier_font, $
value='Energies, Errors and Assignments              Calculated Values')
;

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

if  (*(*pstate).InputEnergies)[0] eq '' then begin
InputEnergies=strarr(4)
InputEnergies[0]=';Enter the data the following way:'
InputEnergies[1]=';Value  Error  Initial State  Final State.'
InputEnergies[2]=';For example:'
InputEnergies[3]=';15.42  0.06  1  3'
*(*pstate).InputEnergies=InputEnergies
endif 

Experimental_Energies = widget_text(Base_Row2,value=*(*pstate).InputEnergies,$
                        ysize=20,xsize=43, font = courier_font,/scroll,/edit)



Calculated_Energies = widget_text(Base_Row2,value = *(*pstate).OutputEnergies,$
                      ysize=20,xsize=33, font = courier_font,/scroll)


void = widget_button(tlb,value = 'Accept and Exit', uname='Accept')
void = widget_button(tlb,value = 'Cancel and Exit', uname='Cancel')

state={main_event:main_event, $
      RE_Option_Type:RE_Option_Type, $
      Base_Col1_Row3:Base_Col1_Row3, $
      Base_Col1_Row4:Base_Col1_Row4, $
      EW_field:EW_field, $
      MagField_field:MagField_field, $
      Theta_field:Theta_field, $
      Phi_field:Phi_field, $
      MFPresent:MFPresent, $
      Temperature_field:Temperature_field, $
      Experimental_Energies:Experimental_Energies}


widget_control,tlb,/realize

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'MP_RefineEnergies',tlb,event_handler = 'MP_RefineEnergies_Events' ;register with the xmanager



end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Diagonalise_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




widget_control,event.top,get_uvalue = pState
main_event=(*pState).main_event
widget_control,main_event.top,get_uvalue = pState1

uname=widget_info(event.id,/uname)
case uname of

'Calculate':    $
begin
widget_control,(*pstate).CalculateButton,sensitive=0
widget_control,(*pstate).MagField_field,get_value=Field
field=double(field[0])
widget_control,(*pstate).Theta_field,get_value=Theta
Theta=double(Theta[0])
widget_control,(*pstate).Phi_field,get_value=Phi
Phi=double(Phi[0])
;get temperature
widget_control,(*pstate).temperature_field,get_value=t
t=double(t[0])
widget_control,(*pState).Eigenvectors_Type,get_value=Eigenvectors_Type

theta_rad=theta*!DTOR
phi_rad=phi*!DTOR
Parameter_Table_Input=(*pstate1).Parameter_Table_Input
kb=(*pstate1).constants.kb

Matrix_Dimension=(*pstate1).Matrix_Dimension
ZeemanMatrices=*(*pstate1).ZeemanMatrices
Zeeman_Pointers=*(*pstate1).Zeeman_Pointers
Counter=(*pstate1).Zeeman_Matrix_Counter; [countx,county,countz]
;
BxMat=ZeemanMatrices[0:Counter[0]-1,*,*]
ByMat=ZeemanMatrices[Counter[0]:Counter[0]+Counter[1]-1,*,*]
BzMat=ZeemanMatrices[Counter[0]+Counter[1]:Counter[0]+Counter[1]+Counter[2]-1,*,*]

;
Bx_Value=make_array(Counter[0],/double)
By_Value=make_array(Counter[1],/double)
Bz_Value=make_array(Counter[2],/double)

values=reform(Parameter_Table_Input[3,*])
values_struc=ValueConvert(values,main_event)
values=values_struc.values
;help,values
Bx_Value[*]=values[Zeeman_Pointers[0:Counter[0]-1]]
By_Value[*]=values[Zeeman_Pointers[Counter[0]:Counter[0]+Counter[1]-1]]
Bz_Value[*]=values[Zeeman_Pointers[Counter[0]+Counter[1]:Counter[0]+Counter[1]+Counter[2]-1]]
;
;
Bz_Value*=cos(theta_rad)
Bx_Value*=(sin(theta_rad)*cos(phi_rad))
By_Value*=(sin(theta_rad)*sin(phi_rad))
;
N=(size(ZeemanMatrices))[1]
H=dcomplexarr(Matrix_Dimension,Matrix_Dimension)

dHdB=dcomplexarr(Matrix_Dimension,Matrix_Dimension)
for i = 0,counter[0]-1 do begin
H+=field*reform(BxMat[i,*,*])*Bx_Value[i]
dHdB+=reform(BxMat[i,*,*])*Bx_Value[i]
endfor
for i = 0,counter[1]-1 do begin
H+=field*reform(ByMat[i,*,*])*By_Value[i]
dHdB+=reform(ByMat[i,*,*])*By_Value[i]
;print,'Hy: ',H
endfor
for i = 0,counter[2]-1 do begin
H+=field*reform(BzMat[i,*,*])*Bz_Value[i]
dHdB+=reform(BzMat[i,*,*])*Bz_Value[i]
endfor
;print,'H: ',H
*(*pstate1).dHdB=dHdB
;check for existence of additional matrices

n_AdditionalMatrices=n_elements(*(*pstate1).entries)-N $
              -(*pstate1).Diamagnetism[0] $
              -(*pstate1).ModelScaleFactor[0] $
              -(*pstate1).MFTC_Pointers[0]

if n_AdditionalMatrices gt 0 then begin
AdditionalMatrices=*(*pstate1).AdditionalMatrices
AddMat_Pointers=*(*pstate1).AddMat_Pointers
ParameterInfoStruc=*(*pState1).ParameterInfoStruc
    for i = 0, n_AdditionalMatrices-1 do begin
    index=AddMat_Pointers[i]
        if reform(ParameterInfoStruc.limits[index,0]) eq 1 then begin
        mat=reform(AdditionalMatrices[i,*,*])
         mat_Value=values[index]
         H+=mat*mat_Value
        endif
    endfor
endif

tspins=0.0

IF ((*pstate1).MFTC_Pointers[0] eq 1) AND $
    (reform((*(*pState1).ParameterInfoStruc).limits[(*pstate1).MFTC_Pointers[1],0]) eq 1) AND $
    ((*pState1).MFT_Treatment eq 2) THEN BEGIN
MFT_OPTION=1
ENDIF ELSE BEGIN
MFT_OPTION=0
ENDELSE

IF MFT_OPTION eq 1 THEN BEGIN
    index=(*pstate1).MFTC_Pointers[1]
    Jint=(double(reform((*pstate1).Parameter_Table_Input[3,index])))[0]

OldDerivOption=(*pState1).DerivOption
(*pState1).DerivOption=0

tstart=systime(/seconds)
Iterations=0
Criterion=(*pState1).MFT_Criterion
Test=0.0
Sx=reform((*(*pstate1).SpinMatrices)[0,*,*])
Sy=reform((*(*pstate1).SpinMatrices)[1,*,*])
Sz=reform((*(*pstate1).SpinMatrices)[2,*,*])
;
PrintOption=1
;
;if PrintOption eq 1 then begin
;filename=(*pstate1).Source_Dir+'SpinExpectationValues.txt'
;print,'filename: ',filename
;format_float = '(7f-12.5,2x)'
;openw,lun,filename,/get_lun
;endif
Szex=0.1d
Sxex=0.1d
Syex=0.1d
AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermA_Last=AddTermA
AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
AddTermB_Last=AddTermB
while (Test lt Criterion) and (iterations lt 100) do begin
Iterations+=1
;
CalculateEnergies,main_event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,AddTerm=AddTermA
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
if PrintOption eq 1 then begin
SBZ=Szex[0]
SBX=Sxex[0]
SBY=Syex[0]
endif


AddTermB=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
 TestB=norm(AddTermB)/norm(AddTermB_Last)
  if TestB gt 1.0 then TestB=1/TestB
  AddTermB_Last=AddTermB

CalculateEnergies,main_event,field,theta,phi,eigenvalues,eigenvectors=eigenvectors,AddTerm=AddTermB
MINEIG=MIN(eigenvalues)
eigenvalues-=MINEIG
eigenvalues-=5
exponent=reform(exp(-eigenvalues/(kb*t)))
exponent/=total(exponent)
n_eigenvalues=n_elements(eigenvalues)
;
Strans=conj(eigenvectors)##Sz##transpose(eigenvectors)
Szex=0.0d
for j = 0, n_eigenvalues-1 do begin
Szex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sy##transpose(eigenvectors)
Syex=0.0d
for j = 0, n_eigenvalues-1 do begin
Syex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
Strans=conj(eigenvectors)##Sx##transpose(eigenvectors)
Sxex=0.0d
for j = 0, n_eigenvalues-1 do begin
Sxex+=exponent[j]*real_part(reform(Strans[j,j]))
endfor
;
if PrintOption eq 1 then begin
SAZ=Szex[0]
SAX=Sxex[0]
SAY=Syex[0]
endif

AddTermA=-Jint*(Sz*Szex[0]+Sx*Sxex[0]+Sy*Syex[0])
if norm(AddTermA) lt 1e-5 then begin
test = 1.0
endif else begin
TestA=norm(AddTermA)/norm(AddTermA_Last)
  if TestA gt 1.0 then TestA=1/TestA
test = testA < testB
  endelse
  AddTermA_Last=AddTermA
endwhile
;print,'iterations: ',iterations
;print,'test ',test
;print,'Szex[0] ',Szex[0]
;print,'Sxex[0] ',Sxex[0]
;print,'Syex[0] ',Syex[0]
H+=AddtermA
(*pState1).DerivOption=OldDerivOption
tspins=systime(/seconds)-tstart
ENDIF  

msg=strarr(23)

if (*pState1).Algorithm_type eq 0 then method='Tridiagonal Decomposition'
if (*pState1).Algorithm_type eq 1 then method='Relatively Robust Representation'
if (*pState1).Algorithm_type eq 2 then method='Divide-and-Conquer'
if (*pState1).EigenvalueTolerance_Value eq 0.0 then begin
tolerance='Tolerance = Default'
endif else begin
tolerance='Tolerance = '+strtrim(string((*pState1).EigenvalueTolerance_Value),2)
endelse

; first calculate with eigenvectors
tstart=systime(/seconds)
	case (*pState1).EigenvalueRange_type of
	0:   $
	begin
	range='All Eigenvalues Calculated'
	eigenvalues=LA_EIGENQL(H,/double, $
			eigenvectors=eigenvectors,$
			method=(*pState1).Algorithm_type,$
			tolerance=(*pState1).EigenvalueTolerance_Value, $
			status = status)
	end
	1:   $
	begin

	range='Eigenvalues indices '+strtrim(string((*(*pState1).EigenvalueRange_Value)[0]),2)+' to '+ $
	    strtrim(string((*(*pState1).EigenvalueRange_Value)[1]),2)+' Calculated.'

	eigenvalues=LA_EIGENQL(H,/double, $
			eigenvectors=eigenvectors,$
			method=(*pState1).Algorithm_type,$
			range=*(*pState1).EigenvalueRange_Value,$
			tolerance=(*pState1).EigenvalueTolerance_Value, $
			status = status)
	end
	2:   $
	begin
	range='Eigenvalues in the range from '+strtrim(string((*(*pState1).EigenvalueRange_Value)[0]),2)+' to '+ $
	    strtrim(string((*(*pState1).EigenvalueRange_Value)[1]),2)+' Calculated.'
	eigenvalues=LA_EIGENQL(H,/double, $
			eigenvectors=eigenvectors,$
			method=(*pState1).Algorithm_type,$
			search_range=*(*pState1).EigenvalueRange_Value,$
			tolerance=(*pState1).EigenvalueTolerance_Value, $
			status = status)
	end
	else:
	endcase

telapsed=systime(/seconds)-tstart+tspins
telapsed*=1e3
;print,'Time Taken for diagonalisation with eigenvectors = ',strtrim(string(telapsed),2),' seconds.'
;tstart=systime(/seconds)


msg[0]='              Output Information'

msg[1]='Diagonalisation Method:'
msg[2]=method
msg[3]=range
msg[4]=tolerance
msg[5]='Time Taken for Computation of'
msg[6]='Eigenvalues and Eigenvectors: '+strtrim(string(telapsed),2)+' ms.'
if status eq 0 then begin
msg[7]='Eigenvalues and Eigenvectors'
msg[8]='have been computed successfully'
endif else begin
msg[7]='The computation of both Eigenvalues and
msg[8]='Eigenvalues has not been successful'
endelse




	tstart=systime(/seconds)


	case (*pState1).EigenvalueRange_type of
	0:   $
	begin
	eigenvalues=LA_EIGENQL(H,/double, $
			method=(*pState1).Algorithm_type,$
			tolerance=(*pState1).EigenvalueTolerance_Value)
	end
	1:   $
	begin
	eigenvalues=LA_EIGENQL(H,/double, $
			method=(*pState1).Algorithm_type,$
			range=*(*pState1).EigenvalueRange_Value,$
			tolerance=(*pState1).EigenvalueTolerance_Value)
	end
	2:   $
	begin
	eigenvalues=LA_EIGENQL(H,/double, $
			method=(*pState1).Algorithm_type,$
			search_range=*(*pState1).EigenvalueRange_Value,$
			tolerance=(*pState1).EigenvalueTolerance_Value)
	end
	else:
	endcase
telapsed=systime(/seconds)-tstart+tspins
;print,'Time Taken for diagonalisation without eigenvectors = ',strtrim(string(telapsed),2),' seconds.'

telapsed*=1e3
n=n_elements(eigenvalues)


msg[9]=' '

msg[10]='Time Taken for Computation'
msg[11]='of Eigenvalues Alone: '+strtrim(string(telapsed),2)+' ms.'
if status eq 0 then begin
msg[12]='Eigenvalue Computation has been Successful'
msg[13]='Number of Eigenvalues: '+strtrim(string(n),2)
msg[14]='Lowest Level at Energy: '+strtrim(string(eigenvalues[0]),2)+' cm-1'

IF MFT_OPTION eq 1 THEN BEGIN
msg[15]=' '
msg[16]='Spin Expectation Values'
msg[17]='SAZ: '+strtrim(string(SAZ),2)
msg[18]='SAX: '+strtrim(string(SAX),2)
msg[19]='SAY: '+strtrim(string(SAY),2)
msg[20]='SBZ: '+strtrim(string(SBZ),2)
msg[21]='SBX: '+strtrim(string(SBX),2)
msg[22]='SBY: '+strtrim(string(SBY),2)
ENDIF



widget_control,(*pstate).Info_text,set_value=msg
endif else begin
msg[11]='The computation of Eigenvalues'
msg[12]='Alone has not been successful'
widget_control,(*pstate).Info_text,set_value=msg
return
endelse

eigenvalues-=eigenvalues[0]


widget_control,(*pstate).Info_text,set_value=msg

CalculateMoments,main_event,theta,phi,eigenvectors=eigenvectors,mome,field=field
;
;Query whether expectation Values have been requested
;
widget_control,(*pstate).ExpectationValue_Type,get_value=ExpectationValue_Type


IF (ExpectationValue_Type eq 1) THEN BEGIN

ZeemanMatrices=*(*pstate1).ZeemanMatrices
Zeeman_Pointers=*(*pstate1).Zeeman_Pointers
n_Zeeman=n_elements(Zeeman_Pointers)

OperatorNames=strarr(n_Zeeman+n_AdditionalMatrices)
OperatorExpectationValues=dblarr(n_Zeeman+n_AdditionalMatrices,Matrix_Dimension)
    for i = 0, n_Zeeman-1 do begin
    index=Zeeman_Pointers[i]
    OperatorNames[i]=(*pstate1).Parameter_Table_Input[0,index] 
    mat=conj(eigenvectors)##reform(ZeemanMatrices[i,*,*])##transpose(eigenvectors)
      for j = 0, Matrix_Dimension-1 do begin
      OperatorExpectationValues[i,j]=mat[j,j]
      endfor    
    endfor
;
if n_AdditionalMatrices ne 0 then begin
    for i = 0, n_AdditionalMatrices-1 do begin
    index=AddMat_Pointers[i]
    OperatorNames[i+n_Zeeman]=(*pstate1).Parameter_Table_Input[0,index] 
    mat=conj(eigenvectors)##reform(AdditionalMatrices[i,*,*])##transpose(eigenvectors)
      for j = 0, Matrix_Dimension-1 do begin
      OperatorExpectationValues[i+n_Zeeman,j]=mat[j,j]
      endfor    
    endfor
endif

;print,'n_AdditionalMatrices ',n_AdditionalMatrices
;print,'OperatorNames ',OperatorNames
;print,'OperatorExpectationValues[8,*] ',OperatorExpectationValues[8,*]
;print,''
;print,'OperatorExpectationValues[9,*] ',OperatorExpectationValues[9,*]
;print,''
;print,'OperatorExpectationValues[10,*] ',OperatorExpectationValues[10,*]

OutPutarr=strarr(n_Zeeman+n_AdditionalMatrices+2,n+1)
OutPutarr[0,0]='Eigenvalues'
OutPutarr[1,0]='-dE/dB'

for i = 0, n_Zeeman+n_AdditionalMatrices-1 do begin
OutPutarr[i+2,0]='<'+strtrim(OperatorNames[i],2)+'>'
endfor

for j = 0, n-1 do begin
OutPutarr[0,j+1]=strtrim(string(eigenvalues[j]),2)
OutPutarr[1,j+1]=strtrim(string(mome[j]),2)
endfor


for i = 0, n_Zeeman+n_AdditionalMatrices-1 do begin
  for j = 0, n-1 do begin
  OutPutarr[i+2,j+1]=strtrim(string(OperatorExpectationValues[i,j]),2)
  endfor
endfor
;
blank=strarr(20)
blank[0]=''
blank[1]=' '
blank[2]='  '
blank[3]='   '
blank[4]='    '
blank[5]='     '
blank[6]='      '
blank[7]='       '
blank[8]='        '
blank[9]='         '
blank[10]='          '
blank[11]='           '
blank[12]='            '
blank[13]='             '
blank[14]='              '
blank[15]='               '
blank[16]='                '
blank[17]='                 '
blank[18]='                  '
blank[19]='                   '
;
outputstrarr=strarr(n+1)
for j = 0, n-1 do begin
    for i = 0, n_Zeeman+n_AdditionalMatrices+1 do begin
        str=OutPutarr[i,j]
        length=strlen(str)
        outputstrarr[j]+=str+blank[20-length]
     endfor
endfor


widget_control,(*pstate).Output_text,set_value=outputstrarr


widget_control,(*pState).Eigenvalues_Type,get_value=Eigenvalues_Type
if Eigenvalues_Type eq 1 then begin
widget_control,(*pstate).EigvalueName_field,get_value=filename
    openw,lun,filename,/get_lun
    for i = 0, n do begin
    printf,lun,outputstrarr[i]
  endfor
    free_lun,lun,/force
endif


ENDIF ELSE BEGIN


OutPutarr=strarr(n+1)
OutPutarr[0]='Eigenvalues           -dE/dB'

for i = 0, n-1 do begin
OutPutarr[i+1]=strtrim(string(eigenvalues[i]),2)+'           '+strtrim(string(mome[i]),2)
endfor

widget_control,(*pstate).Output_text,set_value=OutPutarr

widget_control,(*pState).Eigenvalues_Type,get_value=Eigenvalues_Type
if Eigenvalues_Type eq 1 then begin
widget_control,(*pstate).EigvalueName_field,get_value=filename
    openw,lun,filename,/get_lun
    for i = 0, n do begin
    printf,lun,OutPutarr[i]
  endfor
    free_lun,lun,/force
endif


ENDELSE



widget_control,(*pState).Eigenvectors_Type,get_value=Eigenvectors_Type
if Eigenvectors_Type eq 1 then begin
widget_control,(*pstate).EigvectorName_field,get_value=filename
    openw,lun,filename,/get_lun
    for i = 0, n-1 do begin
    printf,lun,'Eigenvalue'
    printf,lun,eigenvalues[i]
    printf,lun,'Eigenvectors ( real, imaginary ) '
		for j=0,Matrix_Dimension-1 do begin
	    printf,lun,reform(eigenvectors[j,i])
		endfor
	endfor
    free_lun,lun,/force
endif

widget_control,(*pstate).CalculateButton,sensitive=1
return
end
'quit':    $
begin
ptr_free,pState
widget_control,event.top,/destroy
return
end
'BrowseEigenvalueFile':    $
begin
Source_Dir=(*pstate1).Source_Dir
filename=dialog_pickfile(path=Source_Dir,/read)
if filename eq '' then return
widget_control,(*pstate).EigvalueName_field,set_value=filename
end
'BrowseEigenvectorFile':    $
begin
Source_Dir=(*pstate1).Source_Dir
filename=dialog_pickfile(path=Source_Dir,/read)
if filename eq '' then return
widget_control,(*pstate).EigvectorName_field,set_value=filename
end
'EigenvalueType':    $
begin
	widget_control,(*pState).Eigenvalues_Type,get_value=Eigenvalues_Type
	if Eigenvalues_Type eq 0 then begin
	widget_control,(*pstate).Base_Col2_Row3,sensitive=0
	endif else begin
	widget_control,(*pstate).Base_Col2_Row3,sensitive=1
	endelse
end
'EigenvectorType':    $
begin
	widget_control,(*pState).Eigenvectors_Type,get_value=Eigenvectors_Type
	if Eigenvectors_Type eq 0 then begin
	widget_control,(*pstate).Base_Col3_Row3,sensitive=0
	endif else begin
	widget_control,(*pstate).Base_Col3_Row3,sensitive=1
	endelse
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Diagonalise,main_event
widget_control,main_event.top,get_uvalue = pState
;perform checks

fail=0

ConstructMatrices,main_event,fail
if fail eq 1 then return
conv=(*pstate).constants.conv
Matrix_Dimension=(*pstate).Matrix_Dimension
field=(*pstate).MagFieldTheoryValue
;*(*pstate).field=field
theta=(*pstate).Theta_sc
phi=(*pstate).phi_sc


geom = widget_info(main_event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50


tlb = widget_base(title='Calculate and Display Energies and Derivatives',/col,group_leader=main_event.top, $
       xoffset=xpos,yoffset=ypos,tlb_frame_attr = 3,/modal,/align_center)
;
;
Base_Row1=widget_base(tlb,/row,/align_center,/frame)
Base_Col1=widget_base(Base_Row1,/col,/align_center)

Base_Col1_Row1=widget_base(Base_Col1,/col,/align_center,/frame)
;
void = widget_label(Base_Col1_Row1,value = 'Input Variables')
;
;
Base_Col1_Row5=widget_base(Base_Col1_Row1,/row,/align_center)
Base_Col1_Row2=widget_base(Base_Col1_Row5,/row,/align_center)


MagField_field=cw_field(Base_Col1_Row2,/col,title='B (Tesla)',xsize=10, $
       value=field)

Theta_field=cw_field(Base_Col1_Row2,/col,title='Theta / Deg.',xsize=10, $
       value=strtrim(string(float(Theta)),2))

Phi_field=cw_field(Base_Col1_Row2,/col,title='Phi / Deg.',xsize=10, $
       value=strtrim(string(float(Phi)),2))


Base_Col1_Row4=widget_base(Base_Col1_Row5,/row,/align_center)

IF ((*pstate).MFTC_Pointers[0] eq 1) AND $
    (reform((*(*pState).ParameterInfoStruc).limits[(*pstate).MFTC_Pointers[1],0]) eq 1) AND $
    ((*pState).MFT_Treatment eq 2) THEN BEGIN
ENDIF ELSE BEGIN
widget_control,Base_Col1_Row4,sensitive = 0
ENDELSE
temperature_field=cw_field(Base_Col1_Row4,/col,title='Temperature / K',xsize=10, $
       value=strtrim(string(float((*pstate).RefineEnergyTemperature)),2))


Base_Col2_Row1=widget_base(Base_Col1,/col,/align_center,/frame)
;
void = widget_label(Base_Col2_Row1,value = 'Output Eigenvalues to File')

Base_Col2_Row2=widget_base(Base_Col2_Row1,/row,/align_center)


Eigenvalues_Type_Field = ['No','Yes']

Eigenvalues_Type = cw_bgroup(Base_Col2_Row2,Eigenvalues_Type_Field,/row, $
          /exclusive,set_value = 0,/return_index,/no_release,uname='EigenvalueType')

Base_Col2_Row3=widget_base(Base_Col2_Row2,/row,/align_center,sensitive=0)


EigvalueName_field=cw_field(Base_Col2_Row3,/row,title='',value=(*pstate).workdir+'Eigenvalues.out',xsize=40)

void = widget_button(Base_Col2_Row3,value = 'Browse', uname='BrowseEigenvalueFile')


Base_Col3_Row1=widget_base(Base_Col1,/col,/align_center,/frame)
;
void = widget_label(Base_Col3_Row1,value = 'Output Eigenvectors to File')

Base_Col3_Row2=widget_base(Base_Col3_Row1,/row,/align_center)


Eigenvectors_Type_Field = ['No','Yes']


Eigenvectors_Type = cw_bgroup(Base_Col3_Row2,Eigenvectors_Type_Field,/row, $
          /exclusive,set_value = 0,/return_index,/no_release,uname='EigenvectorType')

Base_Col3_Row3=widget_base(Base_Col3_Row2,/row,/align_center,sensitive=0)


EigvectorName_field=cw_field(Base_Col3_Row3,/row,title='',value=(*pstate).workdir+'Eigenvectors.out',xsize=40)

void = widget_button(Base_Col3_Row3,value = 'Browse', uname='BrowseEigenvectorFile')

Base_Col3_Row5=widget_base(Base_Col1,/row,/align_center,/frame)

void = widget_label(Base_Col3_Row5,value = '   Calculate and Display Expectation Values of the Operators?   ')


ExpectationValues_Type_Field = ['No','Yes']

ExpectationValue_Type = cw_bgroup(Base_Col3_Row5,ExpectationValues_Type_Field,/row, $
          /exclusive,set_value = 0,/return_index,/no_release,uname='ExpectationValueType')


courier_font = get_font_name(/large, /courier)

Info_text = widget_text(Base_Col1,value = '              Output Information',ysize=20, font = courier_font,/scroll)


;Base_Col2=widget_base(tlb,/col,/align_center,/frame)


Output_text = widget_text(Base_Row1,value = 'Eigenvalues           -dE/dB',xsize=35, font = courier_font,/scroll)


CalculateButton = widget_button(tlb,value = 'Calculate', uname='Calculate')
void = widget_button(tlb,value = 'Exit', uname='quit')

;
state={MagField_field:MagField_field, $
	   Theta_field:Theta_field, $
     Phi_field:Phi_field, $
     temperature_field:temperature_field, $
	   Base_Col2_Row3:Base_Col2_Row3, $
	   Base_Col3_Row3:Base_Col3_Row3, $
	   Eigenvalues_Type:Eigenvalues_Type, $
     Eigenvectors_Type:Eigenvectors_Type, $
     ExpectationValue_Type:ExpectationValue_Type, $
	   EigvalueName_field:EigvalueName_field, $
	   EigvectorName_field:EigvectorName_field, $
	   Info_text:Info_text, $
     Output_text:Output_text, $
     CalculateButton:CalculateButton, $
       main_event:main_event}

;
widget_control,tlb,/realize
;
pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
xmanager, 'Diagonalise',tlb,event_handler = 'Diagonalise_Events' ;register with the xmanager
;
;
;
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MP_CalculateINS,event
widget_control,event.top,get_uvalue = pState
Source_Dir=(*pstate).Source_Dir
cd,Source_Dir
tstart=systime(/seconds)
spawn,'ins mnmndimer.inp',result
help,result
print,result
print,'woof'
telapsed=systime(/seconds)-tstart
print,'Time Taken for INS Calculation = ',strtrim(string(telapsed),2),' seconds.'
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MP_Launch_Help,event
pdf_file = !DAVE_AUXILIARY_DIR+'\PSI\MagProp\MagPropUserManual.pdf'
void = launch_help(pdf_file,tlb = event.top)
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagProp_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)
widget_control,(*pstate).CalcButton,sensitive=1
widget_control,(*pstate).RefineButton,sensitive=1
return
endif


widget_control,event.top,get_uvalue = pState
uname=widget_info(event.id,/uname)


case uname of
'SampleType':   $
begin
SampleType,event
end
'MagProp_exit':   $
begin
MagProp_exit,event
end
;'Read_Experimental_Data':   $
;begin
;MagProp_Read_Experimental_Data,event
;end
;'Specify_Source_File':   $
;begin
;MagProp_Specify_Source_File,event
;end
;'Specify_Source_Dir':   $
;begin
;MagProp_Specify_Source_Directory,event
;end
'Remove_Parameter_From_Model':   $
begin
ParameterInfoUpdate,event,/DeleteEntry
end
'Specify_Model_Parameters':   $
begin
ParameterInfoUpdate,event,/UpdateEntry
end
'Display_Model_Parameters':   $
begin
ParameterInfoUpdate,event,/DisplayEntry
end
'Calculate_Curve':   $
begin
widget_control,(*pstate).CalcButton,sensitive=0
(*pState).chisq=-10.0
if (*pState).data eq 0 then begin
GetDefaultValues,event
endif
if (*pState).quantities[1] eq 'Moment' then begin
Calculate_MagCurve,event
endif else begin
Calculate_ChiCurve,event
endelse
widget_control,(*pstate).CalcButton,sensitive=1
end
'Refine_Data':   $
begin
(*pState).chisq=-10.0
if ((*pState).data eq 0) then begin
  if ((*pstate).Energy_Refine ne 1) then begin
  return 
  endif else begin
    if (n_elements(*(*pstate).InputEnergies) eq 0) then return
  endelse
endif
;
if (*pState).quantities[1] eq 'Moment' then begin
Refine_Data,event,/mome
endif else begin
Refine_Data,event,/chi
endelse
end
'MagProp_SaveSession':   $
begin
MagPropSaveSession,event
end
'MagProp_RestoreSession':   $
begin
MagPropRestoreSession,event
end
'DefaultQuantity':   $
begin
DefaultQuantity,event
end
'DerivativeCalcOption':   $
begin
DerivativeCalcOption,event
end
'SusPowderCalcMethod':   $
begin
SusPowderCalcMethod,event
end
'MagnetisationPowderCalcMethod':   $
begin
MagnetisationPowderCalcMethod,event
end
'Diamagnetism':   $
begin
Enter_Diamagnetism,event
end
'ModelScale':   $
begin
ModelScale,event
end
'MagProp_SaveAscii':   $
begin
MagProp_SaveAscii,event
end
'MagProp_ReadAscii':   $
begin
MagProp_ReadAscii,event
end
'MagProp_Save_jpeg':   $
begin
magprop_SaveImage,event,/jpeg
end
'MagProp_Save_gif':   $
begin
magprop_SaveImage,event,/gif
end
'MagProp_Save_tiff':   $
begin
magprop_SaveImage,event,/tiff
end
'MagProp_Save_ps':    $
begin
MagProp_Save_ps,event
end
'MagProp_Print_Image':    $
begin
MagProp_Print_Image,event
end
'RefinementOptions':    $
begin
RefinementOptions,event
end
'TempRange':    $
begin
TempRange,event
end
'ErrorBars':    $
begin
ErrorBars,event
end
'ChangeTitle':    $
begin
ChangeTitle,event
end
'DataScale':    $
begin
DataScale,event
end
'ImportSquidFile':    $
begin
ImportSquidFile,event
end
'ImportLigfieldFile':    $
begin
Read_Ligfield_File,event
end
'CursorPositionType':    $
begin
CursorPositionType,event
end
'ExperimentalQuantity':    $
begin
ExperimentalQuantity,event
end
'HamMatGen':    $
begin
HamMatGen,event
end
'MFT':    $
begin
MFT,event
end
'Diagonalise':    $
begin
Diagonalise,event
end
'Diagonalisation_Method':    $
begin
Diagonalisation_Method,event
end
'MP_Launch_Help':   $
begin
MP_Launch_Help,event
end
'MP_RefineEnergies':   $
begin
MP_RefineEnergies,event
end
'SetField':   $
begin
MP_SetField,event
end
'InputMatrices':   $
begin
MP_InputMatrices,event
end
'ChangeWorkingDirectory':   $
begin
ChangeWorkingDirectory,event
end
'MP_CalculateINS':   $
begin
MP_CalculateINS,event
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MagProp,group_leader = group_leader,notify_ids = notify_ids,  $
        register_name = register_name,workDir = workDir
device, get_decomposed = old_dc
device,decomposed = 0
loadCT,5,NColors=12,Bottom=1 ,/silent
if n_elements(register_name) eq 0 then register_name = 'MagProp'
if xregistered(register_name) then return
if n_elements(group_leader) eq 0 then group_leader = 0L

delim=path_Sep()
if not keyword_set(workDir) then workDir='c:'+delim

constants={beta:0.466860192,kb:0.695028718,conv:5584.897346}


tlb = widget_base(/col,title = 'MagProp',mbar=bar,group_leader = group_leader)

       filebuttons=widget_button(bar,value='File',/menu)
          void=widget_button(filebuttons,$
              value='Save Session',uname='MagProp_SaveSession')
          void=widget_button(filebuttons,$
              value='Restore Session',uname='MagProp_RestoreSession')
          void=widget_button(filebuttons,$
              value='Save as Ascii',uname='MagProp_SaveAscii')
          void=widget_button(filebuttons,$
              value='Read Ascii File',uname='MagProp_ReadAscii')
          void=widget_button(filebuttons,$
              value='Import SQUID File',uname='ImportSquidFile')
          void=widget_button(filebuttons,$
              value='Import Ligfield File',uname='ImportLigfieldFile')
          doneb=widget_button(filebuttons,$
              value='EXIT',uname='MagProp_exit')


       optionsbuttons=widget_button(bar,value='Program Options',/menu)
;          void=widget_button(optionsbuttons,$
;              value='Method to Calculate the Magnetic Moment',uname='MagMomentMethod')
          void=widget_button(optionsbuttons,$
              value='Change Local Working Directory',uname='ChangeWorkingDirectory')
          void=widget_button(optionsbuttons,$
              value='Sample Orientation',uname='SampleType')
          SetFieldButton=widget_button(optionsbuttons,$
              value='Set Magnetic Field',uname='SetField',sensitive=0)
          QuantityButton=widget_button(optionsbuttons,$
          value='Change Quantity',/menu)
          void=widget_button(QuantityButton,$
          value='Default Model Quantity',uname='DefaultQuantity')
          ExperimentalQuantityButton=widget_button(QuantityButton,$
          value='Change Experimental Quantity',uname='ExperimentalQuantity',sensitive=0)
          void=widget_button(optionsbuttons,$
              value='Calculation of Derivatives',uname='DerivativeCalcOption')
          PowderAverageButton=widget_button(optionsbuttons,$
              value='Powder Average Method',/menu)
           void=widget_button(PowderAverageButton,$
              value='Susceptibility and Derived Quantities',uname='SusPowderCalcMethod')
           void=widget_button(PowderAverageButton,$
              value='Magnetisation',uname='MagnetisationPowderCalcMethod')
           DiamagnetismButton=widget_button(optionsbuttons,$
              value='Diamagnetism',/menu)
           void=widget_button(DiamagnetismButton,$
              value='Include Diamagnetism Correction in Model',uname='Diamagnetism')
          RefinementOptionsButton=widget_button(optionsbuttons,$
              value='Refinement Options',uname='RefinementOptions')
          void=widget_button(optionsbuttons,$
              value='Change Title',uname='ChangeTitle')
          TemperatureRangeButton=widget_button(optionsbuttons,$
              value='Temperature Range for Fit',uname='TempRange',sensitive=0)
          ErrorBarButton=widget_button(optionsbuttons,$
              value='Enter Error Bars',uname='ErrorBars',sensitive=0)
          void=widget_button(optionsbuttons,$
              value='Model Scaling Factor',uname='ModelScale')
          void=widget_button(optionsbuttons,$
              value='Molecular Field Theory',uname='MFT')
          void=widget_button(optionsbuttons,$
              value='Diagonalisation Method',uname='Diagonalisation_Method')
          void=widget_button(optionsbuttons,$
              value='Calculate and Display Energies and Expectation Values',uname='Diagonalise')
          void=widget_button(optionsbuttons,$
              value='Refine on Energy Spectrum',uname='MP_RefineEnergies')
;          void=widget_button(optionsbuttons,$
;              value='Calculate INS Spectrum',uname='MP_CalculateINS')



         saveimagebuttons=widget_button(bar,value='Save Image',/menu)
          void=widget_button(saveimagebuttons,$
              value='Save jpeg',uname='MagProp_Save_jpeg')
          void=widget_button(saveimagebuttons,$
              value='Save gif',uname='MagProp_Save_gif')
          void=widget_button(saveimagebuttons,$
              value='Save tiff',uname='MagProp_Save_tiff')
          void=widget_button(saveimagebuttons,$
              value='Save PS',uname='MagProp_Save_ps')
       printbuttons=widget_button(bar,value='Print Image',/menu)
          void=widget_button(printbuttons,$
              value='Print',uname='MagProp_Print_Image')


         GenerateHamiltonianButtons=widget_button(bar,value='Generate Hamiltonian',/menu)
          void=widget_button(GenerateHamiltonianButtons,$
              value='Hamiltonian Matrix Generator',uname='HamMatGen')
          void=widget_button(GenerateHamiltonianButtons,$
              value='Input Matrix Files',uname='InputMatrices')

       helpbuttons=widget_button(bar,value='Help',/menu)
          void=widget_button(helpbuttons,$
              value='Display Help File',uname='MP_Launch_Help')



ExperimentalData_Base=widget_base(tlb,/col,/align_center)



FileName_Base=widget_base(ExperimentalData_Base,/row)

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

xsize = 700 & ysize =xsize/GoldenRatio

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

Graphical_Base_cola=widget_base(Graphical_Base,/col,/base_align_center)


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

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



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

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


CursorPosition_Field = ['Data','Model']

CursorPosition_Type = cw_bgroup(Graphical_Base_colb,CursorPosition_Field,/row, $
          /exclusive,set_value = 1,/return_index,/no_release,uname='CursorPositionType')



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

win = widget_draw(Graphical_Base,xsize = xsize,ysize = ysize,/button_events,/motion_events, $
      event_pro = 'MagProp_MouseEvents')


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

column_labels=['Designation','Matrix File','Type','Value','Error']
row_labels=strtrim(string(indgen(100)+1),2)

Parameter_Table_Input=strarr(5,100)

Parameter_Table=widget_table(Table_Base,column_widths=90,$
       column_labels=column_labels,row_labels=row_labels,xsize=5,ysize=100,$
       alignment=0,scr_ysize=218,value=Parameter_Table_Input)

ParameterInfo_Base_M=widget_base(Table_Base,/col,/align_center)

ParameterInfo_Base=widget_base(ParameterInfo_Base_M,/row,/align_center)

ParameterInfo_Base_col=widget_base(ParameterInfo_Base,/col,/align_center)

ParameterInfo_Base_col1=widget_base(ParameterInfo_Base_col,/col,/align_right,/frame)


Parameter_Droplist=widget_Droplist(ParameterInfo_Base_col1,value='',/dynamic_resize, $
       title='Parameter',uname='Display_Model_Parameters')


Parameter_Value=cw_field(ParameterInfo_Base_col1,/row,title='Value',xsize=10, $
       value='')


LowLimit_Value=cw_field(ParameterInfo_Base_col1,/row,title='Lower Limit',xsize=10, $
       value='')

UpperLimit_Value=cw_field(ParameterInfo_Base_col1,/row,title='Upper Limit',xsize=10, $
       value='')


void = widget_button(ParameterInfo_Base_col,value = 'Accept Changes', uname='Specify_Model_Parameters')


ParameterInfo_Base_col2=widget_base(ParameterInfo_Base,/col,/align_center)


Parameters_Fix_Field = ['Include','Fix Value','Set Lower Limit','Set Upper Limit']

Parameters_Fix_Value = cw_bgroup(ParameterInfo_Base_col2,Parameters_Fix_Field,/col, $
          /nonexclusive,set_value = [0,0,0,0],/return_index,/no_release,/frame)

ParameterInfo_Base_row1=widget_base(ParameterInfo_Base_col2,/row,/align_center)

void = widget_button(ParameterInfo_Base_row1,value = 'Remove from Model', uname='Remove_Parameter_From_Model')



CalcButton = widget_button(ParameterInfo_Base_M,value = 'Calculate Curve', uname='Calculate_Curve')

;ParameterInfo_Base_row2=widget_base(ParameterInfo_Base_M,/row)

;void = widget_button(ParameterInfo_Base_row2,value = 'Refine on Data', uname='Refine_Data')
RefineButton = widget_button(ParameterInfo_Base_M,value = 'Refine on Data', uname='Refine_Data')

;chi_sq=cw_field(ParameterInfo_Base_row2,/row,title='Chi^2',xsize=10, $
;       value=' ')

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], $
         autoscale:1, $
         xrange:[0.0,1.0], $
         yrange:[0.0,1.0]}

;DefaultValues
dv={DefQuant:0, $
    Tmin:2.0,    $
    Tmax:300.0,  $
    Tpoints:299,   $
    Bmin:10000.0,    $
    Bmax:50000.0,    $
    Bpoints:5}


state = {winState:winState, $
         Source_File:'', $
         Source_Dir:workDir, $
         Mouse_x:Mouse_x, $
         Mouse_y:Mouse_y, $
         x:ptr_new(/allocate_heap), $
         y_original:ptr_new(/allocate_heap),$
         y:ptr_new(/allocate_heap),$
         dy:ptr_new(/allocate_heap),$
         yt:ptr_new(/allocate_heap),$
         field:ptr_new(/allocate_heap),$
         temperature:ptr_new(/allocate_heap),$
         ZeemanMatrices:ptr_new(/allocate_heap),$
         AdditionalMatrices:ptr_new(/allocate_heap),$
         SpinMatrices:ptr_new(/allocate_heap),$
         ParameterInfoStruc:ptr_new(/allocate_heap),$
         delim:delim, $
         Parameter_Table:Parameter_Table, $
         Parameter_Table_Input:Parameter_Table_Input, $
         Parameter_Droplist:Parameter_Droplist, $
         MagFieldTheoryValue:0.1d, $
         Graphical_Base_colb:Graphical_Base_colb, $
         Parameter_Value:Parameter_Value, $
         LowLimit_Value:LowLimit_Value, $
         UpperLimit_Value:UpperLimit_Value, $
         Parameters_Fix_Value:Parameters_Fix_Value, $
         Quantities:['t','chit',''], $
         Data:0, $
         Zeeman_Pointers:ptr_new(/allocate_heap), $
         Zeeman_Matrix_Counter:intarr(3), $
         AddMat_Pointers:ptr_new(/allocate_heap),$
         Entries:ptr_new(/allocate_heap), $
         Type:ptr_new(/allocate_heap), $
         dHdB:ptr_new(/allocate_heap), $
         Refine_vals:ptr_new(/allocate_heap), $
         constants:constants, $
         DerivOption:0, $
         FieldWidth:0.01, $
         Sample_Type:0, $
         SusPowderMethod:0, $
         theta_start:0.0, $
         theta_end:90.0, $
         theta_nsteps:31, $
         phi_start:45.0, $
         phi_end:45.0, $
         phi_nsteps:1, $
         Theta_sc:0d, $
         Phi_sc:0d, $
         Diamagnetism:[0,0], $
         ModelScaleFactor:[0,0], $
         MFTC_Pointers:[0,0], $
         chisq:-10.0d, $
         Matrix_Dimension:0, $
         TempLims:[-1,-1], $
         TemperatureRangeButton:TemperatureRangeButton, $
         ErrorBarButton:ErrorBarButton, $
         MaxIterations:5, $
         Weighting:0, $
         title:'Magnetic Data', $
         DataScaleFactor:1.0, $
         dv:dv, $
         CalcButton:CalcButton, $
         RefineButton:RefineButton, $
         MatricesInMemory:ptr_new(/allocate_heap), $
         file:'', $
         old_dc:old_dc, $
         CursorPosition_Type:CursorPosition_Type, $
         CursorPosition:1, $
         ExperimentalQuantityButton:ExperimentalQuantityButton, $
         workdir:workdir, $
         register_name:register_name, $
         HamGenTlb:-1l, $
         MagWorkupTlb:-1l, $
         MFTC:0.0, $
         Jint:0.0, $
         PlotFullRange:byte(0), $
		 Algorithm_type:0, $
		 EigenvalueRange_type:0, $
		 EigenvalueTolerance_type:0, $
	 	 EigenvalueTolerance_Value:0d, $
	 	 EigenvalueRange_Value:ptr_new(''), $
     EigenvalueRange_Value_str:'', $
     MFT_Treatment:0, $
     MFT_Criterion:0.995, $
     Energy_Weights:1.0, $
     InputEnergies:ptr_new(''), $
     OutputEnergies:ptr_new(''), $
     Energy_Refine:0, $
     RefineEnergyTemperature:2.0, $
     ER_Field:0.0, $
     ER_Theta:0.0, $
     ER_Phi:0.0, $
     Magnetisation_Method:0, $
     SzMatrixName:'', $
     SxMatrixName:'', $
     SyMatrixName:'', $
     SetFieldButton:SetFieldButton}




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


xmanager,'MagProp',tlb,event_handler = 'MagProp_Events',cleanup= 'MagProp_cleanup'



end