% Jon Newman
% 2010 11 04
% 2010 11 05
% Random Poisson/Spatial Unif Stimulaiton at varying rates

%% When you gonna stimulate?
% Waveform parameters (800 us, biphasic, +-0.75V sqr wave)
Ts = 10e-6; % msec
amp = 0.75; % volts
duration = 100; % samples
pads = 10; % samples
minstimper = 50e-6; % minimal inter-stimulus period,seconds

lam = [5 20 50];
numepochs = 10; % number of repeats for each rate
lengthepoch = 60; % sec
MEA = '16259-Optimus';
minspace = minstimper + duration*Ts;

whosup = [];
for i = 1:numepochs
    whosup = [whosup randperm(length(lam))];
end

st_time = [];
stimtype = [];
start = 0;
for j = 1:length(whosup)
    t = sort(unifrnd(start,start+lengthepoch*1000,lam(whosup(j))*lengthepoch,1));
    while min(diff(t))/1000 < minspace
        ind = find(diff(t)/1000 < minspace)+1;
        t(ind) = unifrnd(start,start+lengthepoch*1000,length(ind),1);
        t = sort(t);
    end
    
    stimtype = [stimtype; lam(whosup(j))*ones(lam(whosup(j))*lengthepoch,1)];
    st_time = [st_time ; t];
    start = start + 1000*lengthepoch;
    
end

%% Where you gonna stimulate?
stimch = setdiff(1:64,[1 8 33 57 64])';
st_chan = stimch(ceil(length(stimch)*rand(length(st_time),1)));

%% What you gonna stimulate with?
basewave = [zeros([1,pads]) amp*ones([1 (duration-2*pads)/2]) -amp*ones([1 (duration-2*pads)/2]) zeros([1,pads])];
st_wave = basewave(ones(size(st_chan)),:);

%% Record Stim Parameters
plot(st_time/1000/60,st_chan,'.')

Parameters = {};
Parameters.UsedStimulusChannels = stimch;
Parameters.IdealTimeFirstStimSec = st_time(1)/1000;
Parameters.RatesUsedHz = lam;
Parameters.WhichRate = whosup;
Parameters.EpochLengthSec = lengthepoch;
Parameters.NumEpochPerRate = numepochs;
Parameters.StimType = stimtype;
Parameters.Stimulus = basewave;

%% Save Experiment Info
fid = [datestr(today,29) '_' MEA '_PoisStim-ChangingRate' ];
makestimfile(st_time,st_chan,st_wave,fid);
save([fid '_Info'], 'Parameters');





