% Jon Newman
% Georgia Tech

% This script extracts data from TDT tanks that a filled during concurrent
% patch MEA experiments

% 16 Feb 2010 - Basic data recall
% 17 Feb 2010 - Timing extraction for stimulation events
% 07 Mar 2010 - Extraction of stimulation events with specific parameters
% 08 Mar 2010 - Extraction of records over specific parametric stimulus
% times
% 13 Apr 2010 - Added script to extract stimulus parameters from 'latest'
% file compared to the block recording time.


%% 1. Enter the parameters needed to specify tank and block to access
% *************************************************************************
tankID = 'C:\TempData\20100409'; % tank name
blockID = '20100409-1'; % block name, the '~' automatically calls CreateEpocIndexing() so that an epoch index is created for the filtering methods
Ifactor = 10; % scale factor for Imon (pA/mV)
Fs = 24414.1; % Hz
% *************************************************************************
%% 2. 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'); % MaxReturn=10000000000000; WavesMemLimit = 1000000000000000000'
% Select the block to access and set epoch indexing
TT.SelectBlock(blockID);
TT.CreateEpocIndexing;
% Set the reference epoch
TT.SetRefEpocV('StmV');

%% 3. Extract some information about this data block
% Get the possible 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);

% When was this data recorded?
start = TT.CurBlockStartTime;
disp('The time of this recording was:');
timeofrec = TT.FancyTime(start ,'Y/O/D H:M:S');

% Now look for the stimulus parameter file that was last used to confirm
% what the stim parameters (amplitude and tau) that were used for this
% record. Then write them in here:
dir(tankID)
paramID = '20100412T140026_StimParameters.mat';
% sp = load(strcat([tankID '\' paramID]));

% amps = sp.stimparams.amps;
amps = [0 1];
% taus = sp.stimparams.taus;
taus = [1 3 5 7 10 15 20];
types = 0:length(taus);

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

for i = amps;
    for j = types;
        
        Type = j;
        Amp = i;
        
        % Filter the data by the current amp and type
        filtstr = strcat(['Type=' num2str(Type) ' and ' 'Amp_=' num2str(Amp)]);
        TT.ResetFilters; % Reset any residual filters that might be hanging around
        TT.SetFilterWithDescEx(filtstr); %Set filter, returns (1) if it succeeds
        disp(strcat(['The epochs that pass [' filtstr '] are [[Type;T1;T2],...]:']));
        timing = TT.GetEpocsExV('Type',2);
        disp(timing)
        
        % Read only the filtered events
        data = {};
        
        % Record the date when the data was recorded
        data.rectime = timeofrec;
        
        % Record the sample freq for these data
        data.sampfreq = Fs;
        
        % Record TDT-derived notes on the data
        data.notes = TT.CurBlockNotes;
        
        % Record the stimulus parameters for this data
        if Type == 0
            data.stimpara.tau = 0;
            data.stimpara.amp = Amp;
        else
            data.stimpara.tau = taus(Type);
            data.stimpara.amp = Amp;
        end
        
        % Record the valid record time
        if ~isnan(timing)
            data.valitime = timing(2:3,:);
        end
        
        % Extract extracellular record
        N = TT.ReadEventsSimple('eNeu');
        data.extrarec.spiketime = TT.ParseEvInfoV(0, N, 6);
        data.extrarec.waveform = double(TT.ParseEvV(0, N));
        data.extrarec.channel = TT.ParseEvInfoV(0, N, 4);
        data.extrarec.unitID = TT.ParseEvInfoV(0, N, 5);
        
        % Extract intracellular record
        data.intrarec.vmon = double(TT.ReadWavesOnTimeRangeV('Heka',1));
        data.intrarec.imon = double(Ifactor*detrend(TT.ReadWavesOnTimeRangeV('Heka',2),'constant'));
        data.intrarec.stim = double(TT.ReadWavesOnTimeRangeV('Heka',3));
        
        % Extract extracellular stimulus record
        data.stimulus.vapp = double(TT.ReadWavesOnTimeRangeV('Stim',1));
        data.stimulus.vmon = double(TT.ReadWavesOnTimeRangeV('Stim',2));
        
        %  Save these sorted Epochs in their own files.
        if ~isnan(timing)
            if Type ==0
                fid = strcat(['Tau_' num2str(Type) '-' 'Amp_' num2str(Amp) '.mat']);
            else
                fid = strcat(['Tau_' num2str(taus(Type)) '-' 'Amp_' num2str(Amp) '.mat']);
            end
            fileloc = strcat([tankID '\' blockID '\' fid]);
            save(fileloc,'data');
        end
        
    end
end

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



