% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This code has been written by Adelie Antoine, using functions from
% animaltags (M. Johnson, Animal Tag Tools Wiki (2017).
% URL https:// animaltags.org/), and following P. Goulet's work.
%
% It is designed to prepare files containing localisation, time at various
% formats and depth of dive data.
% The data is then exported to RStudio to plot the dive profiles, for the 
% whole deployment, and add shading during twilight.
%
% Last modification : February 2023
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% We suppose that the studied individual is identified as "314a"

clear all
close all

% load dtag_and_sonar_tools file, containing all the animaltags functions
addpath(genpath('...\dtag_and_sonar_tools'));

% load the NetCDF files containing calibrated depth data and tag info
% at 5Hz
A = load_nc('...\lw19_314a_sensor.nc'); 

%% Set time of the recordings :
% /!\ CAUTION change l.27 according to number of rows in A
% (cf. tag info)
A.second = [0:1/5:(3172541-1)/5]'; % time of the depth measure after the start of the deployment, given the sampling rate is of 5Hz
A.second = seconds(A.second);
A.start_in_datetime = datetime('2019-11-12 03:30:42'); % change according to the tag info
datetime.setDefaultFormats('default','yyyy-MM-dd hh:mm:ss')
A.datetime =datetime(A.start_in_datetime + A.second);
A.posix = posixtime(A.datetime);

%% add lat and lon :
load(".../lw19_314a_argos_track.mat"); % load the argos track file

for ii=1:length(A.second)           % for each measure...
   tdiff = abs(POS.data(:,1)-A.time(ii)) ;    % get the time offset between the recording and each gps point
   [min_tdiff,ti]=min(tdiff);       % pick the closest gps point
                  % if it is less than 2 minutes away, allocate it to the recording
      A.lat(ii)=POS.data(ti,2);
      A.lon(ii)=POS.data(ti,3); 
end

A.datenum = datenum((A.info.dephist_deploy_datetime_start )) + A.second;

T = table(A.datenum, A.datetime,A.posix, A.lat', A.lon', A.P.data);


writetable(T, "...\data_for_sunangle_314a.csv")
