% JPL2MPL converts a java plist to a matlab plist
%
% CALL:  mpl = jpl2mpl(jpl)
%
% M Hewitson 23-11-08
%
% $Id: jpl2mpl.m,v 1.7 2010/08/06 19:10:49 ingo Exp $
%
function mpl = jpl2mpl(jpl)
  
  mpl = plist;
  mpl.setName(char(jpl.getName()));
  
  % build java plist
  for aa=1:awtinvoke(jpl, 'getNparams')
    p = awtinvoke(jpl, 'getParam', aa-1);
    if p.isActive
      val = awtinvoke(p, 'getDefaultVal');
      key = awtinvoke(p, 'getKey');
      if isempty(val)
        if strcmp(awtinvoke(p,'getValueType'), 'char')
          val = '';
        else
          val = [];
        end
      end
      if ischar(val)
        % Try to evaluate the string
        disp(sprintf('$$$ checking parameter value %s', val));
        try
          if any(strcmpi(val, utils.helper.ltpda_classes))
            % we don't eval strings that are a class name
            pval = val;
          elseif ~isempty(getBaseVariable(val))
            
            pval = getBaseVariable(val);
            
          elseif strcmpi(val, 'false') || strcmpi(val, 'true')
            
            % Handle true and false as logicals
            pval = eval(lower(val));
            
          elseif  exist(val) ~=0
            %           warning('parameter value ''%s'' is a file on the MATLAB path: not evaluating', val);
            % we don't eval strings that are any kind of MATLAB file
            pval = val;
            
          elseif strcmpi(key, 'start') || strcmpi(key, 'end') || ...
              strcmpi(key, 'startt') || strcmpi(key, 'endt') || ...
              strcmpi(key, 'start_time') || strcmpi(key, 'end_time') || ...
              strcmpi(key, 'starttimes') || ...
              strcmpi(key, 't0')
            
            pval = val;
            
          else
            % then we can eval this
            pval = evalin('base', val);
          end
        catch
          %         warning('Evaluation of string parameter value %s failed', val);
          % if the evaluation of the string failed, just return the string
          pval = val;
        end
      else
        % if the value is not a string, just return it
        pval = val;
      end
      mpl.append(param(char(awtinvoke(p,'getKey')), pval));
    end
  end
end

% Checks to see if a value from a plist represents a variable in the base
% workspace. If so, the variable is evaluated and the result returned.
%
function res = getBaseVariable(val)
  
  try
    if evalin('base', sprintf('exist(''%s'', ''var'')', val))
      cmd = ['exist(''' val ''')'];
      res = evalin('base', val);
    else
      res = [];
    end
  catch
    res = [];
  end
  
end

