% Jon Newman
% 11 Feb. 2010
% 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

%% General Parameters
% Stimulation Time Resolution (in kHz)
Fs = 24.414; 

% Coeffcient Indicies
Nf = 1:1024;

%% Create Coefficients
taus =Fs*[5 10 20 50 100]; %tau's in milliseconds
b = zeros(length(taus),length(Nf));

for j = 1:length(taus)
    bu = exp(-Nf/taus(j));
    b(j,:) = bu/norm(bu);
end

% Write the Coefficients to file
csvwrite('FIR_coeffs',b);

%% TDT Inteface via Active X
close all; clear all; clc;

a = csvread('C:\Documents and Settings\Patch Rig\Desktop\PROTOCOLS\20100208_concurrentPatchMEA\UserFiles\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

%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)

% close all;
% figure
% subplot(6,1,1)
% stem(r)
% for i = 0:4
%     TD.SetTargetVal('MEA.tauSelect',i);
%     pause(2)
%     r = TD.ReadTargetV('MEA.currCoeffs',0, 1024);
%     subplot(6,1,i+2)
%     stem(r)
% end

TD.CloseConnection