clear 
clc

%% load data
load p-unit_spike_times.mat
load p-unit_stimulus.mat
sample_rate = 20000;

%% calculate STA
all_times = [];
for i = 1:length(spike_times)
    all_times = cat(1, all_times, spike_times{i});
end

[st_average, sta_sd, num] = sta(stimulus(:,2), all_times, 1000, sample_rate);
fig = figure();
set(fig, 'PaperUnits', 'centimeters');
set(fig, 'PaperSize', [11.7 9.0]);
set(fig, 'PaperPosition',[0.0 0.0 11.7 9.0]);
set(fig,'Color', 'white')
plot(((1:length(st_average))-1000)/sample_rate, st_average)
xlabel('time [s]')
ylabel('stimulus')

%% reverse reconstruction

% make binary representation of the spike times
binary_spikes = zeros(size(stimulus, 1), length(spike_times));
estimated_stims = zeros(size(binary_spikes));
for i = 1:length(spike_times)
    binary_spikes(round(spike_times{i}*sample_rate), i) = 1;
    estimated_stims(:,i) = conv(binary_spikes(:,i), st_average, 'same');
end

fig = figure();
set(fig, 'PaperUnits', 'centimeters');
set(fig, 'PaperSize', [11.7 9.0]);
set(fig, 'PaperPosition',[0.0 0.0 11.7 9.0]);
set(fig,'Color', 'white')
plot(stimulus(:,1), stimulus(:,2), 'displayname','original')
hold on
plot(stimulus(:,1), mean(estimated_stims,2), 'r', 'displayname', 'reconstruction')
xlabel('time [s]')
ylabel('stimulus')
legend show

%% calculate STC

% we need to downsample the data otherwise the covariance matrixs gets too
% large 20Khz to 1kHz

% downsampled_binary = zeros(size(stimulus, 1)/20, length(spike_times));
downsampled_stim = zeros(size(stimulus,1)/20,1);

% for i = 1:length(spike_times)
%     indices = round(spike_times{i}.*1000);
%     indices(indices < 1) = [];
%     downsampled_binary(indices, i) = 1;
% end
for i = 1:length(downsampled_stim)
    start_index = (i-1) * 20 + 1;
    downsampled_stim(i) = mean(stimulus(start_index:start_index+19,2));
end

[st_average, ~, ~] = sta(downsampled_stim, all_times, 50, 1000);