function varargout = LabBook(varargin)
%The labbook takes screenshots of the current matlab figure and generates
%html to display a collection of shots + annotations.
%
% LM:   4 Feb 2008   KU    Fixed distortion in screenshot thumbnails (function 'smartresize')
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
% 
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
% 
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
% 
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
% 
% CERR is distributed under the terms of the Lesser GNU Public License. 
% 
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
% 
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

persistent lastCapturedImageName;
persistent currentLabBook;

thumbnailWidth = 300;

if(nargin > 0)
	switch(upper(varargin{1}))
        
        case 'CAPTURE' %Capture passed figure, thumbnail and return both, [image, thumb]
            if(nargin > 1)
                figToCapture = varargin{2};
                F = getframe(figToCapture);               
                [y,x,color] = size(F.cdata);
                resizeFactor = thumbnailWidth/x;
                thumb = F;
                thumb.cdata = imresize(F.cdata,resizeFactor,'nearest');
                varargout{1} = F;
                varargout{2} = thumb;
                return;
            else
                error('LabBook: No figure specified.');
            end            
            
        case 'SAVE' %Save the passed image, thumbnail, and annotation to the passed filename, with the proper extentions.
            if(nargin == 5)
                if ~exist (currentLabBook,'dir')
                    error('LabBook: Specified LabBook Directory does not exist');
                    return;
                end
                large = varargin{2};
                thumb = varargin{3};
                imageName = varargin{4};
                annotation = varargin{5};
                filename = fullfile(currentLabBook, imageName);
                imwrite(large.cdata, [filename '.png'], 'png');
        %        imwrite(thumb.cdata, [filename 'Thumb' '.png'], 'png');                
                fid = fopen([filename '.txt'],'w');
                fwrite(fid, annotation, 'char');
                fclose(fid);    
                varargout{1} = [filename '.png'];
            else
                error('LabBook: Improper Number of Arguments');
            end
            
        case 'ANNOTATE' %Annotate figure stored in filename with text in annotation.  LabBook('Annotate', filename, annotation);
            if(nargin > 1)
                filename = varargin{2};
            else
                filename = lastCapturedImageName
            end
            
            if(nargin > 2)
                annotation = varargin{3};
            else
                error('No annotation specified.');
            end            
            fid = fopen([filename '.txt'],'w');
            fwrite(fid, annotation, 'char');
            fclose(fid);                                                               
                                                
        case 'GENERATEREPORT' %generate an html report
            %Ideas: an Index.html page, using thumbs, 3x2 per page
            %w/scrolling, to display all possible images.  Thumbs are
            %linked to the corresponding large images.  When large images
            %is called up, txt from annotation report is displayed in a
            %frame at bottom of doc.
            if isempty(currentLabBook)
                currentLabBook = fullfile(getCERRPath, 'LabBook', 'Default');
            end
            fid = fopen(fullfile(currentLabBook, 'index.html'), 'w');
            %html = ['<html><head><script language=''javascript''>function display(num) { thumbs.style.display = ''none'';   document.getElementById(''demoName'').src =  aImage[num] + ''.png'';   demo.style.display = ''inline'';   demoText.innerHTML = aAnnot[num]; }  function hideDemo() { 	thumbs.style.display = ''inline'';   demo.style.display = ''none''; } </script> </head> <body> <div id=''thumbs'' style=''display:inline''> <table> <tr> <script language=''javascript''> '];

            
            %%%%%%%%%%%%%%%%
            html = ['<html>\r'...
					'<head>\r'...
					'<title>Screenshots</title>\r'...
					'<style>\r'...
						'.imageBorder {border-style:solid;border-width:1px;border-color:#666666}\r'...
						'.fileName {font-weight:normal;font-family:verdana;font-size:10px}\r'...
						'.shortAnnot {font-weight:normal;font-family:verdana;font-size:10px}\r'...
						'.longAnnot {font-weight:normal;font-family:verdana;font-size:10px;display:inline}\r'...
						'.bodyMain {background-color:#6699CC}\r'...
						'A {color:#0066FF;text-decoration:none;font-weight:bold;font-family:verdana;font-size:10px}\r'...
						'A:hover {color:#0066FF;text-decoration:underline}\r'...
					'</style>\r'...
					'<script language=''javascript''>\r'...
                    'function smartresize(img, size)\r'...
                    '{\r'...
                    '	if (img.width >= img.height)\r'...
					'	{\r'...
                    '       img.width = size;\r'...
                    '	}\r'...
					'	else if (img.width < img.height)\r'...
					'	{\r'...
                    '       img.height = size;\r'...
                    '	}\r'...
                    '}\r'...
                    'function display(num)\r'...
					'{\r'...
						'var nextNum = parseFloat(num);\r'...
						'var prevNum = parseFloat(num);\r'...
						'nextNum++;\r'...
						'prevNum--;\r'...
						'document.getElementById(''thumbs'').style.display = ''none'';\r'...
						'document.getElementById(''demoName'').src =  aImage[num] + ''.png'';\r'...
						'document.getElementById(''demo'').style.display = ''inline'';\r'...
						'document.getElementById(''demoText'').innerHTML = aAnnot[num];\r'...
						'document.getElementById(''demoFile'').innerHTML = aImage[num] + ''.png'';\r'...
						'document.getElementById(''nextLink'').href = ''javascript:display('' + nextNum + '')'';\r'...
						'document.getElementById(''prevLink'').href = ''javascript:display('' + prevNum + '')'';\r'...
						'if (nextNum >= aImage.length)\r'...
						'{\r'...
						'	document.getElementById(''nextLink'').innerHTML = '' '';\r'...
                        '}\r'...
                        'else\r'...
						'{\r'...
						'	document.getElementById(''nextLink'').innerHTML = ''Next'';\r'...
                        '}\r'...
						'if (prevNum < 0)\r'...
						'{\r'...
						'	document.getElementById(''prevLink'').innerHTML = '' '';\r'...
                        '}\r'...
                        'else\r'...
						'{\r'...
						'	document.getElementById(''prevLink'').innerHTML = ''Prev'';\r'...
                        '}\r'...
                        '}\r'...
					'function hideDemo()\r'...
					'{\r'...
                    '   document.getElementById(''thumbs'').style.display = ''inline'';\r'...
                    '  document.getElementById(''demo'').style.display = ''none'';\r'...
                    '}\r'...
					'</script>\r'...
					'</head>\r'...
					'<body class=''bodyMain''>\r'...
					'<div id=''thumbs'' style=''display:inline''>\r'...
					'<table cellspacing=''5''>\r'...
					'<!--- <tr><td class=''fileName''><a href=''''>Next</a> <a href=''''>[01]</a> <a href=''''>02</a> <a href=''''>03</a> <a href=''''>04</a> <a href=''''>05</a> <a href=''''>Prev</a></td></tr> -->\r'...
					'<tr>\r'...
					'<script language=''javascript''>'];
            %%%%%%%%%
            
            fprintf(fid, html, 'char');           
          
            aImage = ['aImage = ["'];
            aAnnot = ['aAnnot = ["'];
            aAnnotShort = ['aAnnotShort = ["'];
            directoryContents = dir(fullfile(currentLabBook, '*.txt'));
            [temp, dateOrder] = sort(datenum({directoryContents.date}));
           
            for j=1:length(directoryContents)
                i = dateOrder(j);
                myString = directoryContents(i).name;
                if j == 1
                    aImage = [aImage  myString(1:length(myString)-4)];
                else
                    aImage = [aImage '","' myString(1:length(myString)-4)];
                end
                
                tempfid = fopen(fullfile(currentLabBook, myString),'r');
                rawText = fread(tempfid);
                fclose(tempfid);
                annotation = char(rawText');
                if j == 1
                    aAnnot = [aAnnot annotation];
                    aAnnotShort = [aAnnotShort annotation(1:min(40, length(annotation)))];
                else
                    aAnnot = [aAnnot '","' annotation];
                    aAnnotShort = [aAnnotShort '","' annotation(1:min(40, length(annotation)))];
                end
            end
            aAnnot = [aAnnot '"]; '];
            aImage = [aImage '"]; '];
            aAnnotShort = [aAnnotShort '"]; '];
            
            fprintf(fid, aAnnot, 'char');           
            fprintf(fid, aImage, 'char');           
            fprintf(fid, aAnnotShort, 'char');           
            
            %%%%%%%%%%
            html = ['document.write(''<tr>'');\r'...
					'for (var i = 0; i < (aImage.length); i = i + 1)\r'...
					'{\r'...
					'	if (i %% 3 == 0)\r'...
					'	{\r'...
					'		document.write(''</tr><tr>'');\r'...
                    '	}\r'...
					'	document.write("<td valign=''middle''><table class=''imageBorder''><tr><td height=''300'' width=''300'' align=''center''>");\r'...
					'	var img = new Image();\r'...
					'	img.src = aImage[i] + ".png";\r'...
					'	document.write("<a href=javascript:display(''" + i + "'')><img onload=''smartresize(this,300)'' src=''" + aImage[i] + ".png'' border=''0'' alt=''Enlarge image''></td></tr></table><center><a href=javascript:display(''" + i + "'')>" + aImage[i] + ".png</a><br><div class=''shortAnnot''>" + aAnnotShort[i] + "</div></center><br>");\r'...
					'	document.write(''</td>'');\r'...
                    '}\r'...
					'document.write(''</tr>'');\r'...
				'</script>\r'...
				'</tr>\r'...
				'</table>\r'...
				'</div>\r'...
				'<div id=''demo'' style=''display:none'' class=''longAnnot''>\r'...
				'	<center>\r'...
				'	<table border=''0'' width=''50%%''><tr><td align=''left'' width=''70''><a href=''javascript:hideDemo()''>Back</a></td><td align=''center''><div id=''demoFile'' class=''fileName''>Filename</div></td><td align=''right'' width=''70''><a id=''prevLink'' href=''javascript:display("")''>Prev</a> <a id=''nextLink'' href=''javascript:display("")''>Next</a></td></tr></table>\r'...
				'	<br>\r'...
				'	<a href=javascript:hideDemo()><img id=''demoName'' src=''CERR.png'' border=''0'' alt=''Back to thumbs''></a>\r'...
				'	<br><br><b>Comment:  </b>\r'...
				'	<div id=''demoText'' class=''longAnnot''></div></center>\r'...
				'</div>\r'...
				'</body>\r\'...
				'</html>'];
        
       %%%%%%     
            
            fprintf(fid, html, 'char');
%            fprintf(fid, ['   document.write(''<tr>'');for (var i = 0; i < (aImage.length); i = i + 1){	if (i %% 3 == 0)	{ 			document.write(''</tr><tr>'');   	}	document.write(''<td valign="middle">'');	document.write("<a href=javascript:display(''" + i + "'')><img src=''" + aImage[i] + "Thumb.png'' border=''0''><br><center>" + aImage[i] + ".png</center></a>");	document.write(''</td>'');}document.write(''</tr>'');</script></tr></table></div><div id=''demo'' style=''display:none''><center> <a href=javascript:hideDemo()><img id=''demoName'' src=''CERR.png'' border=''0''><br><div id=''demoText''>Caption</div></a> </center> </div>  </div> </body> </html>']);
            fclose(fid);           
            
        case 'DISPLAYREPORT'
            web(fullfile(currentLabBook, 'index.html'), '-browser');
            
        case 'GETCURRENTBOOK'
            if isempty(currentLabBook) | ~exist(currentLabBook,'dir')
                currentLabBook = fullfile(getCERRPath, 'LabBook', 'Default', '');
                [success,msg,msgid] = mkdir(fullfile(getCERRPath, 'LabBook', ''), 'Default');
                if ~success
                    error('Unable to create default labbook directory.');    
                end
            end
            varargout{1} = currentLabBook;
            return;
        case 'SETCURRENTBOOK'
            if(nargin > 1)
                currentLabBook = varargin{2};
            else
                error('No Book specified');
            end
            return;
        case 'CHECKDIRECTORY'
            if(nargin == 2)
                if(~exist(varargin{2}, 'dir'))
                    error('Specified LabBook Directory does not exist');
                end
            else
                error('Incorrect number of checkdirectory Parameters');
            end
	end
else
    warning('not enough parameters');
end
