function demo2D01( option, param )
% demo2D01
%
% Trains a 2D generative model of protein location using the 2D HeLa dataset provided
% by the Murphy Lab at http://murphylab.web.cmu.edu/data/

% Author: Ivan E. Cao-Berg (icaoberg@scs.cmu.edu)
%
% Copyright (C) 2013-2015 Murphy Lab
% Lane Center for Computational Biology
% School of Computer Science
% Carnegie Mellon University
%
% This program 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 2 of the License,
% or (at your option) any later version.
%
% This program 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 this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA.
%
% For additional information visit http://murphylab.web.cmu.edu or
% send email to murphy@cmu.edu

%% preprocessing
%icaoberg
directory = what('demo2D01');
if isfield( directory, 'path' )
    directory = directory.path;
end
cd( directory );

clc;

if nargin == 0
    fprintf(1,'%s\n', 'demo2D01 - Train a 2D generative model' );
    fprintf(1,'%s\n%s\n%s\n%s\n%s\n', 'Select a dataset to download','(1) LAMP2', '(2) Mit', '(3) Nuc', '(4) TfR' );
    option = input('? ');
    param = struct([]);
elseif nargin == 1
    param = struct([]);
elseif nargin > 2
    error( 'Wrong number of input arguments' );
end

switch option
    case 1
        pattern = 'lam';
        directory = [ pwd filesep 'LAM' ];
    case 2
        pattern = 'mit';
        directory = [ pwd filesep 'Mit' ];
    case 3
        pattern = 'nuc';
        directory = [ pwd filesep 'Nuc' ];
    case 4
        pattern = 'tfr';
        directory = [ pwd filesep 'TfR' ];
    otherwise
        warning( 'CellOrganizer: Unknown option.' );
        return
end

% other options
% -------------
% these are optional flags that will help you debug cellorganizer
% verbose (optional) Displays messages to screen. The default is true.
param = ml_initparam( param, ...
    struct( 'verbose', true ) );

% debug (optional) Reports errors and warnings. Default is false.
param = ml_initparam( param, ...
    struct( 'debug', true ) );

% display (optional) Reports errors and warnings. Default is false.
param = ml_initparam( param, ...
    struct( 'display', false ) );

%% continuous integration flags
% ----------------------------
% these flags are optional and are not part of cellorganizer. these are
% simply tools that will help you understand how cellorganizer works based
% on your intermediate results, final results as well as output

%set this to true if you want the training component of the demo to run.
param = ml_initparam( param, ...
    struct( 'train', true ) );

%set this to true if you want the demo to synthesize images from the model
%trained using the training component
param = ml_initparam( param, ...
    struct( 'synthesize', false ) );

%set this to true if you want to make pretty pictures of the outputs
%produced by cellorganizer
param = ml_initparam( param, ...
    struct( 'postprocessing', false ) );

%set this to true if you want matlab to profile the demo
param = ml_initparam( param, ...
    struct( 'profile', false ) );

%% training component: main call to img2slml
if param.train
    tarball = [ 'hela2d-' pattern '.tgz' ];
    url = 'http://murphylab.web.cmu.edu/data/Hela/2D/';
    
    if ~exist( [ pwd filesep tarball ] )
        disp('Downloading dataset');
        urlwrite( [ url tarball] , tarball );
        disp('Extracting files');
        untar( [ pwd filesep tarball ] );
    else
        disp('Pattern found on disk. Extracting files from existing tarball');
        disp('Extracting files');
        system(['tar -xvf ./' tarball] );
    end
    
    dna = [ directory filesep 'orgdna' filesep '*.tif' ];
    cellm = [ directory filesep 'orgcell' filesep '*.tif' ];
    protein = [ directory filesep 'orgprot' filesep '*.tif' ];
    
    %main difference between this demo and demo2D01
    param.masks = [ directory filesep 'crop' filesep '*.tif' ];
    
    param.model.filename = 'model.xml';
    param.model.resolution = [ 0.49, 0.49 ];
    
    param.model.name = 'demo2D01';
    param.model.id = 'demo2D01';
    
    param.train.flag = 'all';
    param.synthesis = 'all';
    
    %documentation
    param.documentation.description = 'This model has been trained using demo2D01 from CellOrganizer';
    
    param.threshmeth_dna = 'rc'; 
    
    %COMMENT: this is the main method for training a model
    img2slml( '2D', dna, cellm, protein, param );
    
    %copy the trained model into the next demo
    try
        copyfile( [ pwd filesep '*.mat' ], '../demo2D02/' );
    catch
        warning( 'Unable to copy file to demo2D02 folder' )
    end
else
    disp( 'Training flag set to false. Skipping training' );
end

%% synthesis component: main call to slml2img
if param.synthesize
    %try to synthesize images from model
    try
        state = rng(3);
    catch
        state = RandStream.create('mt19937ar','seed', 11);
        RandStream.setDefaultStream(state);
    end
    
    outputDirectory = [ pwd filesep 'synthesizedImages' ];
    param.targetDirectory = outputDirectory;
    param.prefix = 'images';
    
    param = ml_initparam( param, ...
        struct( 'numberOfSynthesizedImages', 100 ) );
    
    if param.profile
        profile on
    end
    
    %COMMENT: this is the main method for image synthesis
    slml2img( {'./model.mat'}, param );
    
    if param.profile
        profile off
        profsave( profile('info'), 'profile' );
        zip( 'profile.zip', 'profile' )
        rmdir( 'profile', 's' );
    end
    
end

%% postprocessing component: not part of cellorganizer, just makes pretty pictures
if param.postprocessing
    try
        directory = [ pwd filesep 'temp' filesep 'preprocessed' ];
        files = dir( [ directory filesep 'cell*.mat'] );
        
        preprocessed_images_directory = [ pwd filesep 'preprocessed' ];
        if ~exist( preprocessed_images_directory )
            mkdir( preprocessed_images_directory );
        end
        
        for index=1:1:length( files )
            file = [ directory filesep files(index).name ];
            if param.verbose
                disp(['Loading ' file ]);
            end
            load( file );
            [path, filename, extension] = fileparts( file );
            img = cat( 3, cat( 3, cellbodyimg, nucbodyimg ), zeros(size(cellbodyimg)) );
            if param.verbose
                disp(['Saving ' preprocessed_images_directory filesep filename '.jpg' ]);
            end
            imwrite( img, [preprocessed_images_directory filesep filename '.jpg'] );
            clear img
        end
        %
        %         files = dir( [ outputDirectory filesep param.prefix '*.tif' ] );
        %         for i=1:1:length(files)
        %             file = files(i).name;
        %             synthetic_image = [ outputDirectory filesep file ];
        %             disp( synthetic_image );
        %             img = cat( 3, cat( 3, cellbodyimg, nucbodyimg ), zeros(size(cellbodyimg)) );
        %             img = uint8( img );
        %             imwrite( img, [ outputDirectory filesep param.prefix num2str(i) '.jpg' ] );
        %         end
    catch err
        getReport( err )
        warning( 'Unable to post-process images' );
    end
end