function [] = trainclassifycells(pathclassified,propname)
% TRAINCLASSIFYCELLS Training a classification tree for classifying cells. 
% 
%   TRAINCLASSIFYCELLS(PATHCLASSIFIED,PROPNAME) trains a tree for the 
%   the user-defined cells in the full path PATHCLASSIFIED, a file created by
%   SELECTCLASSIFYCELLS. PROPNAME is the cell features to use. Either give
%   a cell array of strings of the classificators, or use PROPNAME = 'all' 
%   to use all available.
%
%   See also classifycells, selectclassifycells, combinetrainingset
% 	=======================================================================================
% 	CELLSEGM: Cell segmentation, Version 2012
% 	Copyright (c): Erlend Hodneland
%   Jonas Lies Vei 91,
%   5009 Bergen
%   Email: erlend.hodneland@biomed.uib.no
% 	=======================================================================================

if isequal(propname,'all')
    propname = {'volume','intincell','intborder','convexarea'};
end;
npropname = numel(propname);
    
E = load(pathclassified);

% get the cell properties
nobjs = 0;
targets = [];
for i = 1 : numel(E.data)

    % get data from all objects
    nobj = max(E.data{i}.wat(:));
    cellv = (1 : nobj)';
    prop = cellprop(E.data{i}.imsegm,E.data{i}.wat,cellv,propname,E.data{i}.info.prm.h);
    if ~isempty(prop)
        if i == 1
            propall = prop;
        else
            f = fieldnames(prop);
            for j = 1 : numel(f)
                propall.(f{j}) = [propall.(f{j}) ; prop.(f{j})];
            end;
        end;
    end;
    % total number of objects
    target = zeros(nobj,1);    
    target(E.cellv{i}) = 1;
    targets = [targets ; target];
    nobjs = nobjs + nobj;
end;

% the classification values
values = zeros(nobjs,npropname);
for i = 1 : npropname
    values(:,i) = propall.(propname{i});
end;
% train a network
% net = newff(values,targets,10,{'logsig','logsig'});
tree = treefit(values,targets);
% treedisp(t,'names',{'vol','int'});

[a b c] = fileparts(pathclassified);
if isempty(a)
    filename = [b '-' 'tree.mat'];
else
    filename = [a '/' b '-' 'tree.mat'];
end;
msg = ['Saving ' filename];
disp(msg);
save(filename,'tree','propname');






