% Jon Newman
% Ga Tech

% 13 Apr 2010

% Takes data that has already been sorted and pulled from TDT tank by
% stimulus parameters and ARASID's it. Then it appends the arasid data to
% to the file and resaves.

dirID = 'C:\TempData\20100409\20100409-1\';
dirdat = dir(strcat([dirID '*.mat']));

for j = 1:size(dirdat,1)
    
    fid = dirdat(j).name;
    load(strcat([dirID fid]));
    
    % data parameters
    Fs = data.sampfreq;
    Ts = 1/Fs;
    
    % Retrieve stimulus parameters
    amp = data.stimpara.amp;
    tau = data.stimpara.tau;
    
    if tau~=0
        
        % EC stim and IC Imon
        Vstim = data.stimulus.vapp; %CHANGE TO VMON
        Imem = data.intrarec.imon;
        time = Ts*(1:size(Imem,1));
        
        % ARASID
        u = Vstim(:,1);
        y = Imem(:,1);
        breakpoints = floor(length(Y)/10*(1:10));
        y = detrend(y,'linear',breakpoints);
        arasid_data = iddata(y,u,Ts);
        artiSys = impulse(arasid_data,[0 0.02]);
        
        disp(strcat(['Running ARASID on data from: ' fid]));
        
        % Correct for direct activation/cap. artifact
        ImemSansDA = zeros(size(Imem));
        EstArt = zeros(size(Imem));
        modFits = zeros(size(Imem,2),1);
        for i = 1:size(Imem,2);
            Y = Imem(:,i);
            Y = detrend(Y,'linear',breakpoints);
            YH = sim(artiSys,Vstim(:,i));
            EstArt(:,i) = YH;
            ImemSansDA(:,i) = Y-YH;
            modFits(i) = 100*(1-(norm(Y-YH)/norm(Y-mean(Y)))); % in %
        end
        
        % Append corrected data to data struct and resave
        data.arasid.model = artiSys;
        data.arasid.iart = ImemSansDA;
        data.arasid.estifact = EstArt;
        data.arasid.fits = modFits;
        
    else
        data.arasid.model = 'NA';
        data.arasid.iart = 'NA';
        data.arasid.estifact = 'NA';
        data.arasid.fits = 'NA';
    end
    
    disp(strcat(['Finshed. Re-saving file as: ' fid]));
    save(strcat([dirID fid]),'data');
    
end