% The purpose of this script is to generate image frames to use for optical
% stimulation of ChR2-transfected cultures.

clear all;
close all;

lambda = 10; %average stimulation rate, in Hz
T = 60; %total length of movie, in seconds
dt = 1/30; %length of single stim pulse, in seconds (1/dt = frame rate)

t = [0:dt:T];
stim_times = [];

% intensity stats
mu = 0.5;
sigma = 0.5/3;

%--generating color map--%
for j = 1:100
    nm460gamma(j,:)=[0 123 255]*(j/100)/255; %gamma-corrected values
    nm460(j,:)=[0 102 255]*(j/100)/255; %no gamma correction
end

%map1 = [ 150 0 0; 100 20 50; 50 60 127.5; 0 80 200; 0 120 255]/255; %red to blue
%map2 = [0 0 145; 0 20 165; 0 40 175; 0 60 195; 0 80 215; 0 100 235; 0 120 255]/255; %blue only

figure(1);
blank_image = zeros([175 175]);
imshow(blank_image);

for i = 1:length(t)
    if lambda*dt >= rand(1)
        stim_times(1,end+1) = t(i); %draws stim time from poisson process with rate lambda
        figure(2);
        image{i} = mu + randn([175,175]).*sigma; %generates a set of intensities
        imshow(image{i});
        colormap(nm460);
        print(['stim' num2str(i) '.jpg'],'-djpeg');
        colormap(nm460gamma); %adjusts peak wavelength to 460nm
        print(['stim' num2str(i) '_gammacorr.jpg'],'-djpeg');
    else
        figure(1);
        print(['stim' num2str(i) '.jpg'],'-djpeg');
    end
%    print(['stim' num2str(i) '.jpg'],'-djpeg');
end

save('stimulus.mat','T','dt','lambda','stim_times','image');