%% Run a NeXtMidas command
%
% Run a NeXtMidas command. The first argument should be (at a minimum) the
% NeXtMidas function name. NeXtMidas arguments are seperated by spaces;
% therefore, all additional arguments will be converted into strings and
% appended to the command.
%  
% Syntax
% nm(cmd)
% nm(cmd,arg1,...,argN)
% nm cmd arg1,...,argN 
% 
% Input Arguments
% cmd  - command name
% args - additional arguments to append to command
%
% Examples:
% 0. Initialize a NeXtMidas session
% nm('start')
%
% 1. Generate a generic wave
% nm('wave', 'my_wave')
%
% 2. Generate the same wave with a slightly different call
% nm('wave my_wave')
%
% 3. Genereate a wave with a few more parameters
% nm('wave my_wave', 'cf', 16384, 'amp=1024')
% 
% 4. Plot the wave we just generated
% nm('plot my_wave')
%
% 5. End a NeXtMidas session
% nm('end')
%
function status = nmfunc (cmd, varargin) 
  global NXM_HANDLE;
  
  % handle blank command
  if nargin < 1 
    disp('No command argument given - launching NeXtmidas interactive shell');
    cmd = ['shell'];
  end

  % loop through and build up the full command
  for m=1:nargin-1
    arg=varargin{m};
    % look for keyed parameters
    if strfind(arg,'=')
      strs = strsplit(arg,'=');
      key = [char(strs(1)),'='];
      val = char(strs(2));
    else
      key = '';
      val = arg;
    end
    % is this a valid MatLab variable name ?
    carets = strfind(val,'^');
    valx = strrep(val,'^','');
    if ~isempty(carets) && isvarname(valx) && isempty(strfind(valx,' ')) 
      exists = ['exist(''',valx,''')'];
      if evalin('base',exists)
        val = evalin('base',valx);
      end
      if isnumeric(val) 
        val = num2str(val,10);
      end
      % convert to vector results syntax ?
      if strfind(val,' ')>0 
        while strfind(val,'  ') > 0 
          val = strrep(val,'  ',' ');
        end
        val = strrep(val,' ',',');
        val = ['(',val,')'];
      end
    end
    % handle quoted strings
    if ~isempty(strfind(val,' ')) && isempty(strfind(val,'"'))
      cmd = [cmd,',',key,'"',val,'"'];
    else
      cmd = [cmd,',',key,val];
    end
  end

  % special case initialization
  if isempty(NXM_HANDLE)
    disp('Starting NeXtMidas session');
    nmhand=nminit();
    global NXM_HANDLE
    NXM_HANDLE = nmhand;
  end

  % run the command
  if strcmp(cmd,'start')
  elseif strcmp(cmd,'end')
    delete(NXM_HANDLE);
  else
    status = NXM_HANDLE.runCommand(cmd);
    status = char(status);
  end

end

