function nfdata = make_nfdata (varargin)
% nfdata = make_nfdata (data)
% make_nfdata (data1[, data2[, ...]])
%
% The first form takes in the sequences and measurements data, and returns
% a copy that keeps only the non-flagged data points.
%
% The second form looks at the names of the inputs, and for each of them,
% creates a different variable, with the letters 'nf' prepended to the
% name. It then keeps only those measurements and sequences that are
% unflagged and non-zero in all the datasets.

if nargin < 1
    disp ('Nothing to do.');
    return;
end

if nargout == 1
    data = varargin{1};
    nfdata = data;
    if isfield (data, 'flags')
        flags = data.flags==0;
        nfdata.seqs = data.seqs (flags, :);
        nfdata.nseqs = data.nseqs (flags, :);
        nfdata.measurements = data.measurements (flags, :);
        nfdata = rmfield (nfdata, 'flags');
    end
else
    n = length (varargin);
    flags = ones (length (varargin{1}.measurements), 1);
    for i = 1:n
        if (isfield (varargin{i}, 'flags'))
            flags = bitand (flags, varargin{i}.flags==0);
        end
    end
    evalin ('base', ['tmp_make_nfdata__flags = logical(' mat2str(flags) ');']);
    for i = 1:n
        data_name = inputname (i);
        nfdata_name = ['nf' data_name];
        evalin ('base', [nfdata_name '.seqs = ' data_name '.seqs (tmp_make_nfdata__flags, :);']);
        evalin ('base', [nfdata_name '.nseqs = ' data_name '.nseqs (tmp_make_nfdata__flags, :);']);
        evalin ('base', [nfdata_name '.measurements = ' data_name '.measurements (tmp_make_nfdata__flags);']);
    end
    evalin ('base', 'clear tmp_make_nfdata__flags');
end

end