#!/usr/bin/env python

#foolswood.co.uk 2011
#License: GPLv3
#Written for Python 2.x

#reads csv export data files from tracerdaq

def header(lines):
	'''Read tracerdaq header data
	
	Returns a dict containing:
	return_value['samples'] = the number of samples
	return_value['rate'] = the sample rate (in Hz)'''
	hdata = {}
	line = lines[0]
	while not line.__contains__(','):
		parts = line.split(':')
		if parts[0] == 'Sampling Rate':
			hdata['rate'] = int(parts[1])
		elif parts[0] == 'Sample Count':
			hdata['samples'] = int(parts[1])
		del lines[0]
		line = lines[0]
	return hdata

def samples(lines):
	'''Read the data section
	
	outputs a dict
	return_val[ch0] = data from channel 0 in a list
	etc.'''
	line = lines[0]
	line = line.split(',')
	collect = []
	for c in range(len(line)):
		ch = line[c]
		if ch[:7] == 'CHANNEL':
			collect.append(c)
	del lines[0]
	cno = 0
	data = {}
	line = lines[0].split(',')
	for c in collect:
		data['ch'+str(cno)] = []
		cno = cno + 1
	for line in lines:
		if len(line) != 0:
			line = line.split(',')
			cno = 0
			for c in collect:
				data['ch'+str(cno)].append(float(line[c]))
				cno = cno + 1
	return data

def load(fpath):
	'''load a tracerdaq csv file
	
	takes the file path as an argument and returns a tuple of the form:
	(header, data) whose forms are the return values of header and samples respectively'''
	f = open(fpath, 'r')
	lines = f.read().split('\n')
	h = header(lines)
	d = samples(lines)
	h['channels'] = len(d)
	return (h, d)
