function [sMap,sData] = som(sData)

%SOM Initialize, train, label and visualize a self-organizing map.
%
% sMap = som(sData)
%
% ARGUMENTS 
%
%  sData  (struct or matrix) data structure or data matrix 
%
% RETURNS
%
%  sMap   (struct) trained self-organized map
%  sData  (struct) normalized data structure
%
% This is the ultimate user-friendly function that initializes, 
% trains, labels and finally visualizes a SOM based on the given data set.
% The function constitutes of function calls to other basic routines
% of the toolbox performed in the usual order. No parameters other 
% than the data set are given.
%
%  [sMap,sData] = som(D)
%
% See also SOM_INIT, SOM_TRAIN, SOM_AUTOLABEL, SOM_SHOW.

% Copyright (c) 1997 by the SOM toolbox programming team.
% http://www.cis.hut.fi/projects/somtoolbox/

% Version 1.0beta juuso 051197

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Check arguments and initialize

error(nargchk(1, 1, nargin));  % check the number of input arguments

if ~isstruct(sData), 
  sData = som_data_struct(sData); 
  nolabels = 1;
else
  [llen dummy] = size(sData.labels);
  nolabels = 1; i=1; 
  while i<=llen & nolabels, 
    if ~isempty(sData.labels{i}), 
       j=1; 
       while j<=length(sData.labels{i}) & nolabels, 
         nolabels = isempty(sData.labels{i}{j}); j=j+1;
       end
    end
    i = i+1;
  end
end
[dlen dim] = size(sData.data);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Action

fprintf(1,'Preprocessing\n');  % preprocessing (normalization)
sData = som_normalize_data(sData);
fprintf(1,'Initializing\n');   % initialization
sMap = som_init(sData);        
sMap = som_train(sMap,sData);  % training
if ~nolabels,                  % labeling
  fprintf(1,'Labeling\n');
  sMap = som_autolabel(sMap, sData, 'freq');
end
colormap('hot')                % visualization
h = som_show(sMap,[0 1:dim -2],'denormalized'); 
set(h.label(dim+2),'String','Hit histogram')
  % u-matrix, component planes and place for hits
som_addhits(sMap,sData,dim+2,'spot','red') % hits
if ~nolabels,
  som_addlabels(sMap,'all',dim+2,'','white') % labels
end

fprintf(1,'Average quantization error: %e\n',som_quality(sMap, 'qe', sData));
fprintf(1,'Topographic error:          %4.2f%%\n',100*som_quality(sMap, 'topog', sData));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
