% MAKEAXISLABEL makes an axis label from the given ao
%
% CALL
%         [xlbl, ylbl, zlbl] = makeAxisLabel(a)
%
% M Hewitson 10-12-10
%
% $Id: makeAxisLabel.m,v 1.1 2010/12/12 08:29:00 hewitson Exp $
%
function [xlbl, ylbl, zlbl] = makeAxisLabel(d)
  
  xlbl = '';
  ylbl = '';
  zlbl = '';
  yunits = char(d.yunits);
  switch class(d.data)
    case 'tsdata'
      xunits = char(d.xunits);
      xlbl = sprintf('Time %s', xunits);
      ylbl = sprintf('Amplitude %s', yunits);
    case 'fsdata'
      xunits = char(d.xunits);
      xlbl = sprintf('Frequency %s', xunits);
      ylbl = sprintf('Amplitude %s', yunits);
    case 'xydata'
      xunits = char(d.xunits);
      xlbl = sprintf('X-Value %s', xunits);
      ylbl = sprintf('Y-Value %s', yunits);
    case 'cdata'
      xlbl = 'Sample Number';
      ylbl = sprintf('Value %s', yunits);
    case 'xyzdata'
      zunits = char(d.zunits);
      xlbl = sprintf('x-value %s', yunits);
      ylbl = sprintf('y-value %s', yunits);
      zlbl = sprintf('Value %s', zunits);
    otherwise
      error('unknown ao data type');
  end
  
  xlbl = fixlabel(xlbl);
  ylbl = fixlabel(ylbl);
  zlbl = fixlabel(zlbl);
  
end

function ss = fixlabel(ss)
  
  MAX_LENGTH = 50;
  wasCell = true;
  if ~iscell(ss)
    ss = {ss};
    wasCell = false;
  end
  
  for kk = 1:numel(ss)
    s = ss{kk};
    if ~isempty(s)
      % Replace all ^(...) with ^{...}
      jj = 1;
      while jj < numel(s)
        if strcmp(s(jj:jj+1), '^(')
          % find next )
          for k = 1:numel(s)-jj+1
            if s(jj+k) == ')'
              s(jj+1) = '{';
              s(jj+k) = '}';
              break;
            end
          end
        end
        jj = jj + 1;
      end
      % Replace all .^ with ^
      s = strrep(s, '.^', '^');
      
      % reduce size
      if length(s) > MAX_LENGTH
        addStr = '...';
      else
        addStr = '';
      end
      ssize = min(MAX_LENGTH, length(s));
      s = [s(1:ssize) addStr];
    end
    ss(kk) = {s};
  end
  
  
  if ~wasCell
    ss = ss{1};
  end
  
end
