function pderect(dim,label)
%PDERECT Draw rectangle, update Geometry Description matrix.
%
%	PDERECT([xmin xmax ymin ymax],LABEL) draws a rectangle
%	with dimensions defined by the x and y values and labeled
%	with the string LABEL. The label is optional. If omitted,
%	a label will be automatically assigned.
%
%	See also: PDECIRC PDEELLIP PDEPOLY

%	Magnus Ringh 9-21-94, MR 07-25-95.
%	Copyright (c) 1994-95 by The MathWorks, Inc.
%	$Revision: 1.9.1.2 $  $Date: 1995/08/31 08:41:57 $

if nargin<1
  error('Too few input arguments')
end

if ~(any(size(dim)==1))
  error('Input data must be vectors')
end

if ~isreal(dim)
  error('Input data must be real')
end

if (length(dim)~=4)
  error('Input must be a 4x1 vector')
end

if ((dim(1)==dim(2)) | (dim(3)==dim(4)))
  error('Rectangle sides must be > 0')
end

if nargin>1,
  if ~isstr(label)
    error('Label must be a string')
  end
end

pde_fig=findobj(get(0,'Children'),'flat','Tag','PDETool');
% If PDETOOL not started, create PDETOOL interface
if isempty(pde_fig),
  pdetool
  pde_fig=findobj(get(0,'Children'),'flat','Tag','PDETool');
end

if nargin>1,
  if pdeisusd(label)
    error('Label must be unique')
  end
end

ax=findobj(get(pde_fig,'Children'),'flat','Tag','PDEAxes');

if nargin==1,
  % add label:
  small=100*eps*(min(diff(get(ax,'Xlim')),diff(get(ax,'Ylim'))));
  if (abs(abs(diff(dim(1:2)))-abs(diff(dim(3:4))))<small),
    % square
    numsquare=1;
    label='SQ1';
    while pdeisusd(label),		% ensure unique labels
      numsquare=numsquare+1;
      label=['SQ' int2str(numsquare)];
    end
  else
    % rectangle
    numrect=1;
    label='R1';
    while pdeisusd(label),		% ensure unique labels
      numrect=numrect+1;
      label=['R' int2str(numrect)];
    end
  end
end

pde_rect=3;

x=[dim(1) dim(2) dim(2) dim(1)];
y=[dim(3) dim(3) dim(4) dim(4)];

h=findobj(get(pde_fig,'Children'),'flat','Tag','PDEMeshMenu');
pdegd=get(h,'UserData');
% update PDEGD matrix
m=size(pdegd,2)+1;
pdegd(1,m)=pde_rect;
pdegd(2,m)=4;
pdegd(3:6,m)=x';
pdegd(7:10,m)=y';

% Check data before proceeding:
stat=csgchk(pdegd);
err=0;
if stat(m)==1,
  pdetool('error','  Rectangle not complete')
  err=1;
elseif stat(m)>1,
  pdetool('error','  Rectangle lines must not overlap or intersect')
  err=1;
end
if err
  set(pde_fig,'Pointer','arrow');
  return;
end

set(h,'UserData',pdegd);

set(pde_fig,'Pointer','watch');

% First call DECSG to decompose geometry;
err=0;
eval('[dl1,bt1,pdedl,bt,msb]=decsg(pdegd);','err=1;');
if err,
  set(h,'UserData',pdegd(:,1:m-1))
  pdetool('error',lasterr)
  set(pde_fig,'Pointer','arrow');
  return;
end

pdepatch(pdedl,bt,msb,label,m);
set(findobj(get(pde_fig,'Children'),'flat',...
    'Tag','PDEBoundMenu'),'UserData',pdedl);

setuprop(pde_fig,'dl1',dl1)
setuprop(pde_fig,'bt1',bt1)

h=findobj(get(ax,'Children'),'flat','Tag','PDELabel','UserData',m);
set(h,'Tag','PDELblSel')

pdeframe(pdegd,m)

set(pde_fig,'Pointer','arrow');
