function GenerateHtml
% GenerateHtml - Generates html documentation for the learning results.
%

% whether show bounding boxes for selected partial templates
boundSelectedParts = true;

% load the starting image number
load Config

% delete the previous version
html_dir = 'document/html';
if ~exist(html_dir,'dir')
    mkdir(html_dir);
else
%     rmdir(html_dir,'s');  % TODO: find out why removing existing dir causes error (in GenerateHtml.m) 
%     mkdir(html_dir);
end
imFolder = sprintf('exp1_%s',category);
html_path = sprintf('%s/%s.html',html_dir,imFolder);
html = fopen(html_path,'w');

html_img_dir = sprintf('document/html/%s/',imFolder);
if ~exist(html_img_dir,'dir')
    mkdir(html_img_dir);
end

%% html header
tmp = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n';
tmp = [tmp '<html>\n'];
tmp = [tmp '<head>\n'];
tmp = [tmp '<title>Learning active plate template</title>\n'];
tmp = [tmp '<link rel="stylesheet" href="http://www.stat.ucla.edu/~zzsi/plain_and_simple.css" type="text/css" media="screen" />\n'];
tmp = [tmp '<script type="text/javascript" src="http://www.stat.ucla.edu/~zzsi/1.js"></script>\n'];
tmp = [tmp '</head>\n'];
fprintf(html,tmp);
fprintf(html, '<body>\n');
fprintf( html, '<div id="header">\n');
fprintf( html, '<h1>Learning active plate template</h1></div>\n' );
fprintf( html, '\n<div id="content">\n');

%% link to project page
fprintf( html, '\n<p><a href="http://www.stat.ucla.edu/~zzsi/HAB/exp1.html">Exp1 home</a></p>\n' );

%% table of content
fprintf( html, '<div id="content">\n' );
fprintf( html, '<div id="TableOfContents">\n' );
fprintf( html, '<p>Contents</p>\n' );
fprintf( html, '<ul>\n' );
fprintf( html, '<li>\n' );
fprintf( html, '<A href="#download">Download</A>\n' );
fprintf( html, '</li>\n' );
fprintf( html, '<li>\n');
fprintf( html, '<a href="#traindata">Training examples</a>\n' );
fprintf( html, '</li>\n' );
fprintf( html, '<li>\n' );
fprintf( html, '<a href="#parts">Learned partial templates</a>\n' );
fprintf( html, '</li>\n' );
fprintf( html, '<li>\n' );
fprintf( html, '<a href="#matched">Shape matching by Active Plate</a>\n' );
fprintf( html, '</li>\n' );
fprintf( html, '</ul>\n' );
fprintf( html, '</div>\n' );

%% for download
fprintf( html, '<div style="border-bottom:1 solid #dddddd; margin-top:0.3em;"></div>\n' );
fprintf( html, '<a name="download"></a> <table cellspacing="10" cellpadding="10" class="center" width="60%%">\n' );
fprintf( html, '\n<tr><td>\n' );
fprintf( html, sprintf('\n<b>Code and data: (<a href="%s">ZIP</a>).</b>\n',zipfilename) );
fprintf( html, '\n</td>\n' );
fprintf( html, '\n<td>\n' );
fprintf( html, '\n<a href="http://www.stat.ucla.edu/~zzsi/HAB/Exp1/exp1_changelog.html">Change Log</a>\n' );
fprintf( html, '\n</td>\n' );
fprintf( html, '\n</tr>\n' );
fprintf( html, '\n<tr>\n' );
fprintf( html, '\n<td colspan=2 align=left>\n' );
fprintf( html, '\nThe code is modified from the newest implementation\n' );
fprintf( html, '\nof <a href="http://www.stat.ucla.edu/~ywu/AB/ABExp5.html">learning from non-aligned images</a>.\n' );
fprintf( html, '\nRun StartFromHere.m in matlab. To turn on the animation and monitor the intermediate results, set "GraphicsIsOn" to "true" or 1.\n' );
fprintf( html, '\n</td>\n' );
fprintf( html, '\n</tr>\n' );
fprintf( html, '\n</table>\n' );

%% training examples
fprintf(html, '<div style="border-top:1 solid #dddddd; margin-top:0.3em;"></div><h2> ');
fprintf(html, '<a name="traindata"></a>Training examples');
fprintf(html, ' </h2>');
fprintf( html, ['\n<p>Training examples are of different aspect ratios. We inscribe SUM1 maps '...
    sprintf('into a common square bounding box of size %d * %d pixels.', outerBBSize, outerBBSize)...
    sprintf(' Number of EM iterations = %d. Partial template size = %d by %d pixels. ',numIt,partSize,partSize) ...
    sprintf(' Each part is an active basis model of Gabor elements with local shift <= %d pixels, and orientation shift <= %d * PI/%d. ', locationShiftLimit, orientShiftLimit, numOrient) ...
    sprintf(' The lambda threshold for selected Gabor elements is set to %.2f. ', LambdaThreshold) ...
    ' </p>\n']);
% read the training examples
Iname = dir('positiveImage/*.jpg');
% move the images to img/ folder
for i = 1:length(Iname)
    new_img_name = Iname(i).name;
    src = sprintf('positiveImage/%s',new_img_name);
    dst = sprintf('document/html/%s/%s',imFolder, new_img_name);
    % copyfile(src,dst);
    im = imread(src);
    if size(im,3) == 3
    	newIm = zeros(outerBBSize,outerBBSize,3);
    	for c = 1:3
			newIm(:,:,c) = inscribe([outerBBSize,outerBBSize],im(:,:,c),255);
		end
		im = newIm;
	else
		im = inscribe([outerBBSize,outerBBSize],im,255);
		im = repmat(im,[1,1,3]);
	end
	im([1:5,end-4:end],:,:) = 0; im(:,[1:5,end-4:end],:) = 0;
	imwrite(uint8(im),dst);
end
% generate corresponding html
fprintf( html, '\n<p>' );
for i = 1:length(Iname)
    fprintf( html, '<img src="%s" alt="" height=50/>', sprintf('%s/%s',imFolder,Iname(i).name) );
end
fprintf( html, '\n</p>\n' );
% show the starting image
fprintf( html, sprintf('\n<h3> Learning from example %d</h3>\n', starting ) );
fprintf( html, '\n<p> The partial templates are initialized from the following example image. </p>' );
fprintf( html, '\n<p>' );
fprintf( html, '<img src="%s" alt="" height = 100 />', sprintf('%s/%s',imFolder,Iname(starting).name) );
fprintf( html, '\n</p> <p></p>\n' );


%% show learned candidate part templates, together with information gain
fprintf( html, ['<div style="border-bottom:1 solid #dddddd; margin-top:0.3em;"></div>\n <h2>Learned partial parts</h2> <a name="parts"></a><p>Learned final active basis templates' ...
    ' at overlapping subwindows. The number to the lower-left of each template' ...
    ' is the average MAX2 score of the plate (partial template) evaluated on image examples.' ...
    ' The color of the partial template indicates its information gain as the "hotness" measure. '] );
if boundSelectedParts
    fprintf( html, ...
        ['The Active Plate template is composed of selected partial templates with high information gains.' ...
        ' They are indicated by bounding boxes. ' ]);
end
fprintf( html, '</p>\n\n<p>' );

% find the range of average MAX2 score
MAX2 = zeros(length(PartLocX),length(PartLocY));
for ix = 1:length(PartLocX)
    for iy = 1:length(PartLocY)
        load( sprintf('working/LearnedPart_%d_%d',PartLocX(ix),PartLocY(iy)), 'aveMAX2score' );
        MAX2(ix,iy) = aveMAX2score;
    end
end
max_MAX2 = max(MAX2(:));
lowerbound_proportion = .6;
lowerbound_MAX2 = max_MAX2 * lowerbound_proportion;

% dipslay the color legend indicating "hotness" of partial templates
im = zeros(20,500,3);
for j = 1:size(im,2)
	s = j / size(im,2);
	[r g b] = hotness(s);
	im(:,j,1) = r; im(:,j,2) = g; im(:,j,3) = b;
end
legendFileName = 'ColorLegend.png';
imwrite(uint8(im),sprintf('document/html/%s/%s',imFolder,legendFileName));
fprintf( html, '\n <p> low <img src="%s" alt="color legend" width = 500/> high </p>', ...
    sprintf('%s/%s',imFolder,legendFileName) );

load working/partOnOff
count = 0;
for ix = 1:length(PartLocX)
    for iy = 1:length(PartLocY)
        count = count + 1;
    	aveMAX2score = MAX2(ix,iy);
        fprintf( html, '%.1f', aveMAX2score );
        % move the result image to /img
        new_img_name = sprintf('template_iter3_part%d_%d.png',PartLocX(ix),PartLocY(iy));
        src = sprintf('./%s',new_img_name);
        dst = sprintf('document/html/%s/%s', imFolder,new_img_name);
        im = imread(src);
        mask = im(:,:,1) < 255;
		if size(im,3) == 1
			im = repmat(im,[1,1,3]);
		end
		im = double(im);
		
		% apply a custom color to it
		ind = ( max(aveMAX2score,lowerbound_MAX2) - lowerbound_MAX2 ) / (max_MAX2 - lowerbound_MAX2);
		tmp = im(:,:,1);
		[r g b] = hotness(ind);
		tmp(mask) = r;
		im(:,:,1) = tmp; % red
		tmp(mask) = g;
		im(:,:,2) = tmp; % green
		tmp(mask) = b;
		im(:,:,3) = tmp; % blue
        
        % add a bounding box if it is selected
        if boundSelectedParts && partOnOff(count) > 0
            im([1:3,end-2:end],:,:) = 100; im(:,[1:3,end-2:end],:) = 100;
        end
		
		imwrite(uint8(im),dst);
        fprintf( html, '\n<img src="%s" alt="" height=80/>', sprintf('%s/%s',imFolder,new_img_name) );
    end
    fprintf( html, '\n<br />\n\n' );
end
fprintf( html, '\n</p>\n' );


%% matched active plate template (SUM3 templates)
fprintf( html, ['<div style="border-top:1 solid #dddddd; margin-top:0.3em;"></div>\n<a name="matched"></a>' ...
    '\n <h2>Shape matching by Active Plate</h2> \n <p> An active plate template is ' ...
    'composed of a small number of selected partial templates (plates) with high information gain.' ... 
    'The following pairs of images show the matched Active Plate templates' ...
    ' on example images. </p>\n']);
fprintf( html, '\n<p>' );
% move the images to img/ folder
for i = 1:length(Iname)
    new_img_name = sprintf('matchedS3T%d.png',i);
    src = sprintf('output/%s',new_img_name);
    dst = sprintf('document/html/%s/%s',imFolder, new_img_name);
    copyfile(src,dst);
end
% generate corresponding html
fprintf( html, '\n<p>' );
numCol = 4;

for i = 1:length(Iname)
    fprintf( html, '<img src="%s" alt="" height=80/>', sprintf('%s/%s',imFolder,Iname(i).name) );
    fprintf( html, '<img src="%s" alt="" height=80/>\n', sprintf('%s/%s',imFolder,sprintf('matchedS3T%d.png',i)) );
    if rem(i,numCol) == 0
    	fprintf( html, '<br />\n' );
    end
end
fprintf( html, '\n</p>\n' );


%% finishing off
fprintf( html, '\n\n\n</div> \n');
fprintf( html, '<div id="last" class="footer"></div>' );
fprintf(html, '</body> </html> \n');
fclose(html);
disp('finished generating Html.. check here:');
disp([pwd '/' html_path]);

%
%% Tool: color map
%
function [r g b] = hotness(s)
r = 200 + 50 * s;
g = 100 + 150 * (1-s);
b = 100 + 150 * (1-s);
