# -*- coding: utf-8 -*-
# Nicolas Enfon - 01/04/14 - LSIS DYNI
import readfile
import numpy
from pylab import plot, show, subplot, specgram, savefig, figure
from matplotlib.pyplot import *
from scipy.io.wavfile import read,write
from random import random
import cPickle

#Various parameters
audio_file = 'ANTARES_66496.21_full_concatenated.wav'
dat_url = 'ANTARES_66496.21_03_09_2012_23.19.41_02.20.28_T8_Q20_J60_scalo1_L1.dat'
log_url = 'log'

#Reading of the input audio data
sampling_rate, data = read(audio_file)

#Reading of the .dat file
def read(dat_url, startline=None, endline=None):
    ''' Reads a .dat file and returns the needed rows '''
    #TODO: incorporate that in the first readfile.readdat!
    dat_file_raw = readfile.readdat(dat_url)
    dat_file = numpy.array(dat_file_raw)
    if startline == None:
	startline = 0
    if endline == None:
	endline = len(dat_file)
    return dat_file[startline:endline,:]

#Simple detector
def detector(dat_file, threshold=0.25, conv_size=35):
    ''' Detects the energy peaks above a threshold, and saves their position '''
    trend = dat_file.sum(0)
    smoothed_trend = numpy.convolve(trend, numpy.ones(conv_size), mode='same')
    mean = smoothed_trend.mean()
    peaks = []
    for i in xrange( len( smoothed_trend ) ):
	if smoothed_trend[i] > mean * (1 + threshold):
	    peaks.append(i)
    return peaks

def scaled_detector(data, dat_file, peaks, size=1000):
    ''' Scales the peaks and make 0/1 gates that match the audio data size.
	size is in bins, ie in seconds * sampling_rate(data) '''
    peaks = numpy.array(peaks)
    peaks = peaks * len(data) / float(len(dat_file[0]))
    for i in xrange(len(peaks)):
        peaks[i] = int( round( peaks[i] ) )#caution, numpy array keeps float type
    peaks_gate = numpy.zeros( len( data ) )
    for i in xrange( len( peaks ) ):
        deb = int( peaks[i] - size )
        if deb < 0:
            deb = 0
        fin = int( peaks[i] + size )
        if fin >= len( data ):
            fin = len( data ) - 1
        peaks_gate[ deb : fin ] = 1
    return peaks_gate

    
