#! /usr/bin/env python
#
# Requires the filename format for images to be:
# IMG-%Y%m%d-%H%M%S-%i-%f-%I
# 
# Also requires pylab and matplotlib.  

import sys
import os
import time
import code
from numpy import *
from time import strftime
from pylab import *

arg = sys.argv[1]
print "Searching for files in directory ", arg
if len(sys.argv) > 2:
	start = int(sys.argv[2])
	print "Skipping first ", start, " samples"
	if len(sys.argv) > 3:
		sampleLen = int(sys.argv[3])
		print "Using only ", sampleLen, " samples"
	else:
		sampleLen = 0
else:
	start = 0
	sampleLen = 0

files = os.listdir(arg)
#print files

time_secs = [0 for i in range(len(files))]
time_usecs = [0 for i in range(len(files))]
idx = 0
for file in files:
	components = file.split('-')
	timestr = components[1] + components[2]
	timeVal = time.strptime(timestr, "%Y%m%d%H%M%S")
	timestamp = time.mktime(timeVal) 
        microsecs = int(components[3])*1e-6
	#microsecs = 0;

	time_secs[idx] = timestamp
	time_usecs[idx] = microsecs
	idx+= 1

	#print "----------------------------"
	#print components
	#print timestr
	#str = strftime("%a, %d %b %Y %H:%M:%S", timeVal)
	#print str
	#print timestamp, ".", microsecs

timestamp = array(time_secs)
usecs = array(time_usecs)
timestamp = timestamp - min(timestamp)
timestamp += usecs

framerate = 1/diff(sort(timestamp))
if sampleLen > 0:
	framerate = framerate[start:start+sampleLen]
else:
	framerate = framerate[start:]

print "Mean: ", mean(framerate)
print "Min:  ", min(framerate)
print "Max:  ", max(framerate)
print "Std:  ", std(framerate)

subplot(121)
hist(framerate)
title('Histogram of framerate values')
xlabel('Framerate (FPS)')
#axis([min(framerate[start:]),max(framerate[start:]),0,len(framerate)])
#axis([16, 16.1, 0, len(framerate)])
axis([24,25,0,len(framerate)])

subplot(122)
plot(framerate)
title('Framerate over time')
xlabel('Frame')
ylabel('Framerate (FPS)')
axis([0, len(framerate), 24, 25])

#timestampLIST = timestamp.tolist()
#for i in range(len(time_secs)):
#	print time_secs[i], '|', time_usecs[i], '||', timestampLIST[i]

#code.interact(local=locals())
show()
