#!/bin/env /usr/bin/python

# merge/average - combines many test run data files, concatenated into
# one big "infile" into a single "outfile" with every data at a single
# frequency averaged together. That is, this builds a list of all unique
# frequencies, then sweeps thru the infile for each frequency, adds them
# up and divides by the number of occurances, and writes the average out.
# Use unix "sort -n outfile > sorted_outfile" if you need frequencies to
# be in order.

import sys, os

def main (args):

        nargs = len (args)

	if nargs <> 2:
	   print "Usage: ./merge_average_3.py infile outfile\n"
	   sys.exit()

        output_file = (args[nargs-1])

	if os.access(output_file, os.F_OK):
	   print "Output file exists\n"
	   sys.exit()

	# line field seperator, space
	sep = ' '

	freq_list = []
	# make a list of uniq freqs
	fh = open(args[0],"r")
	in_line = fh.readline()
	while in_line <> '':
	   field = in_line[0:in_line.find(sep)]
	   match = False
	   for i in range(0,len(freq_list)):
	      if field == freq_list[i]:
	         match = True
	         break
	   if match == False:
	      freq_list.append(field)
	   in_line = fh.readline()


	# open output file for writing
	out_fh = open(output_file,"w")

	for i in range(0,len(freq_list)):
	   fh.seek(0)
	   count = 0. # number of hits 
	   out_mag = 0. # accumulators
	   out_phase = 0.
	   out_sphase = 0.
	   in_line = fh.readline()
	   while in_line <> '':
	      field = in_line[0:in_line.find(sep)]
	      if field == freq_list[i] : # freqs match, every one at least once
	         count += 1.
	         in_freq = float(field)
	         in_line = in_line[len(field)+1:len(in_line)]
	         field = in_line[0:in_line.find(sep)]
	         in_mag = float(field)
	         in_line = in_line[len(field)+1:len(in_line)]
	         field = in_line[0:in_line.find(sep)]
	         in_phase = float(field)
	         in_line = in_line[len(field)+1:len(in_line)]
	         in_sphase = float(in_line)
	         out_mag += in_mag 
	         out_phase += in_phase
	         out_sphase += in_sphase
	      in_line = fh.readline()
	   out_fh.write(str(in_freq)+' '+str(out_mag/count)+' '+str(out_phase/count)+' '+str(out_sphase/count)+'\n')

	fh.close()
	out_fh.close()

if __name__ == '__main__':
        main (sys.argv[1:])

