%
%  extractDbd.m
%
%  Purpose: Save a .mat file with flight characteristics.
%
%  NOTE: At top of file, set glider index and deployment number
%
%  MATLAB folder - contains util
%
%
%  Author:  Adapted from William Stark by Chris Calloway
%           Marine Sciences Department
%           UNC-Chapel Hill
%
%  Created: March 2013
%
%//////////////////////////////////////////////////////////////////////////

clear all;

% add paths for required files...
addpath('MATLAB/util/');

% SET THE GLIDER INDEX (Pelagia = 1, Ramses = 2) ...
for gliderIndex=1:2

    % SET THE DEPLOYMENT NUMBER (1, 2 or 3) ...
    for deploymentNumber=1:3
        
        clearvars -except gliderIndex deploymentNumber;

        % glider name string...
        if (gliderIndex==1)
            strGliderName = 'Pelagia';
        else
            strGliderName = 'Ramses';
        end
        
        disp(['Extracting DBDs for ', strGliderName, ' Deployment ', num2str(deploymentNumber)]);

        % populate arrays for the deployment start and end dates...
        % ex. strStart(2, 3) is start date for Ramses, Deployment 3
        strStart = {'26-Jan-2012', '16-Feb-2012', '16-Mar-2012'; '26-Jan-2012', '16-Feb-2012', '16-Mar-2012'};
        strEnd   = {'14-Feb-2012', '08-Mar-2012', '04-Apr-2012'; '14-Feb-2012', '12-Mar-2012', '03-Apr-2012'};

        % deployment number string...
        strDeploymentNumber = num2str(deploymentNumber);

        % deployment start date string...
        strStartDate = strStart(gliderIndex, deploymentNumber);

        % deployment end date string...
        strEndDate = strEnd(gliderIndex, deploymentNumber);

        % define the path to the glider ascii files...
        %datadir = strcat('/Users/haloboy/Documents/MASC/MATLAB/CTD_data_correction/GLIDER_CTD_DATA_LEVEL0/',...
        datadir = strcat('GLIDER_DATA_LEVEL0/', strGliderName, '_Deployment', strDeploymentNumber, '/');

        %##########################################################################################


        %*** READ IN DBD DATA *****************************************************
        % declare variables for storing data...
        ptime_dbd=[];
        altitude=[];
        horizontalVelocity=[];
        depth = [];
        pitch=[];
        avgDepthRate = [];
        angleOfAttack = [];

        % try to load all *.dbdasc files at once...
        [files, Dstruct] = wilddir(datadir, '.dbdasc');
        nfile = size(files, 1);

        clear data;

        for i=1:nfile
            % protect against empty dbd file
            if(Dstruct(i).bytes>0)
                data = read_gliderasc2([datadir, files(i,:)]);
                %data = read_gliderasc3([datadir, files(i,:)]);

                % if the number of values (in data.data) is less than the number of 
                % vars (in data.vars), this means that the data were not completely read
                % in.  To correct this, pad data.data with NaNs until its length
                % equals that of data.vars...
                if (length(data.data) < length(data.vars))
                    data.data = padarray(data.data, [0 length(data.vars)-length(data.data)], NaN, 'post');
                end

                % populate variables with data...
                if(~isempty(data.data))
                    ptime_dbd = [ptime_dbd; data.data(:,strmatch('m_present_time', data.vars, 'exact'))];
                    altitude = [altitude; data.data(:,strmatch('m_altitude', data.vars, 'exact'))];
                    horizontalVelocity = [horizontalVelocity; data.data(:,strmatch('m_speed', data.vars, 'exact'))];
                    depth = [depth; data.data(:,strmatch('m_depth', data.vars, 'exact'))];
                    pitch = [pitch; data.data(:,strmatch('m_pitch', data.vars, 'exact'))];
                    avgDepthRate = [avgDepthRate; data.data(:,strmatch('m_avg_depth_rate', data.vars, 'exact'))];
                    angleOfAttack = [angleOfAttack; data.data(:,strmatch('u_angle_of_attack', data.vars, 'exact'))];
                end

                data = [];
            end
        end
        %**************************************************************************


        [Y,I] = sort(ptime_dbd);
        ptime_dbd = Y;
        altitude = altitude(I);
        horizontalVelocity = horizontalVelocity(I);
        depth = depth(I);
        pitch = pitch(I);
        avgDepthRate = avgDepthRate(I);
        angleOfAttack = angleOfAttack(I);

        % convert pitch and angle of attack from radians to degrees...
        pitch = pitch*180/pi;
        angleOfAttack = angleOfAttack*180/pi;

        % % compute actual glide angle = pitch + angle of attack...
        % glideAngle = pitch + angleOfAttack;

        % convert ptime into datenum style...for plotting I think, commenting out
        % ptime_datenum = ptime/3600/24+datenum(1970, 1, 1, 0, 0, 0);
        ptime_datenum_dbd = ptime_dbd/3600/24+datenum(1970, 1, 1, 0, 0, 0);
        %ptimehrly = fix(ptime_datenum*24)/24;
        %ptimedaily = fix(ptime_datenum);
        %ptimedaily2 = unique(ptimedaily);
        %ptimedaily2 = ptimedaily2(1:2:end);

        % create configuration struct...
        units = struct('altitude', 'm',...
                       'angleOfAttack', 'decimal degrees',...
                       'avgDepthRate', 'm/s',...
                       'depth', 'm',...
                       'horizontalVelocity', 'm/s',...
                       'pitch', 'decimal degrees',...
                       'ptime_dbd', 'seconds since 0000-01-01T00:00',...
                       'ptime_datenum_dbd', 'days since 1970-01-01T00:00');

        variable_description = struct('altitude', 'altimeter measured distance from bottom',...
                                      'angleOfAttack', 'difference between pitch and glider angle',...
                                      'avgDepthRate', 'average rate of change of depth, >0 is down',...
                                      'depth', 'depth calculated as function of pressure and position latitude',...
                                      'horizontalVelocity', 'vehicle horizontal speed through water',...
                                      'pitch', 'vehicle angle of inclination, >0 is nose up',...
                                      'ptime_dbd', 'time vector reported by glider',...
                                      'ptime_datenum_dbd', 'Serial Date Number string');

        config = struct('glider_name', strGliderName,...
                        'deployment_number', strDeploymentNumber,...
                        'start_date', strStartDate,...
                        'end_date', strEndDate,...
                        'var_descriptions', variable_description,...
                        'var_units', units);

        % set Level 1 data mat file name...
        strMatFileName = strcat(strGliderName, '_Deployment', strDeploymentNumber, '_Flight_L1.mat');



        % save flight data to mat file...
        save(strMatFileName,...
             'config',...
             'altitude',...
             'angleOfAttack',...
             'avgDepthRate',...
             'depth',...
             'horizontalVelocity',...
             'pitch',...
             'ptime_dbd',...
             'ptime_datenum_dbd');

    end
end