% this script simulates extracellularly recorded 
% spike waveforms and saves them in extdata.mat.

% generate spikes:
n = 1000;
misi = 0.01;
isis = exprnd( misi, n, 1 );
isis = isis + 0.01;
spikes = cumsum( isis );
p = rand( size( spikes ) );

% spike waveforms:
dt = 0.0001;
waveformt = -0.01:dt:0.01;
waveform1 = 2.0*exp( -(waveformt-0.0003).^2/2.0/0.0005^2 ) - 1.4*exp( -(waveformt-0.0005).^2/2.0/0.0005^2 );
waveform2 = exp( -waveformt.^2/2.0/0.002^2 ).*cos(2.0*pi*waveformt/0.005);
p12 = 0.5;

% voltage trace:
noise = 0.2;
time = 0:dt:spikes(end)+3.0*waveformt(end);
voltage = noise*randn( 1, length( time ) );
for k = 1:length( spikes )
    inx = ceil( spikes(k)/dt );
    if p(k) < p12
        voltage(inx:inx+length(waveformt)-1) = voltage(inx:inx+length(waveformt)-1) + waveform1; 
    else
        voltage(inx:inx+length(waveformt)-1) = voltage(inx:inx+length(waveformt)-1) + waveform2; 
    end
end

figure( 1 );
clf;
plot( time(time<1.0), voltage(time<1.0) );
hold on;

% find peaks:
thresh = 0.7;
inx = find( voltage(2:end-1) > thresh & voltage(1:end-2)<voltage(2:end-1) & voltage(2:end-1) > voltage(3:end) ) + 1;
spiketimes = time(inx);
spikevoltage = voltage(inx);
tinx = inx;
for k=1:2
    inx = find( ( spiketimes(2:end-1)-spiketimes(1:end-2)>0.005 | spikevoltage(2:end-1) > spikevoltage(1:end-2) ) & ( spiketimes(3:end)-spiketimes(2:end-1)>0.005 | spikevoltage(2:end-1) > spikevoltage(3:end) ) )+1;
    spiketimes = spiketimes(inx);
    spikevoltage = spikevoltage(inx);
    tinx = tinx(inx);
end
scatter( spiketimes(spiketimes<1.0), spikevoltage(spiketimes<1.0), 100.0, 'r', 'filled' );
%scatter( t(tinx), v(tinx), 100.0, 'r', 'filled' );
hold off;

% save data to file:
save( 'extdata', 'time', 'voltage', 'spiketimes', 'waveformt', 'waveform1', 'waveform2' );
