% jon newman
% ga tech

% 17 may 2010

% using the locations of bursts within the extracellualr data,
% corresponding intracellular current inputs are made into intracellular
% stimulation files for use with patchmaster

tankid = 'c:\tdtdata\20100420\20100420-25';
[directory file] = queryfid(tankid);
fid = strcat([directory '\' file]);

load(fid);

%% relate burst times to intracellular recording
presnip = 12500;
postsnip = 25000; % samples
bursttime = data.extrarec.bursts.bursts(:,1);
intratime = data.trange(1)+ 1/data.sampfreq*(1:length(data.intrarec.imon));

% find where bursts occured in intracellular recording
burstind = [];
for i = 1:length(bursttime)
    [amp ind] = min(abs(intratime-bursttime(i)));
    burstind = [burstind ind];
end

% get the intracellular current inputs during when a burst occured
%% extracellularly
burstinputsnip = zeros(size(burstind,1),presnip+postsnip+1);
nanind = [];
for i = 1:length(burstind)
    if burstind(i)-presnip < 0 || burstind(i)+postsnip > length(data.intrarec.imon)
        burstinputsnip(i,:) = nan(size(burstinputsnip(i,:)));
        nanind = [nanind i];
    else
        burstinputsnip(i,:) = -data.intrarec.imon(burstind(i)-presnip:burstind(i)+postsnip)./2;
    end
end

h = figure()
plot(1/data.sampfreq*(1:(presnip+postsnip+1)),burstinputsnip')
xlabel('time (s)')
ylabel('i_{mem} (pa)')
title('intracellular currents during extracellular bursting')

figdir = strcat([fid(1:end-4) '_FIG']);
figfid = strcat([file(1:end-4) '_intracellburstsnips_divideby2']);
if ~exist(figdir,'dir')
    mkdir(figdir);
end
saveas(h, strcat([figdir '\' figfid '.fig']))
saveas(h, strcat([figdir '\' figfid '.jpg']))


%% Create stimulus template files for HEKA

% Custom stimulus parameters
Fs = data.sampfreq; % Hz
numreps = 25; %number of times each stimulus is repeated during a single protocol
tplbase = 'BurstCurrInput2';

% Create a randomized vector of snip inidicies
stimapporder = [];
for i = 1:numreps
    stimapporder = [stimapporder randperm(size(burstinputsnip,1))];
end

%remove indicies of nan snips
for i = 1:length(nanind)
    stimapporder(stimapporder == nanind(i)) = [];
end
    
%% Create TPL files
stimdir = strcat([directory '\' tplbase]);
mkdir(stimdir);

for i = 1:length(stimapporder)
    fname = strcat([stimdir '\' tplbase '_' num2str(i) '_1.tpl']); % one file per sweep
    fid = fopen(fname, 'w');
    fwrite(fid, 0.001*burstinputsnip(stimapporder(i),:),'single');
    fclose(fid);
end

% resave data file
data.burststim.apporder = stimapporder;
data.burststim.burstinputsnip = burstinputsnip;
data.burststim.presnip = presnip;
data.burststim.postsnip = postsnip;
data.burststim.burstinputtime = burstind;
save(strcat([directory '\' file]),'data')

% save stim application file for this tpl base
backupfid = strcat([directory '\' datestr(now,30) '_apporder']);
save(backupfid,data.burststim.apporder);



