% Jon Newman
% 2011 04 20
% makes protocol for light stimulation parameter sweep

% Parameters for pulse protocols
fid = [datestr(now,29) '_pulse-sweep'];
Tdead = 20; %time between stim sessions, sec
Tprot = 20; %time of stim sessions, sec
freq = [1 5 10 20 40 80]; % Hz
width = [50 100 500 1000]; % uS

% Make the pulse sweep protocols
tot = 30*60; % 30 min spont b4 stimulation
allparams = combvec(freq,width);
r = randperm(length(allparams));

% storage for makedigfile args
T = [];
P = [];

for i = 1:length(allparams)
    
    % grab a random combo of F and W
    F = allparams(1,r(i));
    W = allparams(2,r(i));
    
    % caclulate the on/off times
    N = Tprot*F;
    tot = tot + Tdead;
    t1 = tot + cumsum((1/F)*ones(N,1))-(1/F);
    t0 = t1 + W/1e6;
    tot = tot + Tprot;
    
    % translate to digital event times
    t = zeros(length(t1) + length(t0),1);
    t(1:2:end) = t1;
    t(2:2:end) = t0;
    
    % create the integer numbers used to encode the stimulus
    % on
    b_trig = '1';% Trigger encoded in bit 0
    b_type = '0'; % Type encoded in bit 1
    b_freq = dec2bin(F,7); % Freq encoded in bits 2-8
    b_width = dec2bin(W,14); % Width encoded in bits 9-22
    b_str = [b_width b_freq b_type b_trig];
    int_on = bin2dec(b_str);
    
    % off
    b_trig = '0';
    b_type = '0';
    b_freq = dec2bin(F,7);
    b_width = dec2bin(W,14);
    b_str = [b_width b_freq b_type b_trig];
    int_off = bin2dec(b_str);
    
    int = zeros(length(t1) + length(t0),1);
    int(1:2:end) = int_on;
    int(2:2:end) = int_off;
    
    % add to master list
    T = [T; t];
    P = [P; int];
    
end

% Write the .oldig file
plot(T,P)
makedigfile(fid,P,T);
