# FlockingGetPositions.py

# Define the Function GetPositions(filename) to extract the data in a textfile generated by one of 
# the simulator programs in a useable form.
from numpy import *

# The Function GetPositions
def GetPositions(filename):
    
    # open the data file
    f = open(filename)

    # Determine the num_timesteps, and number of birds in the Flock N
    num_timesteps = 0.0

    for line in f:
        num_timesteps = num_timesteps + 1.0
        if num_timesteps == 1.0:
           l = line[:-1]
           ll = l.split()
           N = len(ll)

    num_timesteps = num_timesteps/2.0     #since x and y data written to seperate lines
    num_timesteps = int(num_timesteps)

    file.close(f)


    # Create initial empty lists for the positions of the CM of flock as a function of time
    # Create initial empty lists of lists for the positions of each bird in the flock as a function of time
    flock_positions_x = []
    flock_positions_y = [] 
    bird_positions_x = []
    bird_positions_y = []

    for n in xrange(N):
       bird_positions_x.append([])
       bird_positions_y.append([])
    

    # loop through the file and add the data to these lists
    f = open(filename)
    linenumber = 0.0

    for line in f:
        linenumber = linenumber + 1.0
     
    # convert the string data into useable list form of floating point numbers, L
        l = line[:-1]
        ll = l.split()
        L = []
        for i in xrange(N):
            L.append(float(ll[i]))

        # compute CM value 
        CMvalue = average(L)

        # add to appropriate lists (x or y)
        if mod(linenumber,2) == 1.0:            
           flock_positions_x.append(CMvalue)
           for n in xrange(N):
               bird_positions_x[n].append(L[n])
     
        if mod(linenumber,2) == 0.0:           
          flock_positions_y.append(CMvalue)
          for n in xrange(N):
              bird_positions_y[n].append(L[n])

    file.close(f)
    return (flock_positions_x, flock_positions_y, bird_positions_x, bird_positions_y, N, num_timesteps)
