function newqual = utQualityVector(tsin,dataout,t,varargin)
%

%   Author(s): James G. Owen
%   Copyright 1986-2004 The MathWorks, Inc.
%   $Revision: 1.1.6.1 $ $Date: 2004/12/26 21:35:28 $

%% Utility method which generates a modified quality vector for methods
%% which modify the data and/or time vectors. The 4th optional argument is
%% a quality code which will be used to denote any observations which have
%% been modifed. Observations are considered modfied if either the data is
%% changed or if a new point is added. If no 4th argument is specified and
%% observations are added the quality vector will be cleared, otherwise its
%% length will be adjusted corresponding to any deleted points.

%% Has a modified quality code been specified
if nargin>=4
    modcode = varargin{1};
else
    modcode = [];
end

%% New time points
[commonT,indout,indin] = intersect(t,tsin.Time);

%% Since the time vector has changed the quality vector needs to be
%% updated. 
newqual = [];
if ~isempty(tsin.Quality)
    % If new time points have been created, delete the quality vector
    if isempty(modcode) 
        if any(setdiff((1:length(t))',indout))
            newqual = [];
        else
            newqual = tsin.Quality(indin);
        end   
    % If new time points have been created, set the quality vector to
    % modcode
    else
        newqual = modcode*ones([length(t) 1]);
        newqual(indout) = tsin.Quality(indin);
    end
end

%% Update the quality vector 
if ~isempty(modcode)    
    % Find the observation indices of data at unodified times which has
    % changed
    I = [];
    if ~isempty(commonT)
        % Get the modified and original data as a 2d matrix
        sout = size(dataout);
        sin = size(tsin.data);
        % dataout and data have the same # of columns
        if tsin.dataInfo.GridFirst || ndims(tsin.data)<=2
            yout = dataout(indout,:);
            yin = tsin.data(indin,:);
        else
            yout = reshape(dataout,[prod(sout(1:end-1)) sout(end)]);
            yin = reshape(tsin.data,[prod(sin(1:end-1)) sin(end)]);
            yout = yout(:,indout);
            yin = yin(:,indin);
        end

        % Find which observations have changed
        if isvector(yout)
            I = isnan(yin) | abs(yout-yin)>eps;
        else
            if tsin.dataInfo.GridFirst
                I = any((isnan(yin) | abs(yout-yin)>eps )');
            else
                I = any(isnan(yin) | abs(yout-yin)>eps);
            end
        end
        
        % Find observations that have either had the  data has changed
        newqual(indout(I)) = modcode;
    end
end