# watch_movie.py  -- a file which loads a text file in which states
# have been stored and plays the states back one by one like a movie

from Wrapped2DArray import *
import pygame
import pygame.surfarray as surfarray


def load( fname , arraysize):
	f = open(fname)
	numLines=0

	for line in f:
		numLines +=1
	f.close()

#	print numLines

	arrList = []
	shaper = (arraysize,arraysize)

	f = open(fname)

	line = f.readline()
#	h = 0
	for i in range(0,int(numLines/arraysize)):
		arr = zeros(shaper,float)
		k = 0
		for j in range(0,arraysize):
			arr[k,j] = float( line.split()[j] )
		k+=1
		for line in f:
#	                print h
#	                h+=1

			if k<arraysize:
				for j in range(0,arraysize):
#					print "i", i
#					print "k", k
					arr[k,j] = float( line.split()[j] )
				k+=1
			else:
				break
		arrList.append(arr)

	f.close()
	return arrList, int(numLines/arraysize)



        # Spatial configuration display
def SpDisplayState(state,nSites,surface,CellSize):
        ConfigRect = pygame.Rect(0,0,nSites*CellSize,nSites*CellSize)
        surface.fill( (0,0,255) ,ConfigRect)

        for i in xrange(nSites):
                for j in xrange(nSites):
                        fc = int((1-state[i,j])*255)    # grayscale based on state value
                        if fc>255:              # make sure we're within bounds of RGB vals
                                fc = 255
                        if fc<0:
                                fc = 0
                        fill_Color = fc,fc,fc
                        surface.fill(fill_Color,[i*CellSize,j*CellSize,CellSize,CellSize])


##### Done with definitions########

fname = raw_input("Please enter a file name to load movie from: ")
arraysize = int( raw_input("Please enter arraysize (aka nSites) for this movie: ") )

arrList, num_frames = load(fname,arraysize)

CellSize = 16 

#Set up display
size = CellSize*arraysize

pygame.init()

OffColor = 0, 0, 255
	# Get display surface
screen = pygame.display.set_mode( (size,size) )
pygame.display.set_caption('2D Cellular Automaton Movie')
	# Clear display
pygame.display.flip()
	# Create RGB array whose elements refer to screen pixels
	# Strangeness: sptmdiag is no longer used, but if this line
	# is removed, then display updates slow down considerably!
sptmdiag = surfarray.pixels3d(screen)

#display 
t = 0
state = zeros((arraysize,arraysize),float)
#print num_frames
while t < num_frames:
#	print t
	for event in pygame.event.get():
		if event.type == pygame.QUIT: sys.exit()
	
	for i in range(0, arraysize):
		for j in range(0,arraysize):
			state[i][j] = arrList[t][i][j]

	# Display state
	SpDisplayState(state,arraysize,screen,CellSize)
	pygame.display.flip()

	t+=1



