% Created on 19/06/2018; Version 1.0
% Version 1.2; 26/06/2018
% Data used from load_E1_buoy_data.m function and datetime.m script

% Function to sort E1_buoy data using flags to identify outliers 
%      Based on the ODV data flagging system: 
%       0 = good quality data, using mean data
%       1 = poor quality data, using mean data
%       4 = questionable quality data due to high standard deviation 
%       8 = bad quality data, using mean data

% Function requires the input variables:
%       a - the mean data of parameter 
%       b - the standard deviation data of parameter
%       minVal - the minimum accepted mean value 
%       maxVal - the maximum accepted mean value 
%       diffp - the maximum difference 
%       SDmax - the maximum accepted standard deviation value 
    
% For function output use 'flag.variable' to save multiple variables into
% the same structure 

% Example: flag.sst = flag_E1(flag,data.Mnsst,data.SDsst,5,25,0.5,1)

%% 
function flag = flag_E1(flag,a,b,minVal,maxVal,diffp,SDmax)

% Create alternative flag matrix that is of equal size to the input
% parameter (a)
flag=[size(a)]

%i=1;
% Step through each value in turn and classify as within the
% accepted range or not; then assign '0' or '8' to show good or bad data
for i = 1:length(a);
    % Test if data point is in desired range (input minimum and maximum)
    if (a(i) >= minVal && a(i) <= maxVal);  
        disp ('0') % flag as good data
       % Add the assigned '0' value to the flag matrix
        flag(i)=0;
    % If the data point is outisde of the desired range then flag as 'bad'
    % data
    else (a(i) < minVal || a(i) > maxVal); 
        disp ('8') % flag as bad data
       % Add the assigned '8' value to the flag matrix
        flag(i)=8;
    end
     
    %i=i+1; % only increment the data counter if new data read in
end


% Step through varibale again looking for where there is a difference
% greater than 0.5 between the current data point and the previous one
%       Issues: potentially where there are gaps in the data set, could...
%       ...be an expected change in variable 
 for j = 2:length(a);  % start on second data point to enable difference to be calculated
     
    if (abs(a(j)-a(j-1))) > diffp; % the absolute difference from the last...
                                 % ...reading; corrects for answer being negative 
       disp ('1') % flag as poor data
       flag(j)=1;  % Add the assigned '1' value to the flag matrix
    end
    
 end
% abs(-0.5)=0.5; abs(0.5)=0.5;


% Loop through SD to identify where it is too high 
%     Loop uses 'data.SDsst' produced from 'load_E1_buoy_data.m'
for n = 1:length(b);
    
    if (b(n) > SDmax);  % Test size of standard deviation (SD)
        disp ('4') % flag as questionable data 
        flag(n)=4;  % Add the assigned '4' value to the flag matrix
    end 
    
end


    