% Jon Newman
% 11 Feb. 2010
% 29 Mar. 2010
% 12 Apr. 2010 - Added random stimulus ampltidude capabilities
% Georgia Tech

% This script creates a set of FIR coefficients to be used with the FIR2 filter
% block on the RPvdsEx to make colored Gaussian waveforms with power
% preservation

%% Stimulus Parameters
% File paths and names
FP = 'C:\Documents and Settings\Annihilatrix II\My Documents\Temp Data\20100412\';
DT = 'DataTanks\20100412\';
ParamFile = strcat([datestr(now,30) '_StimParameters']);

% Stimulation Time Resolution (in kHz)
Fs = 24.414; 
% Coeffcient Indicies (defines length of FIR filter)
Nf = 1:1024;

% Specify stimulus amplitude parameters
stimAmps = [0.1 0.3 0.5]; % Volts, should be equally spaced
stimInc = 0.2;
disp('The stimulus amplitudes are:')
disp(stimAmps)

% Specify time constants of stimulus waveforms
taus =     [0.5 1 3 5 7 10 15 20 50 100]; %tau's in milliseconds. SHOULD ALWAYS BE LENGTH 10. SPECIFY WHICH ONES TO USE IN NEXT LINE.
tausUsed = [0   1 1 1 1 1  1  1  0  0  ]; % Pick the time constants you want to use during your experiment.


%% create coefficients
b = zeros(length(taus),length(Nf));
taus = taus(tausUsed==1)
taus = Fs*taus;
for j = 1:length(taus)
    bu = exp(-Nf/taus(j));
    b(j,:) = bu/norm(bu);
end

% Write the Coefficients to file
csvwrite(strcat([FP DT 'FIR_coeffs.csv']),b);

% Write stimulus parameter file
stimparams.taus = taus;
stimparams.amps = stimAmps;
save(strcat([FP DT ParamFile]),'stimparams')

%% TDT Inteface via Active X

a = csvread(strcat([FP DT 'FIR_coeffs.csv']));

TD = actxcontrol('TDevAcc.X');
TD.ConnectServer('Local');
TD.SetSysMode(2)
pause(3)

% Rearrange Coeffiecients for use with FIR2
loader = [];
for i = 1:size(a,1)
    temp = zeros(1,size(a,2));
    temp(1:2:end) = a(i,1:end/2);
    temp(2:2:end) = a(i,end/2+1:end);
    loader = [loader temp];
end

%Set stim amplitude parameters
TD.SetTargetVal('MEA.NumAmps',length(stimAmps));
TD.SetTargetVal('MEA.StimIncSize',stimInc);
TD.SetTargetVal('MEA.StimMin',min(stimAmps));

%Say how many filters you are providing
TD.SetTargetVal('MEA.NumTaus',length(taus));

%Write Coefficients to memory buffer
TD.WriteTargetV('MEA.Coeffs',0,single(loader));

% Read all the coefficients
r = TD.ReadTargetV('MEA.Coeffs',0, size(loader,2));
pause(2)

TD.CloseConnection