% Jon Newman
% Ming-fai Fong
% Multi-parameter activity assay for cultures transfected with
% optical exciters and silencers

% File name
fam = 'ollie';
mea = '363';
no = '01';

fid = ['u_' datestr(now,29) '_hoss-r3_' fam '_' mea '_' no];

% Parameters to explore 1. Frequency
f = [0.1 0.5 1 0.5];

% 2. Pulse Width
w = [100 500 1000 5000]; %msec

% 3. Amplitude
a = 1:5; % meaning 0.2:0.2:1

% Experiment parameters
t_pre = 30; % seconds
t_dead = 30; % seconds
prot_time = 60; % seconds
channel = 1; % only this ao channel will be used
aoff = -0.5;

% Make the pulse sweep protocols
allparams = combvec(f,w,a);

%% Make the protocol

% Storage vectors
T = [0;0];
A = [aoff;aoff];
C = [channel;0];
T_D = [0;0];
S_D = [0;0];

% digital bits
b_trig = '0'; % one trigger bit
b_chan = '00'; % two bits for the A0 being used
b_freq = '0000000'; % 7 bits for stim freq
b_width = '0000000000000'; % 13 bits for pulse width
b_amp = '000'; % 3 bits for amplitude

% start time at the end of the pre recording
tot = t_pre;

% Finally, apply the non-random series of pulses
r = randperm(size(allparams,2));
for i = 1:size(allparams,2)
    
    % grab a random combo of f,w and a
    p = allparams(:,r(i));
    
    if 1000/p(2) <= p(1)
        continue;
    end

    % caclulate the on/off times
    N = prot_time*p(1);
    t1 = tot + cumsum((1/p(1))*ones(N,1))-(1/p(1));
    t0 = t1 + p(2)/1e3;
    tot = tot + prot_time + t_dead;
    
    % translate to digital event times
    t = zeros(length(t1) + length(t0),1);
    t(1:2:end) = t1;
    t(2:2:end) = t0;
    c = channel*ones(size(t));
    a = zeros(size(t));
    a(1:2:end)  = a(1:2:end) + p(3);
    a(2:2:end)  = a(2:2:end) + aoff;
    
    % create the integer numbers used to encode the stimulus on
    b_chan= dec2bin(channel,length(b_chan)); % Freq encoded in bits 2-8
    b_freq = dec2bin(p(1),length(b_freq)); % Freq encoded in bits 2-8
    b_width = dec2bin(p(2),length(b_width)); % Width encoded in bits 9-22
    b_amp = dec2bin(p(3),length(b_amp)); % Width encoded in bits 9-22
    b_str = [b_amp b_width b_freq b_chan '1'];
    int_on = bin2dec(b_str);
    b_str = [b_amp b_width b_freq b_chan '0'];
    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];
    C = [C; c];
    A = [A; a];
    
    T_D = [T_D; t];
    S_D = [S_D; int];
    
end

% Write the .oldig file
stairs(T,A)
makeauxfile(fid,T,C,A);
makedigfile(fid,T_D,S_D);

