clear all

animals = {'hp12_272a','hp12_293a','hp13_102a','hp13_170a','hp14_226b','hp15_117a','hp16_264a'};
path = mfilename('fullpath');
hdd = path(1);
spath = [hdd,':\d3\scripts'];
caldir = [hdd,':\d3\d3matlab\cal'];
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)

fthresh = 90;
perm_results = cell(length(animals),1);

for an = 1:length(animals)
    
    prefix = animals{an};
    deploy_name = prefix;
    recdir = [hdd,':\d3\data\',prefix(1:4),'\',prefix];
    
    load_nc(fullfile(spath,[prefix,'noise.nc']))
    load(fullfile(spath,[prefix,'noisedata.mat']),'ndata')
    
    bdata = MBCD.data;
    vdata = MVP.data;
    
    allpct  = [];
    for i = 1:length(ndata)
        if ~isempty(ndata(i).TOLpct)
            allpct = [allpct; ndata(i).RMS(1,1),ndata(i).TOLpct(:,8)'];
        end
    end
    
    noise_meas = 4;
    bix = find(bdata(:,4)>0,1,'first');
    if (bdata(bix,1)-ndata(1).rawRMS(1,1))<3600
        bix = find((bdata(:,1)-ndata(1).rawRMS(1,1))>3600,1,'first');
    end
    snoise = allpct;
    snoise(allpct(:,1)<bdata(bix,1),:)=[];
    [kx,mind] = nearest(bdata(:,1),snoise(:,1),59);
    figure(100),
    subplot(4,2,an)
    plot(snoise(:,noise_meas),bdata(kx,4),'o')
    hold on
    plot(snoise(:,noise_meas),bdata(kx,2),'o')
    
    count = 0;
    for thresh = 96:3:115
        clear subset
        subset(:,1) = bdata(kx,4);
        subset(:,2) = bdata(kx,2);
        grouping = zeros(length(kx),1);
        grouping(snoise(:,noise_meas)>=thresh) = 1;
        if sum(grouping)>=5
            count = count+1;
            subset(snoise(:,noise_meas)<thresh&snoise(:,noise_meas)>=fthresh,:) = [];
            grouping(snoise(:,noise_meas)<thresh&snoise(:,noise_meas)>=fthresh,:) = [];
            dataset = [subset,grouping];
            headers = {'duration','count','grouping'};
            xlswrite(['fpermutation_',prefix,'.xls'],headers,count,'A1');
            xlswrite(['fpermutation_',prefix,'.xls'],dataset,count,'A2');
            [thresh, sum(grouping),sum(grouping==0),sum(snoise(:,noise_meas)<thresh&snoise(:,noise_meas)>=fthresh)]
        end
    end
end