#!/usr/bin/env python
#
#   Copyright 2016 Blaise Frederick
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
#
# $Author: frederic $
#       $Date: 2016/07/11 14:50:43 $
#       $Id: showxcorr,v 1.41 2016/07/11 14:50:43 frederic Exp $
#
from __future__ import division, print_function

import bisect
import sys

import numpy as np
import rapidtide.io as tide_io
from pylab import figure, plot, show


def maketcfrom3col(inputdata, timeaxis, outputvector, debug=False):
    theshape = np.shape(inputdata)
    for idx in range(0, theshape[1]):
        starttime = inputdata[0, idx]
        endtime = starttime + inputdata[1, idx]
        if (starttime <= timeaxis[-1]) and (endtime >= 0.0) and (endtime > starttime):
            startindex = np.max((bisect.bisect_left(timeaxis, starttime), 0))
            endindex = np.min((bisect.bisect_right(timeaxis, endtime), len(outputvector)))
            outputvector[startindex:endindex] = inputdata[2, idx]
            print(starttime, startindex, endtime, endindex)
    if debug:
        fig = figure()
        ax = fig.add_subplot(111)
        ax.set_title("temporal output vector")
        plot(timeaxis, outputvector)
        show()
    return outputvector


def usage():
    print("tcfrom3col - convert a 3 column fsl style regressor into a one column timecourse")
    print("")
    print("usage: tcfrom3col infile timestep numpoints outfile")
    print("")
    print("required arguments:")
    print("	infile:      a text file containing triplets of start time, duration, and value")
    print("	timestep:    the time step of the output time coures in seconds")
    print("	numpoints:   the number of output time points")
    print("	outfile:     the name of the output time course file")
    print("")
    return ()


# get the command line parameters
debug = False
nargs = len(sys.argv)
if nargs != 5:
    usage()
    exit()
infilename = sys.argv[1]
timestep = float(sys.argv[2])
numpoints = int(sys.argv[3])
outfilename = sys.argv[4]

# now make the vector
inputdata = tide_io.readvecs(infilename)
timeaxis = np.arange(0.0, numpoints * timestep, timestep)
outputdata = 0.0 * timeaxis
outputdata = maketcfrom3col(inputdata, timeaxis, outputdata, debug=debug)
tide_io.writenpvecs(outputdata, outfilename)
