%% Step 3: Based on the output file from step 3, this script creates a file for each click train of
% interest with time and sample cues for each click within this clicktrain.
% Saves it as a file that includes information of which animal and the
% start and end time of emission i the full recording.
close all
clear all
path = mfilename('fullpath');
hdd = path(1);
spath = [hdd,':\d3\scripts'];
% prefix = 'hp12_272a';
% prefix = 'hp12_293a';
% prefix = 'hp13_102a';
% prefix = 'hp14_226b';
  prefix = 'hp15_218a';
% prefix = 'hp16_264a';

cpath = fullfile(spath,'pernille',prefix,'curC','test'); % Goes to this folder: 'F:\d3\scripts\pernille\hp14_226b\curC';
channel = 1; 
fs = 5e5;

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']; 

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

load([prefix,'_TEST.mat'],'subcl','CT')
 
recPieces = subcl*fs; 
rp = 1:size(subcl,1);
ia = rp;
iaix = find(ia>0);

 for i = 1:length(iaix);
     CL{channel} = CT{ia(iaix(i)),channel}; %original
     trialInSession = ia(iaix(i));
     
     curC.rc = CL ;
     curC.recp = recPieces(ia(iaix(i)),:);
     curCC = curC;
     
     if exist(fullfile(cpath, strcat('sound_tag_', prefix, '_',num2str(round(10*subcl(trialInSession,1))),'_',num2str(round(10*subcl(trialInSession,2))), '.mat')))
         load(fullfile(cpath, strcat('sound_tag_',  prefix, '_',num2str(round(10*subcl(trialInSession,1))),'_',num2str(round(10*subcl(trialInSession,2))),'.mat')))
         curC.rc{channel} = curCC.rc{channel};
         disp(['loaded and updated the mat file for ',num2str(i)])
     end
      save(fullfile(cpath, strcat('sound_tag_', prefix, '_',num2str(round(10*subcl(trialInSession,1))),'_',num2str(round(10*subcl(trialInSession,2))))), 'CL')
 end