#! /usr/bin/env python
###############################################################################
#                                                                             #
#   Copyright 2005 University of Cambridge Computer Laboratory.               #
#                                                                             #
#   This file is part of Nprobe.                                              #
#                                                                             #
#   Nprobe is free software; you can redistribute it and/or modify            #
#   it under the terms of the GNU General Public License as published by      #
#   the Free Software Foundation; either version 2 of the License, or         #
#   (at your option) any later version.                                       #
#                                                                             #
#   Nprobe is distributed in the hope that it will be useful,                 #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of            #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             #
#   GNU General Public License for more details.                              #
#                                                                             #
#   You should have received a copy of the GNU General Public License         #
#   along with Nprobe; if not, write to the Free Software                     #
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA #
#                                                                             #
###############################################################################


##############################################################################
## 
## 
## 
## Splice two or more time series (each with sel-contained t) to form 
## continuous series
##
## 

############################################################################ 

import string
import glob
import os
import sys
import nprobe
from sys import argv
import getopt
from signal import *
from np_plot import *
	    
	     
##############################################################################

def usage():

    print 'usage ts_splice.py  [-s offset] <data file ts1> <data file ts2> <...>'
    print '-s add offset sec to start\n-d discrete series - otherwise continuous'
    sys.exit(1)
	    
	     
##############################################################################

##############################################################################

def get_data(files):
    alldata = []

    for file in files:
	data = []
	f = open(file, 'r')
	n = 0
	line = 0
	while 1:
	    s = f.readline()
	    line = line +1
	    if not len(s):
		break
	    if s[0] == '#' or s[0] == ' ' or s[0] =='\n':
		#print 'comment'
		continue
	    vs = string.split(s)
	    try:
		data.append([string.atof(vs[0]), string.atof(vs[1])])
		n = n + 1
	    except IndexError:
		print 'Malformed data line %d in %s' % (line, file)
		sys.exit (1)
	alldata.append((data,n))

    return alldata
	    
	     
############################################################################## 

def splice(data, st, dis):

    sp = []
    l = 0

    for dd in data:
	d = dd[0]
	d.sort()
	for p in d:
	    sp.append([p[0]+st, p[1]])
	    #print '%.0f %.0f' % (p[0]+st, p[1])
	    l += 1
	if not dis:
	    st += d[-1][0]
	    #print st
    return (sp, l)
	    
	     
##############################################################################

def main():

    start = 0.0
    discrete = 0
    view = 0
    
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'hs:dv')
	
    except getopt.error, s:
        print 'ts_splice: ' + s
        usage()
        sys.exit(1)
	
    for opt in optlist:
	if opt[0] == "-h":
	    usage(scriptname)
	if opt[0] == "-s":
	    start = string.atof(opt[1])
	if opt[0] == "-d":
	    discrete = 1
	if opt[0] == "-v":
	    view = 1

    if len(args) >= 2:
	print 'Splicing as ',
	if discrete:
	    print 'discrete series'
	else:
	    print 'continuous series'
	for f in args:
	    print f

	data  = get_data(args)
    else:
	print 'Specify two or more data files'
	usage()

    basepath = args[0]

    d, dlen = splice(data, start, discrete)

    if view:
	setstr = ''
	first = 1
	for a in args:
	    setstr += a
	    if not first:
		setstr += '+'
	    first = 0

	s = DataSet(d, DATA_TS, '', 0, None)

	try:
	    np_Plot([s], standalone='yes', path=basepath,  
		title='Spliced', xlab=' Elapsed time s', ylab='ms')
	except EmptyDataSetError:
	    print '%s - empty data set' % (ds.path)
	sys.exit(1)

    else:

	fnm = raw_input('Enter file to save as (! to abort)')
	if fnm[0] == '!':
	    return
	f = open(fnm, 'w')
	for p in d:
	    f.write('%10f\t%10f\n')
	


    return
	    
	     
##############################################################################


# Call main when run as script
if __name__ == '__main__':
        main()
