#!/usr/bin/perl -w

# perl/splitindivburst: part of meabench, an MEA recording and analysis tool
# Copyright (C) 2000-2002  Daniel Wagenaar (wagenaar@caltech.edu)
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA



use strict;

sub usage {
print STDERR <<'EOF';
Usage: splitindivburst burstfile infile [out-burst out-inter]

where burstfile is the output of findburst and infile is a file of spikeinfos.

Outputs to infile.burst-%i those spikes that are deemed to be part of a burst,
and to infile.inter those spikes that occur between bursts. Infile must be
time sorted (by spikeorder) before passing to splitburst.

Each burst is written to a separate file, generated by replacing %i in
out-burst by a sequence number, counting from 1.

Timestamps are not altered on either of the output files.

Last two arguments override standard filenames.

Infile can be "-" for stdin.
EOF
exit(1);
}

my $RECLEN = 164;
my $RECPACK = "LLssss75";

usage() if @ARGV<2;
usage() if @ARGV>4;

my $burstlist = shift @ARGV;
my $infile = shift @ARGV;
my $burstout = $infile . ".burst-%i"; $burstout = shift @ARGV if @ARGV;
my $interout = $infile . ".inter"; $interout = shift @ARGV if @ARGV;

open BURSTLIST, "<$burstlist" or die "Cannot read $burstlist";
open INFILE, "<$infile" or die "Cannot read $infile";
open INTEROUT, ">$interout" or die "Cannot write $interout";

my $burst=0;
my ($burststart, $burstend) = getburst();
my $spike;
while (read(INFILE,$spike,$RECLEN)==$RECLEN) {
  my @t = unpack("LL",$spike);
  my $t = $t[0]/25000 + $t[1]*171798.69184;
  if ($t < $burststart) {
    print INTEROUT $spike;
  } elsif ($t < $burstend) {
    print BURSTOUT $spike;
  } else {
    ($burststart, $burstend) = getburst();
  }
}
exit(0);

sub getburst {
  close BURSTOUT;
  my $line = <BURSTLIST>;
  return (0,0) unless defined $line;
  chomp $line;
  $line =~ s/^ +//;
  my ($t0, $dt) = split(/ +/,$line);
  open(BURSTOUT, sprintf(">$burstout",++$burst)) or die "Cannot write $burstout";
  return ($t0, $t0+$dt);
}
