function md=meshexprefine(md,domainname,newresolution)
%MESHEXPREFINE - refine mesh from a model
%
%   This routine refines a mesh for a given area using an Argus domain outline 
%   and a new resolution for this domain.
%   Appending ~ at the beginning of domainname will make this routine refine
%   the elements which are not in the domain outline. 
%   newresolution is the resolution to which the flagged elements must be refined.
%
%   Usage:
%      md=meshexprefine(md,domainname,newresolution)
%
%   Example:
%      md=meshexprefine(md,'RefineAreas.exp',1000)

%some checks on list of arguments
if ((nargin~=3) | (nargout~=1)),
	meshexprefineusage();
	error('meshexprefine error message');
end

if ~ischar(domainname) 
	meshexprefineusage();
	error('meshexprefine error message');
end

if (md.counter<1)
	error('meshexprefine error message: you need to run mesh.m first on this model');
end

%Check the first letter of domainname, if it is ~, then we need to strip it away from 
%domainname. The subsequent refinement will be done on the mask of the domain outline.
if strcmpi(domainname(1),'~'),
	mask=1;
	domainname=domainname(2:length(domainname));
else
	mask=0;
end

%Read domainname file into a matlab array (x,y):
refinearea=ArgusContourToMesh(md.elements,md.x,md.y,expread(domainname,1),'element',1);
aires=area(md);

%flags areas within the domain
if mask==1,
	pos=find(~refinearea);
else
	pos=find(refinearea);
end
aires(pos)=newresolution*newresolution/2; %triangle area

pos=find(refinearea);
aires(pos)=2*aires(pos); %be sure this does not get refined.

%refine using the new area vector
md=meshrefine(md,aires);

%return model
end
