function [ goes_out ] = monotonic( goes_in )

% monotonic:  Assures an vector either increases or decreases monotonically.
%   First figures out if the array mostly increases or decreases.
%   Then the function finds elements that 'go the wrong way' and turn them
%   to NaNs.
%
% J. G. Bellingham
% Feb 16, 2014

% First remove nans...
temp = goes_in;
goes_in = goes_in(~isnan(goes_in));

% Figure out if vector mostly
delta = diff(goes_in);
up = sum(delta > 0);
down = sum(delta < 0);
goes_out = goes_in;

if up > down
    bad = find(delta <= 0);
    index = 1:length(goes_in);
    ok = 1 + index *0;
    
    if length(bad) > 0
        for i = 1:length(bad)
            ok(find((goes_in <= goes_in(bad(i))) & (index > bad(i)))) = 0;
        end;
        goes_out(~ok) = NaN;
    end;
else
    bad = find(delta > 0);
    index = 1:length(goes_in);
    ok = 1 + index *0;
    
    if length(bad) > 0
        for i = length(bad)
            ok(find((goes_in >= goes_in(bad(i))) & (index > bad(i)))) = 0;
        end;
        goes_out(~ok) = NaN;
    end;
end;

% Now put back in original array (remember, had to store a version that had
% NaNs in it...

temp(~isnan(temp)) = goes_out;
goes_out = temp;
