function [ObjectClassMasks, ObjectInstanceMasks, PartsClassMasks, PartsInstanceMasks, objects, parts] = loadAde20K(file)
%
% [ObjectClassMasks, ObjectInstanceMasks, PartsClassMasks, PartsInstanceMasks, objects, parts] = loadAde20K(filename);
% 
% ObjectClassMasks
% ObjectInstanceMasks
% PartsClassMasks
% PartsInstanceMasks
% objects
% parts


fileseg = strrep(file,'.jpg', '_seg.png');

% Read object masks
seg = imread(fileseg);

R = seg(:,:,1);
G = seg(:,:,2);
B = seg(:,:,3);

ObjectClassMasks = (uint16(R)/10)*256+uint16(G);
[~,~,Minstances_hat] = unique(B(:));
ObjectInstanceMasks = reshape(Minstances_hat-1,size(B));

if nargout>2 || nargout==0
    % Read part masks
    file_parts = strrep(file,'.jpg', '_parts.png');
    partsseg = imread(file_parts);
    R = partsseg(:,:,1);
    G = partsseg(:,:,2);
    B = partsseg(:,:,3);
    PartsClassMasks = (uint16(R)/10)*256+uint16(G);
    [~,~,Minstances_hat] = unique(B(:));
    PartsInstanceMasks = reshape(Minstances_hat-1,size(B));
end

if nargout>4
    % Read attributes
    % format: '%03d; %s;  %d; %s; "%s"\n', instance, name, whole(j)==0, crop, atr
    fid = fopen(strrep(file, '.jpg', '_atr.txt'), 'r');
    if fid>-1
        C = textscan(fid, '%s', 'Delimiter', ';');
        fclose(fid);
        C = C{1};
        C = reshape(C, [5 length(C)/5])';
        
        instance = str2num(cell2mat(C(:,1)));
        names = C(:,2);
        ispart = str2num(cell2mat(C(:,3)));
        iscrop = str2num(cell2mat(C(:,4)));
        listattributes = strrep(C(:,5), '"', '');
        
        objects.instancendx = instance(ispart==0);
        objects.class = names(ispart==0);
        objects.iscrop = iscrop(ispart==0);
        objects.listattributes = listattributes(ispart==0);
        
        parts.instancendx = instance(ispart==1);
        parts.class = names(ispart==1);
        parts.iscrop = iscrop(ispart==1);
        parts.listattributes = listattributes(ispart==1);
    else
        objects = [];
        parts = [];
    end
end
    
if nargout == 0
    figure
    subplot(221)
    imshow(ObjectClassMasks, []);
    title('Object class')
    subplot(222)
    imshow(ObjectInstanceMasks, []);
    title('Instances')
    subplot(223)
    imshow(PartsClassMasks, []);
    title('Part class')
    subplot(224)
    imshow(PartsInstanceMasks, []);
    title('Part Instance')
    colormap(cat(1, [0 0 0], hsv(255)))
end
