% Jon Newman
% Georgia Tech
% 16 Feb 2010 - Basic data recall
% 17 Feb 2010 - Timing extraction for stimulation events
% 07 Mar 2010 - Extraction of stimulation events with specific parameters
% 
% This script extracts data from TDT tanks that a filled during concurrent
% patch MEA experiments


%% Parameters needed to specify tank and block to access

tankID = 'C:\Users\Jon\Desktop\20100305'; % tank name
blockID = '~arasid-1'; % block name, the '~' automatically calls CreateEpocIndexing() so that an epoch index is created for the filtering methods

%% Open connection to server

%First instantiate a variable for the ActiveX wrapper interface
TT = actxcontrol('TTank.X');
% Then connect to a server.
TT.ConnectServer('Local', 'Me');
% Now open a tank for reading.
TT.OpenTank(tankID, 'R');
% Set global parameters
TT.SetGlobals('Channel=0; Options=FILTERED; RespectOffsetEpoc=0')
% Select the block to access
TT.SelectBlock(blockID);
% Set the reference epoch
TT.SetRefEpocV('StmV');
%% Get the Epoch Codes
epochcodes = {};
i = 0;
code = 'temp';
while 1==1
    code = TT.GetEpocCode(i);
    i=i+1;
    if ~strcmp(code,'')
        epochcodes{i} = code;
    else
        clear 'code'
        break
    end
end

disp('The available epoch string codes for this block: ');
disp(epochcodes);

%% Filter data so that only epochs for specified events are pulled

TT.ResetFilters; % Reset any residual filters that might be hanging around
TT.SetFilterWithDescEx('Type=-1 and Amp_=0.1'); %Set filter, returns (1) if it succeeds
disp('The epochs that pass the filter are [[Type;T1;T2],...]:');
disp(TT.GetEpocsExV('Type',2))

%% Read only the filtered events
data = {};

% Extract extracellular record
N = TT.ReadEventsSimple('eNeu');
data.extrarec.spiketime = TT.ParseEvInfoV(0, N, 6);
data.extrarec.waveform = TT.ParseEvV(0, N);
data.extrarec.channel = TT.ParseEvInfoV(0, N, 4);
data.extrarec.unitID = TT.ParseEvInfoV(0, N, 5);

% Extract intracellular record
N = TT.ReadEventsV(10000, 'Heka', 1, 0, 0.0, 0.0, 'FILTERED');
data.intrarec.vmon = TT.ParseEvV(0, N);
N = TT.ReadEventsV(10000, 'Heka', 2, 0, 0.0, 0.0, 'FILTERED');
data.intrarec.imon = TT.ParseEvV(0, N);
N = TT.ReadEventsV(10000, 'Heka', 3, 0, 0.0, 0.0, 'FILTERED');
data.intrarec.stim = TT.ParseEvV(0, N);

% Extract extracellular stimulus record
N = TT.ReadEventsV(10000, 'Stim', 1, 0, 0.0, 0.0, 'FILTERED');
data.stimulus.vapp = TT.ParseEvV(0, N);
N = TT.ReadEventsV(10000, 'Stim', 2, 0, 0.0, 0.0, 'FILTERED');
data.stimulus.vmon = TT.ParseEvV(0, N);

% Close the tank and release client access to server
% TT.CloseTank
% TT.ReleaseServer
% TT.ClearEpocIndexing

%% Examine Data
figure()
subplot(2,1,1)
plot(data.stimulus.vmon)
subplot(2,1,2)
plot(data.intrarec.imon)