function grid_data=griddata_mesh_to_grid(x_m,y_m,grid_data,x,y,mesh_data,varargin)
%GRIDDATA_MESH_TO_GRID - interpolates data from a mesh to a grid
%
%   This routine takes a mesh (x,y) and values for every grid of the mesh (mesh_data),
%   and interpolates it (using nearest interpolation) onto the gridded data (grid_data). 
%   x_m and y_m (vectors of coordinates) are used to find interpolation locations onto grids.
%
%   Usage:
%      grid_data=griddata_mesh_to_grid(x_m,y_m,grid_data,x,y,mesh_data,varargin)

if nargin==7,
	roundup=varargin{1};
else
	roundup=0;
end

s=size(grid_data);
if length(x_m) ~= (s(2)+1),
	error('x_m should be wider than grid_data by 1');
end

if length(y_m) ~= (s(1)+1),
	error('y_m should be larger than grid_data by 1');
end

x_m0=x_m(1:end-1);
x_m1=x_m(2:end);
y_m0=y_m(1:end-1);
y_m1=y_m(2:end);

for i=1:length(x),
	if mod(i,100000)==0,
		disp(['   progress ' num2str(i/length(x)*100) '%']);
	end
	posx=find( (x(i)-x_m1)<=0 & (x(i)-x_m0)>0 );
	posy=find( (y(i)-y_m1)<=0 & (y(i)-y_m0)>0 );
	
	y0=posy-roundup;
	y1=posy+roundup;
	if y0<=0, y0=1; end
	if y1>s(1), y1=s(1);end

	x0=posx-roundup;
	x1=posx+roundup;
	if x0<=0, x0=1; end
	if x1>s(2), x1=s(2);end

	grid_data(y0:y1,x0:x1)=mesh_data(i);
end
