% Jon Newman
% 2013-12-08
% Apply sinusoidal stimuli

% File name
fam = 'smiley';
mea = '22568';
no = '01';

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

% Pulse parameters
N = 100;      % Number of trials for each parameter set
Vmax = 5;    % Volts
dt = 0.01; % DAC sample res. (ms)
A = 10; % Total light power per pulse, mW*ms/mm^2
T = [1.33 2 3 4 5 10 20 30 40 50]; % Triangle widths, ms
aoff = -0.1; % Off voltage

% Create triangle waveforms to apply
[tri, tri_time] = make_area_triangles(T,A,Vmax,dt,aoff);

% Create pulse order
which_tri = repmat(1:numel(T),1,N);
which_tri = which_tri(randperm(numel(which_tri)));

% Experiment parameters
t_pre = 60; % seconds
t_per = 0.1; % 60% seconds

% Stim channel 
channel = 0;

%% Make the protocol

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

% digital bits - all we need to encode is u because everything is
% dependent on that
b_trig = '0'; % one trigger bit
b_chan = '00'; % two bits for the A0 being used
b_u = '00000'; % 5 bits to encode the pulse type (just a number)
tot = t_pre; % start time at the end of the pre recording
% slope = slope*1000*5/2; % V_ref volts/sec

for i = 1:length(which_tri)
    
    this_tri = tri{which_tri(i)};
    this_time = tri_time{which_tri(i)};
    
    % Create the analog pulse
    t1 = tot + this_time;
    ton = t1(1);
    toff = t1(end);
    c = channel*ones(size(this_tri));

    % Update total time
    tot = t1(end) + t_per;

    % create the integer numbers used to encode the stimulus on
    b_chan= dec2bin(channel,length(b_chan)); % Freq encoded in bits 2-8
    b_u = dec2bin(which_tri(i),length(b_u)); % 100e6 * u encoded in bits 2-31
    
    % Acutal encoding strings
    b_str = [b_u b_chan '1'];
    int_on = bin2dec(b_str);
    b_str = '0';
    int_off = bin2dec(b_str);
    
    % add to master list
    T = [T; t1'];
    C = [C; c'];
    A = [A; this_tri'];
    
    T_D = [T_D; [ton; toff]];
    S_D = [S_D; [int_on; int_off]];
    
end

T = [T;tot;tot];
A = [A;aoff;aoff];
C = [C;1;0];

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

