%% Initialisation
% first make sure no figures are open or no data is stored in working space
close all;
clearvars;
clc;

% Check whether my custom functions are available
hasCbrewer  = ~isempty(which('cbrewer'));
hasNicegraph = ~isempty(which('nicegraph'));
hasSavegraph = ~isempty(which('savegraph'));
hasBftext = ~isempty(which('bf_text'));

if hasCbrewer
    % Use custom cbrewer colormap if available
	col = cbrewer('qual','Pastel1',3);
else
    % Fallback to built-in colormap
    colors = lines(3);
end


%% Exponential Parameters
mu	= 5; % mean spike counts per interval

%% Plotting
figure(1);
clf;

% Exponential
x		= linspace(0,50,1000);		% range for x-axis (max count to display)
y = exppdf(x,mu);
subplot(2,2,1);
plot(x,y,'k-','LineWidth',1.5);
xlim([0 50]);
xlabel({'interval duration'});
ylabel({'frequency'});
set(gca,'XTick',0:10:50,'YTick',[]);


% Exponential & Dead Time
x		= linspace(0,50,1000);		% range for x-axis (max count to display)
y = exppdf(x-10,mu);
subplot(2,2,2);
plot(x,y,'k-','LineWidth',1.5);
xlim([0 50]);
xlabel({'interval duration'});
ylabel({'frequency'});
set(gca,'XTick',0:10:50,'YTick',[]);


% Gamma & Dead Time
x		= linspace(-10,40,1000);		% range for x-axis (max count to display)
y = gampdf(x,mu,2);
subplot(2,2,3);
plot(x,y,'k-','LineWidth',1.5);
xlim([-10 40]);
xlabel({'interval duration'});
ylabel({'frequency'});
set(gca,'XTick',-10:10:40,'XTickLabel',0:10:50,'YTick',[]);

%% Simulate and plot ISI histogram
r = gamrnd(mu,2,[10000,1]);
subplot(2,2,4);
histogram(r,100);

xlim([-5 45]);
xlabel({'interval duration'});
ylabel({'frequency'});
set(gca,'XTick',-5:10:45,'XTickLabel',0:10:50,'YTick',[]);




for ii = 1:4
	subplot(2,2,ii)
	if hasNicegraph
		nicegraph;
		axis normal;
		set(gca, 'FontSize', 24);
	else
		% Minimal built-in equivalent
		box off;
		set(gca, 'TickDir', 'out', 'FontSize', 11);
	end
	if hasBftext
		bf_text(0.9,0.9,char(64+ii),'FontSize',24);
	end

end


%% Save figure
fname = fullfile('..','images','spike_isi_distribution.png');
if hasSavegraph
    % Use custom helper
    savegraph(fname,'png');
else
    % Built-in export (R2020a+; otherwise use print/saveas)
    exportgraphics(gcf, fname, 'Resolution', 300);
end

