#!/usr/bin/python

import numpy
from numpy.fft import fft
import Image, ImageDraw, ImageOps, sys

filename=sys.argv[1]

f=open(filename, "r")
data=f.readlines()
print str(len(data)) +" samples"
samplerate=data[0].split()[3]
print samplerate+"Hz => "+str(1/float(samplerate))+" seconds per sample"
print str(len(data)/float(samplerate))+"s"
lengthins=len(data)/float(samplerate)

length_to_process=100

fourierspersecond=24
fourierwidth=0.3
fourierspread=1.0/fourierspersecond

totaltransforms=round(length_to_process*fourierspersecond)
#totaltransforms=200
fourierspacing=round(fourierspread*float(samplerate))

fourierwidthindex=fourierwidth*float(samplerate)
print "For Fourier width of "+str(fourierwidth)+" need "+str(fourierwidthindex)+" samples each FFT"
print "Doing "+str(fourierspersecond)+" Fouriers per second"
print "Total " + str(totaltransforms*fourierspread)
print "Spacing: "+str(fourierspacing)
print "Total transforms "+str(totaltransforms)

lastpoint=round(length_to_process*float(samplerate)+fourierwidthindex)

fourierarray=numpy.zeros(fourierwidthindex)
time=numpy.zeros(lastpoint)
sound=numpy.zeros(lastpoint)

for line in range(2,lastpoint):
	row=data[line].split()
	time[line]=float(row[0])
	sound[line]=(float(row[2])+float(row[1]))/2
f.close

moviescanrange=100*24
moviewidth=400
movieheight=300
offset=round(moviewidth/2)

im=Image.new("RGB",(totaltransforms+offset,300))
imd=ImageDraw.Draw(im)

lowfrequency=30
highfrequency=1000

for position in range(0,totaltransforms):
	print "FFT: ",str(position).zfill(3)
	fourierarray=sound[((position*fourierspacing)):((position*fourierspacing)+(fourierwidthindex))]
	outfft=fft(fourierarray)
	#fout=open("frame_"+str(position).zfill(4)+".dat","w")
	for x in range(300):
		imd.point((position+offset,x),((255*((outfft[x].real)**2)/160),0,0))
	#	fout.write('%f %f\n'%(1.0*x/fourierwidth,(outfft[x].real)**2))
	#fout.close()



frame=Image.new("RGB",(moviewidth,movieheight))

linepos=(moviewidth/2)-fourierspersecond*fourierwidth

for xp in range(0,moviescanrange):
	print "Rendering frame "+str(xp).zfill(4)
	
	leftpart=im.crop((xp,0,xp+linepos,movieheight-1)).point(lambda i:i*0.4)
	rightpart=im.crop((xp+linepos,0,xp+moviewidth-1,movieheight-1))
	
	frame.paste(leftpart,(0,0))
	frame.paste(rightpart,(linepos,0))
	frame=ImageOps.flip(frame)
	
	framed=ImageDraw.Draw(frame)	
	framed.line([(linepos,0),(linepos,500)],fill=(0,255,0))
	frame.save("frame_"+str(xp).zfill(4)+".jpg")

