%% Step 2: This script runs a click detector through all clicktrains of interest. In this case 'pc' = possible calls.
% It saves the output as a mat file that is needed for step 3.

clear all
clf

path = mfilename('fullpath');
hdd = path(1);
spath = [hdd,':\d3\scripts']; % The path to where the output figure is saved. 
global recdir prefix

%   prefix = 'hp12_272a';
%   prefix = 'hp12_293a';
%   prefix = 'hp13_102a';
%   prefix = 'hp14_226b';
    prefix = 'hp15_218a';
%   prefix = 'hp16_264a';

recdir = [hdd,':\d3\data\',prefix(1:4),'\',prefix];
caldir = [hdd,':\d3\d3matlab\cal'];

deploy_name = prefix;
prhdir = [hdd,':\d3\data\metadata\prh'];
auddir = [hdd,':\d3\data\metadata\aud']; % where you can find your audits

settagpath('cal',caldir,'prh',prhdir, 'audit', auddir)

R = loadaudit(deploy_name);

cliplevel = 179; %Dtag cliplevel is 179!
% channel = 2;
channel = 1;
blankt = 0.0012; % blank time seconds - seconds after one click where no new click should be looked for. 

pc = strmatch('pc',R.stype,'exact');
calls = [R.cue(pc,1) R.cue(pc,1)+R.cue(pc,2)];

subcl = calls;
% ix = find(subcl(:,1)>cues(1)&subcl(:,2)<cues(2))

fs = 5e5;
[b,a] = butter(2,8e4/(fs/2),'high'); % highpass filter with cut off f=80 kHz for analysis
figure(100),
set(gcf,'position',[88         292        1732         686])
axpos = [0.0885    0.0616    0.8802    0.4556];
axpos2 = [0.0885    axpos(2)+axpos(4)+0.025    0.8802    0.4056];
font = 15;

%%
for i = 1:length(subcl) 
    % for i = 1;
    clear s dane %
    try
        [x,afs] = d3wavread(subcl(i,:),recdir,prefix) ;
        for j = 1:size(x,2)
            x(:,j) = x(:,j) - mean(x(:,j));
        end
                        s(:,1) = filtfilt(b,a,x(:,1));
        disp(['running section ',num2str(i),' out of ', num2str(length(subcl))])
                thresh = rms(s(1:0.1*fs))/3*10^(cliplevel/20-6)

        [dane,thresh] = detectTagclicks3(x, afs, thresh, blankt);
         if size(dane{1},1)<=10
            thresh = 0.0005*10^(cliplevel/20-6);
            [dane,thresh] = detectTagclicks3(x, afs, thresh, blankt);
        end
        
        if ~isempty(dane);
            for j = 1:length(dane);
                CT{i,j} = [dane{j}(:,1)+subcl(i,1)*afs,dane{j}(:,2)+subcl(i,1),dane{j}(:,3:4)];
            end
        end
        figure(100), clf
        ax(1) = subplot(211);
        tax = (1:length(s))/fs+subcl(i,1);
        plot(tax,s)
        hold on
        plot(CT{i,channel}(:,2),rms(s)/3*ones(length(dane{1,channel}(:,1)),1),'ro'); %Adds red circles around the individual detected clicks. 
        xlim([tax(1) tax(end)])
        hold off
        grid on
        set(gca,'position',axpos2,'fontsize',font,'xticklabel','')
        ylabel('relative amplitude','fontsize',font+2)
        title(['sequence ',num2str(i),' out of ', num2str(length(subcl))],'fontsize',font+2)
        
        ax(2) = subplot(212);
        plot(CT{i,channel}(2:end,2),diff(CT{i,channel}(:,2))*1000,'.')
            grid on
        set(gca,'position',axpos,'fontsize',font)
        xlabel('tag time (s)','fontsize',font+2)
        ylabel('ICI (ms)','fontsize',font+2)
        linkaxes(ax,'x')
        set(gcf,'PaperPositionMode','auto')
        print(gcf,fullfile(spath,'pernille',['ici_',prefix,'_',num2str(round(10*subcl(i,1))),'_',num2str(round(10*subcl(i,2)))]),'-dtiff','-zbuffer','-r200')
    catch err
        disp(['something went wrong in number ', num2str(i)])
        i = i+1;
    end
end
% save('-v7.3',fullfile(spath,[prefix,'_CLDetPC1st.mat']))
save('-v7.3',fullfile(spath,[prefix,'_TEST.mat']))
% save('-v7.3',[prefix,'_CLDetPC1st2.mat']) 