#! /usr/bin/python

import scipy.io as sio
import sys
testa = sio.loadmat('110316_1_ctrl_2.mat')
fmt = "{:.5f} {:+10.6f} {:.5f}"
rad = 350 # Samples before and after spike.
step = 0.0001 # Sampling step

for k in range(1,18):
  # Extract trace number {k}:
  tname = 'Trace_2_4_{:d}_1'.format(k)
  tr = testa.get(tname)
  n = len(tr)
  print 'trace {:<20s} {:6d} samples'.format(tname, n)
  # Find and write out spikes:
  inx = 0 # Next index to search.
  m = 0  # Number of spikes found so far. 
  while inx < n:
    # Find the start {ist} of next spike:
    ist = inx 
    while ist < n and tr[ist][1] < 0.041:
      ist = ist + 1
    # Find the end {ien} of the spike:
    ien = ist + 1
    while ien < n and tr[ien][1] > 0.039:
      ien = ien + 1
    if ien < n:
      # We have another spike:
      m = m + 1
      print '  spike {:d} at {:d}..{:d}'.format(m,ist,ien-1)
      # Write it out:
      imd = (ist + ien - 1)/2
      fname = 'out/{:s}_sp{:04d}.txt'.format(tname,m)     
      ff = open(fname, 'w')
      for i in range(imd-rad,imd+rad+1):
        # Compute spike-relative time:
        tm = step*(i - imd)
        if i >= 0 and i < n:
          ff.write(fmt.format(tm, tr[i][1], tr[i][0]))
          ff.write('\n')
      ff.close
    inx = ien + 1
  print "{:d} spikes".format(m)