function [image_rgb varargout]=buildoverlay(md,field,transparency,highres,smoothing,windowsize,border);
%BUILDOVERLAY - creates an RGB image of a field
%
%   This routine is used by plotmodel to superimpose a radar
%   image and a field of the model
%
%   Usage:
%      image_rgb=buildoverlay(md,field,transparency,highres,smoothing,windowsize);
%
%   Example:
%      image_rgb=buildoverlay(md,md.vel,0.5,1,1,10^3);
%
%   See also: RADARPOWER, PLOTMODEL, BUILDOVERLAYCOLORBAR

%2d plots only
if ~strcmpi(md.type,'2d'),
	error('plot_overlay error message: only 2d plots allowed');
end

%Ok, first we need to recover the radar map.
md=radarpower(md,highres);

if isfield(struct(md),field)
	data=eval(['md.' field ';']);
else
	data=field;
end

%load x,y, etc ... to speed up plot
x=md.x;
y=md.y;
z=md.z;
elements=md.elements;

if md.numberofgrids==size(elements,1),
	error('buildoverlay error message: the number of elements is the same as the number of grids! cannot plot anything with model/plot, use matlab/plot instead')
end

if smoothing,
	data=averaging(md,data,1);
end

%use mesh2grid solution to get an gridded data to display using imagesc
md.dummy=data;
md.mesh2grid_parameters={'dummy'};
if length(data)==length(elements),
	md.mesh2grid_interpolation={'element'};
elseif length(data)==md.numberofgrids,
	md.mesh2grid_interpolation={'node'};
else 
	error('plot_overlay error message: data should be numberofgrids of numberofelements long');
end
md.mesh2grid_filter={'average'};
md.mesh2grid_cornereast=min(md.x);
md.mesh2grid_cornernorth=max(md.y);
md.mesh2grid_ncolumns=length(md.sarxm);
md.mesh2grid_xposting=(max(md.x)-min(md.x))/md.mesh2grid_ncolumns;
md.mesh2grid_nlines=length(md.sarym);
md.mesh2grid_yposting=(max(md.y)-min(md.y))/md.mesh2grid_nlines;
md.mesh2grid_windowsize=windowsize;

md.cluster='none';
md=solve(md,'mesh2grid','cielo');

%Ok, we have two images, double format: 
radar=md.sarpwr;
results=md.mesh2grid_results{1};

%nullify NaN in results
results(find(isnan(results)))=0;

%Build hsv color image from radar and results
%intensity
v=radar/max(max(radar));

%hue
%cut results under 1.5, and log
results(find(results<1.5))=1.5;
h=bytscl(log(results))/(255+1); %1 offset on colormap

%saturation
s=(0.5+results/125)/transparency;s(find(s>1))=1;s(find(s<0))=0;
s(find(results==1.5))=0;

%Include border
v((1:border),:)=0;  v((end-border+1:end),:)=0; v(:,1:border)=0;v(:,(end-border+1:end))=0;

%Transform hsv to rgb
image_hsv=zeros(size(results,1),size(results,2),3);
image_hsv(:,:,1)=h;
image_hsv(:,:,2)=s;
image_hsv(:,:,3)=v;
image_rgb=hsv2rgb(image_hsv);

if nargout==3,
	varargout{1}=md.sarxm;
	varargout{2}=md.sarym;
end
