import tkFileDialog
from matplotlib.pyplot import *
from Tkinter import *
from Pmw import ComboBox
from numpy import *
from scipy import *
from math import *
from scipy import integrate
from scipy import interpolate
from scipy import stats
from scipy.optimize import curve_fit
import datetime


def fitfunction(x, a, b, c, d, e, f, g):
	#return (a+b*x+c*pow(x,2)+d*pow(x,3)+e*pow(x,4)+f*pow(x*5))*np.exp(-x*x)
        #return (a+b*x+c*x*x+d*x*x*x+e*x*x*x*x+f*x*x*x*x*x)*np.exp(-x*x)
        return (a+b*x+c*x*x+d*x*x*x+e*x*x*x*x+f*x*x*x*x*x)*np.exp(-g*x*x)
        #return a+b*np.exp(-c*x+d)


def loadoptvalue():
    
    global optvar
    
    try:
        f = open('optfile.dat')
        line = f.read()
        value = line.split()[0]
        optvar = int(value)
    except IOError as e:
        f = open('optifile.dat','w')
        f.write("0")
        f.flush()
        f.close()
        optvar = 0
        
def writeVar():
    global optvar
    
    if optvar == 0:
        optvar = 1
    else:
        optvar = 0
    
    f = open('optfile.dat', 'w')
    wline = "%d" % (optvar)
    f.write(wline)
    f.flush()
    f.close()

def vp_start_gui():
    global val, w, root, optvar
    root = Tk()
    root.title('Cheby')
       
    loadoptvalue()
    if(optvar == 0):
    
        new = Tk()
        new.title("Read me first")
        lbl = Label(new, text="Peak selection:  place a cursor on the maximum and press 'a' (to deselect press 'd').\n\nLimit selection:  place a cursor on the left-hand side limit and press 'w' (to deselect press 'r');\n\tright hand limit will be set automatically).\n ")
        lbl.grid(row=0, column=0)
    
        cbx = Checkbutton(new, text="Do not show again", variable=optvar, command=writeVar)
        cbx.grid(row=1, column=0)
           
    
    w = DexiusMaxiumus(root)
    root.mainloop()

"""
Variables
"""

optvar = 0
origx = 0.
origy = 0.
profx = []
profy = []
tempx = []
tempy = []
limity = 0.0
selectedPeaks = []
templatePeaksX = []
peakLimits = []
wavelength = 0.0
peakno = -1
peak = [0]
peakAreas = []
scaleHeight = 1000.
plotindex = 700
L = []
Ft = []
fcoef = []
points = 20
logfile = open("logfile.dat", "a")
datestring = str(datetime.datetime.now())
logfile.write("Program Started: " + datestring + "\n")


def mysin(angle):
	return sin(angle*2.*pi/360)

def mycos(angle):
	return cos(angle*2.*pi/360)
        
class DexiusMaxiumus:
			
		
    def exitProgram(self):
        global logfile
        datestring = str(datetime.datetime.now())
        logfile.write("Program ended: " + datestring + "\n\n\n")
        logfile.flush()
        logfile.close()
	sys.exit()

    def loadProfile(self):
        pass

        global profx
        global profy

        desiredFile = tkFileDialog.askopenfilename()
        #desiredFile = './MgO.dat'        
        if desiredFile != '':
            f = open(desiredFile, 'r')
            lines = f.readlines()
            f.close()

            profx = []
            profy = []

            for line in lines:
                profx.append(float(line.split()[0]))
                profy.append(float(line.split()[1]))

            location =  desiredFile.rfind("/")
            self.statusLabel.configure(text="Opened " + desiredFile[location+1:])
            figure(0)
            clf()
            plot(profx, profy)
            title("Sample Profile")
            xlabel("Angle")
            ylabel("Intesity")
            connect('key_press_event', self.selectPeaksKey)
            #connect('button_press_event', self.selectPeaksButton)
            show()

    def selectPeaksKey(self, event):

        global peakLimits
        global selectedPeaks
        
        if event.key == 'w':
            if len(selectedPeaks) > len(peakLimits):
                xlocation = event.xdata

                intlocation = 0
                diff = 100000000000.00

                for i in range(len(profx)):
                    if( abs(xlocation-profx[i]) < diff):
                        diff = abs(xlocation-profx[i])
                        intlocation = i

                peakLimits.append(intlocation)
                figure(0)
                clf()
                line = "Sample Profile, %d/%d peaks/limits selected" % (len(selectedPeaks), len(peakLimits))
                title(line)
                xlabel("Angle")
                ylabel("Intesity")
                plot(profx, profy)
                for i in range(len(selectedPeaks)):
                    scatter(profx[selectedPeaks[i]], profy[selectedPeaks[i]]+100, color='red')
                    text(profx[selectedPeaks[i]+100], profy[selectedPeaks[i]]+150, str(i+1), fontsize=14, color='black')
                for i in range(len(peakLimits)):
                    scatter(profx[peakLimits[i]], profy[peakLimits[i]], color='green')
                    other = abs(peakLimits[i] - selectedPeaks[i])
                    scatter(profx[peakLimits[i]+2*other], profy[peakLimits[i]], color='green')
                    
                self.enableTangentButton()
                self.enableRegressionButton()

        if event.key == 'r':
            peakLimits.pop()
            figure(0)
            clf()
            line = "Sample Profile, %d/%d peaks/limits selected" % (len(selectedPeaks), len(peakLimits))
            title(line)
            xlabel("Angle")
            ylabel("Intesity")
            plot(profx, profy)

            for i in range(len(selectedPeaks)):
                scatter(profx[selectedPeaks[i]], profy[selectedPeaks[i]]+100, color='red')
                text(profx[selectedPeaks[i]+100], profy[selectedPeaks[i]]+150, str(i+1), fontsize=14, color='black')
            
            for i in range(len(peakLimits)):
                scatter(profx[peakLimits[i]], profy[peakLimits[i]], color='green')
                other = abs(peakLimits[i] - selectedPeaks[i])
                scatter(profx[peakLimits[i]+2*other], profy[peakLimits[i]], color='green')
                
            self.enableTangentButton()
            self.enableRegressionButton()
        
        if event.key == 'a':
            xlocation = event.xdata

            intlocation = 0
            diff = 100000000000.00

            for i in range(len(profx)):
                if( abs(xlocation-profx[i]) < diff):
                    diff = abs(xlocation-profx[i])
                    intlocation = i
            max = -1000;
            maxint = 0
            for i in range(intlocation-20, intlocation+20):
                if profy[i] > max:
                    max = profy[i]
                    maxint = i

            selectedPeaks.append(maxint)
            figure(0)
            clf()
            line = "Sample Profile, %d/%d peaks/limits selected" % (len(selectedPeaks), len(peakLimits))
            title(line)
            xlabel("Angle")
            ylabel("Intesity")
            plot(profx, profy)
            for i in range(len(selectedPeaks)):
                scatter(profx[selectedPeaks[i]], profy[selectedPeaks[i]]+100, color='red')
		text(profx[selectedPeaks[i]+100], profy[selectedPeaks[i]]+150, str(i+1), fontsize=14, color='black')
				
            if(len(peakLimits) > 0):
                for i in range(len(peakLimits)):
                    scatter(profx[peakLimits[i]], profy[peakLimits[i]], color='green')
                    other = abs(peakLimits[i] - selectedPeaks[i])
                    scatter(profx[peakLimits[i]+2*other], profy[peakLimits[i]], color='green')

            self.statusLabel.configure(text = "%d peaks selected" % len(selectedPeaks))
            
            global peak
            peak = []
            for i in range(len(selectedPeaks)):
                peak.append(i+1)
            
            self.peakMenu._list.setlist(peak)
            
            self.enableTangentButton()
            self.enableRegressionButton()

        if event.key == 'd':
            selectedPeaks.pop()
            figure(0)
            clf()
            line = "Sample Profile, %d peaks selected" % len(selectedPeaks)
            title(line)
            xlabel("Angle")
            ylabel("Intesity")
            plot(profx, profy)
            for i in range(len(selectedPeaks)):
                scatter(profx[selectedPeaks[i]], profy[selectedPeaks[i]]+100, color='red')
                text(profx[selectedPeaks[i]+100], profy[selectedPeaks[i]]+150, str(i+1), fontsize=14, color='black')
                
            self.statusLabel.configure(text = "%d peaks selected" % len(selectedPeaks))
            
            if(len(peakLimits) > 0):
                for i in range(len(peakLimits)):
                    scatter(profx[peakLimits[i]], profy[peakLimits[i]], color='green')
                    other = abs(peakLimits[i] - selectedPeaks[i])
          
            #scatter(profx[peakLimits[i]+2*other], profy[peakLimits[i]], color='green')
            
            list = []
            
            for i in range(len(selectedPeaks)):
                list.append(i)
            
            self.enableTangentButton()
            self.enableRegressionButton()
                
        show()
        
    def enableTangentButton(self):
        
        if ( (len(selectedPeaks) > 0) and (len(selectedPeaks) == len(peakLimits)) and (len(templatePeaksX) > 0 )):
            self.tangentButton.configure(state=NORMAL)
        else:
            self.tangentButton.configure(state=DISABLED) 
    
    def enableRegressionButton(self):

        if( (len(selectedPeaks) > 1) and (len(selectedPeaks) == len(peakLimits)) and (len(templatePeaksX) > 0)):
            self.regressionButton.configure(state=NORMAL)
        else:
            self.regressionButton.configure(state=DISABLED)
    
    def selectPeaksButton(self, event):
        
        global selectedPeaks
        
        if event.button == 1:
            xlocation = event.xdata

            intlocation = 0
            diff = 100000000000.00

            for i in range(len(profx)):
                if( abs(xlocation-profx[i]) < diff):
                    diff = abs(xlocation-profx[i])
                    intlocation = i
            max = -1000;
            maxint = 0
            for i in range(intlocation-20, intlocation+20):
                if profy[i] > max:
                    max = profy[i]
                    maxint = i

            selectedPeaks.append(maxint)
            figure(0)
            clf()
            line = "Sample Profile, %d/%d peaks/limits selected" % (len(selectedPeaks), len(peakLimits))
            title(line)
            xlabel("Angle")
            ylabel("Intesity")
            plot(profx, profy)
            for i in range(len(selectedPeaks)):
                scatter(profx[selectedPeaks[i]], profy[selectedPeaks[i]]+100, color='red')
		text(profx[selectedPeaks[i]+100], profy[selectedPeaks[i]]+150, str(i+1), fontsize=14, color='black')
				
            if(len(peakLimits) > 0):
                for i in range(len(peakLimits)):
                    scatter(profx[peakLimits[i]], profy[peakLimits[i]], color='green')
                    other = abs(peakLimits[i] - selectedPeaks[i])
                    scatter(profx[peakLimits[i]+2*other], profy[peakLimits[i]], color='green')

            self.statusLabel.configure(text = "%d peaks selected" % len(selectedPeaks))
            
            global peak
            peak = []
            for i in range(len(selectedPeaks)):
                peak.append(i+1)
            
            self.peakMenu._list.setlist(peak)
            
            self.enableTangentButton()
            self.enableRegressionButton()

        if event.button == 3:
            selectedPeaks.pop()
            figure(0)
            clf()
            line = "Sample Profile, %d peaks selected" % len(selectedPeaks)
            title(line)
            xlabel("Angle")
            ylabel("Intesity")
            plot(profx, profy)
            for i in range(len(selectedPeaks)):
                scatter(profx[selectedPeaks[i]], profy[selectedPeaks[i]]+100, color='red')
                text(profx[selectedPeaks[i]+100], profy[selectedPeaks[i]]+150, str(i+1), fontsize=14, color='black')
                
            self.statusLabel.configure(text = "%d peaks selected" % len(selectedPeaks))
            
            if(len(peakLimits) > 0):
                for i in range(len(peakLimits)):
                    scatter(profx[peakLimits[i]], profy[peakLimits[i]], color='green')
                    other = abs(peakLimits[i] - selectedPeaks[i])
          
            #scatter(profx[peakLimits[i]+2*other], profy[peakLimits[i]], color='green')
            
            list = []
            
            for i in range(len(selectedPeaks)):
                list.append(i)
            
            self.enableTangentButton()
            self.enableRegressionButton()
                    
        show()
        
        

    def loadTemplate(self):
        global tempx, tempy, limity, selectedPeaks

        tempx = []
        tempy = []
        limity = []
        templatePeaks = []
        
        desiredFile = tkFileDialog.askopenfilename()
	#desiredFile = './Lab2.dat'        
	if desiredFile != '':
            f = open(desiredFile, 'r')
            lines = f.readlines()
            f.close()

            for line in lines:
                tempx.append(float(line.split()[0]))
                tempy.append(float(line.split()[1]))

            location =  desiredFile.rfind("/")
            self.statusLabel.configure(text="Opened " + desiredFile[location+1:])
            figure(1)
            clf()
            plot(tempx, tempy)
            xlabel("Angle")
            ylabel("Intensity")
            title("Instrumental Profile")
            connect('key_press_event', self.selectLimitAlt)
            show()
            
    def selectLimit(self, event):

        global limity

        limity = event.ydata
        figure(1)
        clf()
        xdot = [tempx[0], tempx[-1]]
        ydot = [event.ydata, event.ydata]
        plot(tempx, tempy)
        plot(xdot, ydot)
        self.selectTemplatePeaks()     
        xlabel("Angle")
        ylabel("Intensity")
        line = "Profile, %d peaks selected" % len(templatePeaksX)
        title(line)   
        self.enableRegressionButton()
        show()
        pass

    def selectLimitAlt(self, event):
        
        ### Here I am !!!

        global templatePeaksX

    
        if event.key == 'a':
            xlocation = event.xdata

            intlocation = -1

            diff = 100000000000.00

            for i in range(len(tempx)):
                if( abs(xlocation-tempx[i]) < diff):
                    diff = abs(xlocation-tempx[i])
                    intlocation = i
            
            max = -1000;
            maxint = -1

            for i in range(intlocation-20, intlocation+20):
                if tempy[i] > max:
                    max = tempy[i]
                    maxint = i
            
            templatePeaksX.append(maxint)
        
        if event.key == 'd':
            if(len(templatePeaksX) > 0):
                templatePeaksX.pop()


        figure(1)
        clf()
        plot(tempx, tempy)
        xlabel("Angle")
        ylabel("Intensity")
        line = "Profile, %d peaks selected" % len(templatePeaksX)
        title(line)   
        for i in range(len(templatePeaksX)):
            scatter(tempx[templatePeaksX[i]], tempy[templatePeaksX[i]]+10, color='RED')
        self.enableRegressionButton()
        self.enableTangentButton()
        show()


        pass
    
    def selectTemplatePeaks(self):
       
        global templatePeaksX

        templatePeaksX = []
        
        for i in range(5,len(tempx)-5):
            
            if( (tempy[i] > limity) and (tempy[i] > tempy[i-1] and tempy[i] > tempy[i-2] and tempy[i] > tempy[i-3] and tempy[i] > tempy[i-4] and tempy[i] > tempy[i-5] and tempy[i] > tempy[i+1] and tempy[i] > tempy[i+2] and tempy[i] > tempy[i+3] and tempy[i] > tempy[i+4] and tempy[i] > tempy[i+5]) ):
                templatePeaksX.append(i)
                
        for i in range(len(templatePeaksX)):
            scatter(tempx[templatePeaksX[i]], tempy[templatePeaksX[i]]+10, color='RED')
        
        self.enableTangentButton()
            
    def selectWl(self, var):
        
        global wavelength
        
        if (var == "Other"):
            self.wlEntry.configure(state=NORMAL)
        else:
            wavelength = float(var.split()[0])

    def makeLine(self, event):

        global tempx
	global tempy
        global L
        global Ft
        global logfile
                
        clf()
        
        xline = [0., max(L)]
        yline = [0., 0.]

	x = []
	y = []
	
	x.append(origx)
	y.append(origy)
	x.append(event.xdata)
	y.append(event.ydata)
	
	plot(L, Ft)
	scatter(L, Ft)
	#scatter(x, y)
	plot(x, y)
        plot(xline, yline, color='red')
        
        gradient, intercept, r_value, p_value, std_err = stats.linregress(x, y)
        xcross = -1.0*intercept/gradient
        scatter(xcross, 0, color='black')
	titleLine = "<La>: %.0lf A" % (xcross)
        title(str(titleLine))
        peakno = int(self.peakMenu.get()) - 1
        anglePeak = profx[selectedPeaks[peakno]]
        logline = "Peak %d (%.0lf) <La>: %.0lf A\n" % (peakno+1, anglePeak, xcross)
        logfile.write( logline )
        
        xlabel("L/A")
        ylabel("|F(L)|")
        show()
	pass

    def calcTangent(self):
        
	global peakno
        global tempx
        global tempy
        global plotindex
        global L
        global Ft
                
        peakno = int(self.peakMenu.get()) - 1
        anglePeak = profx[selectedPeaks[peakno]]

        mindiff = 11111110.0

        selectedpeak = 0
        
        if len(templatePeaksX) > 1:
            for i in range(len(templatePeaksX)):
                diff = abs(anglePeak - tempx[templatePeaksX[i]])
                if (diff < mindiff):
                    mindiff = diff
                    selectedpeak = i

        templPeak = 0
        templPeak = tempx[templatePeaksX[selectedpeak]]

        other = selectedPeaks[peakno]-peakLimits[peakno]
        ipx = profx[selectedPeaks[peakno]-other:selectedPeaks[peakno]+other]
        ipy = profy[selectedPeaks[peakno]-other:selectedPeaks[peakno]+other]
        itx = profx[selectedPeaks[peakno]-other:selectedPeaks[peakno]+other]
        ity = tempy[templatePeaksX[selectedpeak]-other:templatePeaksX[selectedpeak]+other]

        maxp = max(ipy)
        maxt = max(ity)

        for i in range(len(ipy)):
            ipy[i] /= maxp
            ipy[i] *= scaleHeight

        for i in range(len(ity)):
            ity[i] /= maxt
            ity[i] *= scaleHeight
            
        fipy = fft(ipy) 
        fity = fft(ity)
    
        fre = []
        fim = []

        for i in range(len(fipy)):
            h = fipy[i]
            g = fity[i]

            nazivnik = g.real*g.real + g.imag*g.imag
            fre.append( (h.real*g.real+h.imag*g.imag)/nazivnik )
            fim.append( (h.imag*g.real-h.real*g.imag)/nazivnik )

        f = []                          # Koeficijenti dekonvoluiranog profila
        
        for i in range(len(fre)):
            f.append(complex(fre[i], 0.0))
        
        fcoef = []    
        fcoef.append(f)
        
        new = fre[:points]
        tx = array(range(len(new)))
        ty = array(new)
        
        pop, pope = curve_fit(fitfunction, tx, ty)
        ttempx = range(len(new))
        ttempy = []                     # Fitani koeficijenti dekonvoluiranog profila
        
        for xval in ttempx:
            ttempy.append((pop[0]+pop[1]*xval+pop[2]*xval*xval+pop[3]*xval*xval*xval+pop[4]*xval*xval*xval*xval+pop[5]*xval*xval*xval*xval*xval)*np.exp(-pop[6]*xval*xval))   
        
        
           
        tempy2 = []
        for i in range(len(ttempy)):
            tempy2.append(ttempy[i])
        for i in range(len(ttempy)-1):
            tempy2.append(ttempy[len(ttempy)-1-i])

        new2 = ifft(tempy2)             # Dekonvoluirani profil
        g2 = []

        
        for i in range(len(new2)/2):    # Zrcaljen dekonvoluirani profil
            g2.append(new2[i])
        
        for i in range(len(new2)/2, len(new2)):
            g2.append(new2[i])
	        
        localX = []
        xmin = profx[peakLimits[peakno]]
        other = abs(peakLimits[peakno]-selectedPeaks[peakno])
        xmax = profx[peakLimits[peakno]+2*other]
        steps = len(g2)
        xstep = (xmax - xmin) / (steps - 1)
        for i in range(steps):
            localX.append(xmin+i*xstep)
        
        maxy = max(g2)
        
        for i in range(len(g2)):
            g2[i] /= maxy
            g2[i] *= scaleHeight

	L = []
	Ft = []
        
	maxPeak = profx[selectedPeaks[peakno]+other]

	for i in range(points):
		naz = 4.*(mysin(maxPeak/2.)-mysin(anglePeak/2.))
		br = i*wavelength
		L.append(br/naz)
                Ft.append(abs(ttempy[i]))               # Fitane vrijednosti koeficijenata

        global origx
        global origy
        
	origx = L[0]
	origy = Ft[0]

	figure()
	plot(L, Ft)
	scatter(L, Ft)
	xlabel("L/A")
	ylabel("|F(L)|")
	title("Click button to make tangent")
	connect('button_press_event', self.makeLine)
	show()

    def calcForOnePeak(self, peakloc):
        
        global fcoef
	global tempx
	global tempy
        global points
        
        anglePeak = profx[selectedPeaks[peakloc]]

        mindiff = 11111110.0

        selectedpeak = 0
        
        if len(templatePeaksX) > 1:
            for i in range(len(templatePeaksX)-1):
                diff = abs(anglePeak - tempx[templatePeaksX[i]])
                if (diff < mindiff):
                    mindiff = diff
                    selectedpeak = i
        else:
            selectedpeak = 0

        templPeak = tempx[templatePeaksX[selectedpeak]]

        other = selectedPeaks[peakloc]-peakLimits[peakloc]
        ipx = profx[selectedPeaks[peakloc]-other:selectedPeaks[peakloc]+other]
        ipy = profy[selectedPeaks[peakloc]-other:selectedPeaks[peakloc]+other]
        itx = profx[selectedPeaks[peakloc]-other:selectedPeaks[peakloc]+other]
        ity = tempy[templatePeaksX[selectedpeak]-other:templatePeaksX[selectedpeak]+other]
            
        maxp = max(ipy)
        maxt = max(ity)

        for i in range(len(ipy)):
            ipy[i] /= maxp
            ipy[i] *= scaleHeight

        for i in range(len(ity)):
            ity[i] /= maxt
            ity[i] *= scaleHeight

        fipy = fft(ipy)
        fity = fft(ity)

        fre = []
        fim = []

        for i in range(len(fipy)):
            h = fipy[i]
            g = fity[i]

            nazivnik = g.real*g.real + g.imag*g.imag
            fre.append( (h.real*g.real+h.imag*g.imag)/nazivnik )
            fim.append( (h.imag*g.real-h.real*g.imag)/nazivnik )

        f = []
        for i in range(len(fre)):
            f.append(complex(fre[i], 0.0))
    
        new = fre[:points]
        tx = array(range(len(new)))
        ty = array(new)
        
        pop, pope = curve_fit(fitfunction, tx, ty)
        ttempx = range(len(new))
        ttempy = []
        
        for xval in ttempx:
            ttempy.append((pop[0]+pop[1]*xval+pop[2]*xval*xval+pop[3]*xval*xval*xval+pop[4]*xval*xval*xval*xval+pop[5]*xval*xval*xval*xval*xval)*np.exp(-pop[6]*xval*xval))       
    
        tempy2 = []
        for i in range(len(ttempy)):
            tempy2.append(ttempy[i])
        for i in range(len(ttempy)-1):
            tempy2.append(ttempy[len(ttempy)-1-i])
    
        new2 = ifft(tempy2)

        g2 = []

        for i in range(len(new2)/2, len(new2)):
            g2.append(new2[i])

        for i in range(len(new2)/2):
            g2.append(new2[i])


        localX = []
        xmin = profx[peakLimits[peakloc]]
        other = abs(peakLimits[peakloc]-selectedPeaks[peakloc])
        xmax = profx[peakLimits[peakloc]+2*other]
        steps = len(g2)
        xstep = (xmax - xmin) / (steps - 1)
        for i in range(steps):
            localX.append(xmin+i*xstep)
            localX[i] = localX[i] - (0.07) # REMOVE THIS LATER


        maxy = max(g2)
        for i in range(len(g2)):
            g2[i] /= maxy
            g2[i] *= scaleHeight
	
        return abs(integrate.trapz(g2, localX))

    def doRegression(self):
        
        global peakAreas
        global logfile
        
        peakAreas = []
        
        for i in range(len(selectedPeaks)):
            peakAreas.append(self.calcForOnePeak(i))
        
        mx = []
        my = []

	for i in range(len(selectedPeaks)):
		gamma = peakAreas[i]*mycos(profx[selectedPeaks[i]])/scaleHeight
		sinus = pow(mysin(profx[selectedPeaks[i]]), 2)
		
		yval = pow(gamma,2)/sinus
		xval = gamma/sinus
		#print xval, yval

		mx.append(xval)
		my.append(yval)

	retvalues = stats.linregress(mx, my)

	figure()
	
	scatter(mx,my)

	lrx = [min(mx), max(mx)]
	lry = []
	
	for i in range(len(lrx)):
		lry.append(retvalues[0]*lrx[i]+retvalues[1])

	plot(lrx, lry, color='red')
	#scatter(lrx, lry, color='red')
	#xlabel("gamma/(sin(theta0)^2")
        # r'$\lambda = 3737 \AA$'
        
        xlabel(r'$\gamma$ / sin$\theta^2_0$', size=16)
	ylabel(r'$\gamma^2$ / sin$\theta^2_0$', size=16)
	titleline = ""
	lam = wavelength
	Lv = 1.
	C = 1.
	if (retvalues[1] > 0):
		Lv = lam / retvalues[0]
                Lv = Lv * 180. / 3.1415
                
		C = sqrt(retvalues[1])/4.
                
		titleline = "<Lv> = %.0f A, e = %.0lf " % (Lv, C)
                logfile.write("WH: " + titleline + "\n")
	else:
		Lv = lam / retvalues[0]
                Lv = Lv * 180. / 3.1415
                errLv = retvalues[-1] * lam / retvalues[0]**2
		
		titleline = "<Lv> = %.0lf A, e = 0" % (Lv)
                logfile.write("WH: " + titleline + "\n")
		
        
        title(titleline)
        show()        



    def mc(self):
	self.peakMenu.set()

    def __init__(self, root):
        
        global wavelength 
        
        self.wlVar = StringVar()
        self.peakVar = StringVar()
                
        Label(root, text="Open profiles:", justify=RIGHT).grid(row=0,column=0, padx=10, pady=10)
        self.openButton = Button(root, text="Sample", command=self.loadProfile)
        self.openButton.grid(row=0, column=1)
        self.profButton = Button(root, text="Instrumental", command=self.loadTemplate).grid(row=0, column=2)
        self.statusLabel = Label(root)
        self.statusLabel.configure(text="Program started", justify=CENTER)
        self.statusLabel.grid(row=1, column=0, columnspan=3, pady=10)
        Label(root, text="Select wl (A):", justify=RIGHT).grid(row=2, column=0)
        self.optionMenu = OptionMenu(root, self.wlVar, "1.5406 (Cu)", "0.7093 (Mo)", "Other", command=self.selectWl)
        self.wlVar.set("1.5406 (Cu)")
        wavelength = 1.5406
        self.optionMenu.grid(row=2, column=1)
        self.wlEntry = Entry(root,state=DISABLED)
        self.wlEntry.grid(row=2, column=2)
        self.regressionButton = Button(root, text="Williamson-Hall plot", state=DISABLED, justify=CENTER, command=self.doRegression)
        self.regressionButton.grid(row=3, column=0, pady=10)
        Label(root, text="Select peak:", justify=RIGHT).grid(row=4, column=1)
        self.peakMenu = ComboBox(root, scrolledlist_items=peak, entry_width=2)
        self.peakMenu.grid(row=4, column=2)
        self.tangentButton = Button(root, text="Warren-Averbach-Bertaut", state=DISABLED, command=self.calcTangent)
        self.tangentButton.grid(row=4, column=0)
        self.exitButton = Button(root, text="Exit", command=self.exitProgram).grid(row=5, column=1, pady=20)
        

if __name__ == '__main__':
    vp_start_gui()
