function [find,vaf,ultra,lengths] = ...
    atreefndtm(proxtm,inpermrow,inpermcol)

% ATREEFNDTM finds and fits a two-mode additive tree;
% iterative projection is used
% heuristically to find a two-mode ultrametric component that 
% is added to a two-mode centroid metric to 
% produce the two-mode additive tree.
%
% syntax: [find,vaf,ultra,lengths] = ...
%      atreefndtm(proxtm,inpermrow,inpermcol)
%
% PROXTM is the input proximity matrix 
% (with a dissimilarity interpretation);
% INPERMROW and INPERMCOL are permutations for the row and column 
% objects that determine the order in which the
% inequality constraints are considered;
% FIND is the found least-squares matrix (with variance-accounted-for
% of VAF) to PROXTM satisfying the additive tree constraints;
% the vector LENGTHS contains the row followed by column values for 
% the two-mode centroid metric component;
% ULTRA is the ultrametric component.


[nrow ncol] = size(proxtm);

[centfit,centvaf,lengths] = centfittm(proxtm);

resproxtm = proxtm - centfit;

[ultrafit,ultravaf] = ultrafndtm(resproxtm,inpermrow,inpermcol);

find = centfit + ultrafit;

aveprox = sum(sum(proxtm))/(nrow*(ncol));

diff = sum(sum((proxtm- find).^2));

denom = sum(sum((proxtm- aveprox).^2));

vaf = 1 - (diff/denom);


vafdiff = 1.0;

while (vafdiff >= 1.0e-006)
    
    vafprev = vaf;
    
    resproxtm = proxtm - ultrafit;
    [centfit,centvaf,lengths] = centfittm(resproxtm);  
    
    
    resproxtm = proxtm - centfit;
    [ultrafit,ultravaf] = ultrafndtm(resproxtm,inpermrow,inpermcol);
    
    find = centfit + ultrafit;
    
    diff = sum(sum((proxtm - find).^2));
    denom = sum(sum((proxtm - aveprox).^2));
    vaf = 1 - (diff/denom);
    
    vafdiff = abs(vaf - vafprev);
end
   
