function h = manovacluster(varargin)
%MANOVACLUSTER Cluster group means using manova1 output
%   MANOVACLUSTER(STATS) draws a dendrogram showing the clustering
%   of group means, calculated using the output STATS structure
%   from MANOVA1 and applying the single linkage algorithm.
%   See the DENDROGRAM function for more information about the figure.
%
%   MANOVACLUSTER(STATS,METHOD) uses the METHOD algorithm in place
%   of single linkage. The available methods are:
%
%      'single'   --- nearest distance
%      'complete' --- furthest distance
%      'average'  --- average distance
%      'centroid' --- center of mass distance
%      'ward'     --- inner squared distance
%
%   MANOVACLUSTER(AX,...) plots into axes AX instead of GCA.
%
%   H = MANOVACLUSTER(...) returns a vector of line handles.
%
%   See also MANOVA1, DENDROGRAM, LINKAGE, PDIST, CLUSTER,
%   CLUSTERDATA, INCONSISTENT.

%   Copyright 1993-2023 The MathWorks, Inc. 

import matlab.graphics.chart.internal.inputparsingutils.peelFirstArgParent
import matlab.graphics.chart.internal.inputparsingutils.prepareAxes

narginchk(1,3);
[parent,args] = peelFirstArgParent(varargin,false);
[parentSpecified, isValidAxes] = internal.stats.validateAxes(parent, false);
if parentSpecified && ~isValidAxes
    error(message('stats:dendrogram:BadAxes'))
end

if isempty(args)
    error(message('MATLAB:narginchk:notEnoughInputs'))
elseif numel(args) > 2
    error(message('MATLAB:narginchk:tooManyInputs'))
else
    [args{:}] = convertStringsToChars(args{:});
    stats = args{1};
    if numel(args) > 1 && ~isempty(args{2})
        method = args{2};
    else
        method = 'single';
    end
end

% Draw dendrogram of multivariate group means
d = stats.gmdist;
gn = stats.gnames;
[a,b] = meshgrid(1:length(d));
parent = prepareAxes(parent, parentSpecified);
hh = dendrogram(parent, linkage(d(a<b)', method), 0);

% Fix up X axis tick labels
oldlab = get(parent, 'XTickLabel');
maxlen = max(cellfun('length', gn));
newlab = repmat(' ', size(oldlab,1), maxlen);
ng = size(gn,1);
for j=1:size(oldlab,1)
   k = str2num(oldlab(j,:));
   if (~isempty(k) & k>0 & k<=ng)
      x = gn{k,:};
      newlab(j,1:length(x)) = x;
   end
end
set(parent, 'XtickLabel', newlab);

% Return handles if requested
if (nargout>0), h = hh; end
