#!/usr/bin/python
# -*- coding: utf-8 -*
"""
Flower Plucker
To pluck a typical (codeword) signal for paper purposes
"""

from __future__ import division # without this, python 2.x will understand 1/2 as 0.0
import numpy as np
import matplotlib.pyplot as plt
import time

FILENAME = "trace2_14:03:42.timestamp"
traceno = 14
startendparams = (882.5, 885)

# Parameters (in ms)
startpluck = startendparams[0] * 1000
endpluck   = startendparams[1] * 1000
timebin    = 10

# Conversion ratio (from timestamp to ms)
convratio = 8 * 1000 * 1000

# Open and load the timestamp file
f = open(FILENAME, 'rb')
loaddata = np.fromfile(file=f, dtype='uint64')

# Some magic code to obtain the timing of the detection events. Each time bin in 125 ps
time_array = np.uint64((loaddata << 32) >> 15) + np.uint64(loaddata >> 47)

# Some magic code to obtain the channel of the detection events
channel_array = np.uint8((loaddata >> 32) & 0xf)

nofbins = int((endpluck-startpluck) / timebin)
data_sig1 = channel_array & 0x1			# Get a masked array with that particular channel
completed_array1, bin_edges = np.histogram(time_array, bins = nofbins, range = (startpluck*convratio, (startpluck+nofbins*timebin)*convratio), weights=data_sig1)
# timebin_array = (bin_edges[:-1] - startpluck*convratio) / convratio
timebin_array = (bin_edges[:-1]) / convratio

norm_completed_array1 = completed_array1/timebin
norm_timebin_array = timebin_array / 1000    # Convert to s

data_tosave = np.transpose(np.vstack([norm_timebin_array, norm_completed_array1]))
filename = "selected_traces/trace_" + str(traceno) + ".dat"
np.savetxt(filename, data_tosave, fmt='%.3f', header="# Time (s) Counts (ms-1) ")

# Plot
plt.figure(figsize=(12,5))
plt.plot(norm_timebin_array, norm_completed_array1)
plt.xlabel("time (s)")
plt.ylabel("rate (ms-1)")
plt.savefig(filename+".pdf")
plt.show()
