function OutputActiveBasisTemplate(category)
% OutputActiveBasisTemplate - Generates figures and captions.
%

% load the template
matFile = sprintf('result/%s/activebasis_model.mat',category);
load(matFile,'sym','Asym','SUM2score');
templateSize = size(sym);
sizex = templateSize(1); sizey = templateSize(2);
deformedTemplate = Asym;

% load example images
rootFolder = pwd;
imageNames = [];
imageNames = [imageNames; dir(sprintf('%s/image/%s/*.jpg',rootFolder,category))];
imageNames = [imageNames; dir(sprintf('%s/image/%s/*.bmp',rootFolder,category))];
imageNames = [imageNames; dir(sprintf('%s/image/%s/*.png',rootFolder,category))];
numImage = length(imageNames);
I = cell(numImage,1);
for i = 1:numImage
    I{i} = imread( sprintf('%s/image/%s/%s',rootFolder,category,imageNames(i).name) );
    if size(I{i},3) == 3
        I{i} = rgb2gray(I{i});
    end
    I{i} = double(imresize(I{i},templateSize,'nearest'));
end

K = numImage; bx = 10; by = 10; cc = 3;  
[SUM2scoresort, ind] = sort(SUM2score); 
col = 5; row = floor(K/col)+1;
Iout = zeros(row*sizex+(row-1)*(2*bx+cc), 2*col*sizey+(col-1)*(2*by+cc))+255; 
towrite =  -sym; 
towrite = (255 * (towrite-min(towrite(:)))/(max(towrite(:))-min(towrite(:))));
Outepspng(towrite, sprintf('%s/result/%s/activebasis_template', rootFolder, category));
Iout(1:sizex, 1:sizey) = towrite;
i = -1;
for r = 1 : row
    for c = 1 : col
        i = i+1; 
        if ((i>=1)&&(i<=K))
            towrite = I{ind(numImage-i+1)}; 
            towrite = (255 * (towrite-min(towrite(:)))/(max(towrite(:))-min(towrite(:))));
            Iout((r-1)*sizex+1+(r-1)*(2*bx+cc): r*sizex+(r-1)*(2*bx+cc), (c-1)*2*sizey+1+(c-1)*(2*by+cc): (c-1)*2*sizey+sizey+(c-1)*(2*by+cc)) = towrite; 
            towrite =  -(deformedTemplate{ind(numImage-i+1)}); 
            towrite = (255 * (towrite-min(towrite(:)))/(max(towrite(:))-min(towrite(:))));
            Iout((r-1)*sizex+1+(r-1)*(2*bx+cc) : r*sizex+(r-1)*(2*bx+cc), (c-1)*2*sizey+sizey+(c-1)*(2*by+cc)+1 : (c-1)*2*sizey+sizey+(c-1)*(2*by+cc)+sizey) =towrite;  
        end
    end
end
for r = 1 : row-1
  Iout(r*sizex+(r-1)*(2*bx+cc)+bx+1:r*sizex+(r-1)*(2*bx+cc)+bx+cc, :) = 0; 
end
for c = 1 : col-1
  Iout(:, c*(sizey*2)+(c-1)*(2*by+cc)+by+1:c*(sizey*2)+(c-1)*(2*by+cc)+by+cc) = 0; 
end
Outepspng(Iout, sprintf('%s/result/%s/activebasis_figure', rootFolder, category));

