function edit(varargin)
%EDIT Edit M-file.
%   EDIT FUN opens the file FUN.M in a text editor.  FUN must be the
%   name of an m-file or a MATLABPATH relative partial pathname (see
%   PARTIALPATH).
%
%   EDIT FILE.EXT opens the specified text file.
%
%   EDIT FUN1 IN FUN2 opens function FUN1 in the context of m-file
%   FUN2.  
%
%   EDIT FUN(A,B,C) opens file FUN.M that matches the 
%   given input arguments.  For example, edit feval(g), when
%   g=inline('sin(x)'), opens inline/feval.m.
%
%   EDIT, by itself, opens up a new editor window.

%   Copyright 1984-2000 The MathWorks, Inc. 
%   $Revision: 1.67 $  $Date: 2000/09/22 19:20:03 $

% Reject anything but string arguments
if ~iscellstr(varargin)
   disp('The input must be a string.');
   return;
end

%
% Decide which file, if any, to edit.
%
% Pass the arguments through to WHICH.
% If there are no matching files in the WHICH's scope, assume
% that the file isn't on the path, and try opening it directly.
%
fcnname = '';
if nargin > 0
   fcnname = strtrim(varargin{1});
   fullpath = [];
   %Be sure to escape single quotes embedded inside of the file name.
   whichargs = [ '''' strrep(fcnname, '''', '''''') ''''];
   
   % If there is more than one arg, we're using a special form of WHICH
   if nargin > 1
      whichargs = [whichargs sprintf(',''%s''', varargin{2:end})];
   end
   
   % Pass the incoming arguments through to WHICH
   
   % If we have Java classes in memory, make sure that we are
   % not passing along a Java method to EDIT.
   [tmp1,tmp2,jclasses] = inmem;

   if ~isempty(jclasses)
     fullpath = evalin('caller', ['which(' whichargs  ',' '''-all'')']);
     for i = 1:length(fullpath)
       [pathname,name,ext] = fileparts(fullpath{i});

       if (exist(fullpath{i},'class') ~= 8) & (exist(name,'class') ~=8) & ...
             isempty(findstr([filesep '@'],pathname))
         % Then the fully qualified name isn't a Java constructor
         % and it isn't a Java method either, so the only thing it
         % could be is a filename.
         % Make sure we aren't picking up an overloaded method, too.
         break
       end
     end
     % If we've reached the end of the list then return it as a
     % char array and let EDIT do its old behavior.
	if (~isempty(i))
     		fullpath = fullpath{i};
	end
   else
     fullpath = evalin('caller', ['which(' whichargs ')']);
   end
   
   mdltag = 'loaded model ';
   if ~isempty(strmatch(mdltag, fullpath)) & length(fullpath) > length(mdltag)
     fullpath = fullpath(length(mdltag)+1:end);
   end
   
   %
   % Eliminate cases where WHICH returns a value that isn't a legitimate pathname.
   % Can't catch this using EXIST on fcnname below, because for some forms of EDIT
   % (e.g., edit subfun in fun), fcnname isn't enough information for EXIST.
   %
   if strcmp(fullpath, 'variable')
      disp(sprintf('Can''t edit the variable ''%s''.', fcnname));
      return;
   elseif strcmp(fullpath, 'built-in')
      disp(sprintf('Can''t edit the built-in function ''%s''.', fcnname));
      return;
   end
   
   % If we don't find a match, assume we're trying to edit a file
   % that isn't on the path.
   if isempty(fullpath) & nargin == 1
      fullpath = strtrim(varargin{1});
   end
   
   % If we still don't have a match, give up.
   if isempty(fullpath)
      disp(sprintf('File ''%s'' not found.', fcnname));
      return;
   end
      
   % Make sure the file we're opening is of an openable type
   exists = evalin('caller', ['exist(''' strrep(fullpath,'''','''''') ''')']);
   
   switch exists
   case 0
      disp(sprintf('File ''%s'' not found.', fcnname));
      return;
   case 1   % Variable: this is caught above.
      disp('Internal error in edit.m.');
      return;
   case 3
      disp(sprintf('Can''t edit the MEX-file ''%s''.', fcnname));
      return;
   case 4
      % Editing an MDL-file is allowed only when the user specifies the file
      % extension .mdl explicitly, making their intent clear.  If you edit
      % an MDL-file accidentally you can corrupt it and trash the model.  Only
      % MathWorks developers and sophisticated users edit MDL-files.
      % (Note: it's OK to do case-insensitive comparison against '.mdl' on UNIX
      % here even though the UNIX file system is case-sensitive, because exist
      % has already told us that this must be an MDL-file.)
      if (length(fcnname) < 4) | (strcmp(lower(fcnname(end-3:end)), '.mdl') ~= 1),
         disp(sprintf('Can''t edit the MDL-file ''%s'' unless you include the ''.mdl'' file extension.', fcnname));
         return;
      end
   case 5   % Built-in: this is caught above.
      disp('Internal error in edit.m');
      return;
   case 7
      disp(sprintf('Can''t edit the directory ''%s''.', fcnname));
      return;
   end
   
   
   % Map a P-file to the corresponding M-file.  Note: we can't do this by
   % checking exist(name) == 6, because name might point to a P-file that
   % is not on the path.
   if length(fullpath) >= 2,
      ext = fullpath(end-1:end);
      if ~isunix, ext = lower(ext); end  % file system on PC is case-tolerant
      if strcmp(ext, '.p') == 1,
         if exist([fullpath(1:end-2) '.m']) ~= 2,  % will return 2 if the M-file exists
            disp(sprintf('The P-file ''%s'' has no matching M-file ''%s'' to edit.', fullpath, [fullpath(1:end-2) '.m']));
            return;   
         end
         fullpath(end-1:end) = '.m';
      end
   end
end

if exist('fullpath')
   editor(fullpath);
else
   editor;
end

%------------------------------------------
function editor(file)
% EDITOR  Open file in user specified editor

% Determine which editor to run.  Assume builtin editor to begin with.
builtinEd = 1;

% Make sure our environment supports the editor
err = javachk('mwt', 'The MATLAB Editor');
if ~isempty(err)
	if ~isunix
		error (err);
	else
		builtinEd = 0;
		% Special case for hp700 
		if isequal(lower(computer), 'hp700')
			if nargin == 0 
				eval( ['!$EDITOR &']);
			else
				eval( ['!$EDITOR "' file '" &']);
			end;
		else
			if nargin==0
				system_dependent('miedit', '');
			else
				system_dependent('miedit', file);
			end;
		end;
		return;
	end;
end

% Get the MATLAB editor preference.
if  builtinEd == 1
	if com.mathworks.ide.editor.EditorOptions.getBuiltinEditor == 0,
	    editor = char(com.mathworks.ide.editor.EditorOptions.getOtherEditor);
	    builtinEd = 0;
	end;
end

if builtinEd == 1
        %make call to Java
        % Try to open the Editor
        try
            if nargin==0,
                com.mathworks.ide.editor.EditorApplication.newDocument;
                
            else,
                com.mathworks.ide.editor.EditorApplication.openDocument(file);
                
            end % if nargin
            
        catch
            % Failed. Bail
            error('Failed to open editor');
        end
        return
else
    % User-specified editor
    if isunix
        % Special case for vi
        if strcmp(editor,'vi') == 1
            editor = 'xterm -e vi';
        end
        
        % On UNIX, we don't want to use quotes in case the user's editor
        % command contains arguments (like "xterm -e vi")
        if nargin == 0
            eval(['!' editor ' &'])
        else
            eval(['!' editor ' "' file '" &'])
        end
    else
        % On Windows, we need to wrap the editor command in double quotes
        % in case it contains spaces
        if nargin == 0
            eval(['!"' editor '" &'])
        else
            eval(['!"' editor '" "' file '" &'])
        end
    end
end


%------------------------------------------
function s1 = strtrim(s)
%STRTRIM Trim spaces from string.

if ~isempty(s) & ~isstr(s)
    warning('Input must be a string.')
end

if isempty(s)
    s1 = s;
else
  % remove leading and trailing blanks (including nulls)
  c = find(s ~= ' ' & s ~= 0);
  s1 = s(min(c):max(c));
end
