function out=_subplot(varargin)

global defaultFigureUserData defaultAxesUserData

[lhs,rhs]=argn();

win=get('current_figure');
IMD=win.immediate_drawing;
win.immediate_drawing="off";

_axes_ppty_value_list=list();
if type(varargin(1))==1
  if length(varargin)==1
    subplotString=string(varargin(1));
    if length(subplotString)~=3
      str=sprintf('subplot : arguments must be a number of the type nmp or n,m,p');
      _error(str);
    end
    n=evstr(part(subplotString,1));
    m=evstr(part(subplotString,2));
    p=evstr(part(subplotString,3));    
  elseif length(varargin)==3
    [n,m,p]=varargin(1:3);
  end
  if (p<1) | (p>n*m)
    str=sprintf('subplot : number of subplot must be between 1 and %d',n*m);
    _error(str);
  end
  
  lx=1/m;
  ly=1/n;  
  [y,x]=meshgrid(0:ly:1-ly,0:lx:1-lx);
  x=x(p);y=y(p);
  outerpos=[min(x) min(y) max(x)-min(x)+lx max(y)-min(y)+ly];  
  margin=win.user_data.margin;
  pos=outerpos+margin*[1-outerpos(1) 1-outerpos(2) -1-outerpos(3) -1-outerpos(4)];
elseif type(varargin(1))==10
  if convstr(varargin(1),'l')=='position'
    out=parsePosition('subplot',varargin(2),'position','Position');
    pos=out(2);
    i=2;
  else
    str=sprintf('subplot : unknown command option %s',varargin(1));
    _error(str);
  end
end  

matchingAxes=[];
for i=1:size(win.children,1)
  ax=win.children(i);
  if abs(ax.user_data.Position-pos)<%eps
    matchingAxes=[matchingAxes;ax];
  end      
end



if type(matchingAxes)==1
  to_delete=[];    
  for i=1:size(win.children,1)
    if win.children(i).user_data.Tag~='colorbar'
      ab=win.children(i).user_data.Position;
      if (pos(1)+pos(3)-ab(1)>%eps) & ...
          (ab(1)+ab(3)-pos(1)>%eps) & ...
          (pos(2)+pos(4)-ab(2)>%eps) & ...
          (ab(2)+ab(4)-pos(2)>%eps) 
          to_delete=[to_delete;win.children(i)];
      end
    end
  end

  if to_delete~=[]
    delete(to_delete);   
  end

  out=_axes('Position',pos);
  sca(out.handle);
  
else
    if length(matchingAxes)>1
      delete(matchingAxes(1:$-1));  
    end  
    sca(matchingAxes($));
    out=mlist(['pltlibH','handle'],matchingAxes($));
end


_ind=find(win.user_data.eventHandlers=="plotlib_subplot_handler");
if _ind==[]
  _add_event_handler(win,"plotlib_subplot_handler");
else
   win.event_handler_enable='on';
end

win.immediate_drawing=IMD;

endfunction
