#This code actually frickin' works! 
#It's a butchered version of Neil's step.py that moves an image of a Muybridge elephant around the screen.
#!/usr/bin/python
import clutter
import serial

#Buncha variables

sfilter = 0.9
sxoffset = 0
sxscale = 1
syoffset = 0
syscale = 1
index = 0
step = []
step_filt = []
eps = float(sfilter)
print "variables loaded"

#define what it means to read the serial port
port = "/dev/ttyUSB0"
ser = serial.Serial(port,9600)
ser.setDTR()
ser.flush()

print "port set up"

stage = clutter.Stage()
stage.set_size(1024, 600)
stage.set_title("Elephant")
stage.set_color(clutter.color_from_string("black"))
timeline = clutter.Timeline(400)
timeline.set_loop(True)

print "timeline and stage initialized"

#Load the elephant
elephant = clutter.Texture(filename="elephant.gif")

#Show the whole image
(width, height) = elephant.get_size()

print "beginning elephant placement loop"

#Place the elephant 
def place_elephant (timeline, dt):
   global index, channel, baseline, path, path_filt, step, step_filt, saveflag
   #
   # idle routine
   #

   lo_dn = ord(ser.read())
   hi_dn = ord(ser.read())
   lo_up = ord(ser.read())
   hi_up = ord(ser.read())
   if ((lo_dn == 1) & (hi_dn == 2) & (lo_up == 3) & (hi_up == 4)):
      if (step_filt == []):
         step_filt = step
         print "reset step-filt"
      else:
         for i in range(len(step_filt)):
            step_filt[i] = (1-eps)*step_filt[i] + eps*step[i]
            #y = ("%.0f"%step_filt[0])
            y = int(step_filt[0]/2)
            print y
            x = 100
            elephant.set_position(x,y)
            print "set elephant position"
      index = 0
      step = []
   else:
      value_up = 256*hi_up + lo_up
      value_dn = 256*hi_dn + lo_dn
      value = (value_up + (1023-value_dn))/2.0
      index += 2
      step.insert(0,value)
#      print "figured out value"


#Bring the elephant on stage
stage.add(elephant)

print "finding framing ..."
byte2 = 0
byte3 = 0
byte4 = 0
while 1:
   byte1 = byte2
   byte2 = byte3
   byte3 = byte4
   byte4 = ord(ser.read())
   if ((byte1 == 1) & (byte2 == 2) & (byte3 == 3) & (byte4 == 4)):
      print "start plotting"
      break

#Call the elephant over
timeline.connect("new-frame", place_elephant)

#Show everything
stage.show_all()

#Time begins
timeline.start()

#Quit properly
stage.connect('destroy', clutter.main_quit)
clutter.main()



