import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Button
from decimal import Decimal
import time
import string
import subprocess

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    pullData = open("SpectrometerData1"+".dat","r").read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []
    cnt = 0
    for eachLine in dataArray:
        cnt = cnt +1
        if len(eachLine) > 1 and cnt > 2:
            
            if string.find(eachLine, "$") == -1 and len(eachLine.split(',')) == 2:
                #print eachLine
                x,y = eachLine.split(',')
                if x.isdigit() and string.find(y[1:0], " ") and len(y.split('.')) == 2:#and len(lh) > 0 and lh[0].isdigit() and lh[1].isdigit():
                    yar.append(1024-int(x))
                    xar.append(Decimal(y))
            elif string.find(eachLine, "$") != -1:
                xar = []
                yar = []
    ax1.clear()
    ax1.plot(xar,yar)
    

class Index:
    ind = 0
    def next(self, event):
        subprocess.Popen("Write Data.py", shell=True)
        ani = animation.FuncAnimation(fig, animate, interval=100)

callback = Index()
axnext = plt.axes([0, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'ReScan')
bnext.on_clicked(callback.next)
ani = animation.FuncAnimation(fig, animate, interval=100)
plt.show()

