function [hasparts, ispartof, recursiveparts, recursiveparents] = findparts(annotation,j)
%
% [hasparts, ispartof, recursiveparts, recursiveparents] = findparts(annotation,j)
%   hasparts, ispartof are the fields of the object.
%   recursiveparts returs the full list of parts going down the part tree.
% 
%   hasparts, ispartof and recursiveparts are object IDs.
% 
%   use id2ndx(annotation, hasparts)) to transform in annotation struct indices.

% Get IDs of non-deleted objects (objects can be deleted or disapear due to
% several reasons. For instance using the function LMquery can make some
% objects to be removed. LMquery does not modify the hasparts and the
% ispartof fields. This can create some inconsistency).

annotation_id = [annotation.object.id];
annotation_del = str2num([annotation.object.deleted]');

valid_ids = annotation_id(annotation_del==0);

hasparts = [];
ispartof = [];
recursiveparts = [];
recursiveparents = [];

if isfield(annotation.object(j), 'parts')
    if isfield(annotation.object(j).parts, 'hasparts')
        hasparts = str2num(annotation.object(j).parts.hasparts);
        hasparts = intersect(hasparts, valid_ids);
        hasparts = setdiff(hasparts, annotation.object(j).id);
    end
    if isfield(annotation.object(j).parts, 'ispartof')
        ispartof = str2num(annotation.object(j).parts.ispartof);
        ispartof = intersect(ispartof, valid_ids);
        ispartof = setdiff(ispartof, annotation.object(j).id);
    end
end


if nargout>2
    recursiveparts = hasparts;
    n = id2ndx(annotation, hasparts);
    
    for i = 1:length(n)
        [~, ~, recursiveparts_i] = findparts(annotation,n(i));
        recursiveparts = [recursiveparts, recursiveparts_i]; 
    end
end

if nargout>3
    recursiveparents = ispartof;
    n = id2ndx(annotation, ispartof);
    
    for i = 1:length(n)
        [~, ~, ~, recursiveparents_i] = findparts(annotation,n(i));
        recursiveparents = [recursiveparents_i, recursiveparents]; 
    end
end

%     
% id = [];
% jp = [];
% if isfield(annotation,'object') && isfield(annotation.object(j),'id')
%     id = annotation.object(j).id;
% end
% 
% if ~isempty(id) && isfield(annotation.object,'partof')
%     parts = str2double({annotation.object(:).partof});
%     jp = find(parts==str2double(id));
% end
