function [xxx,yyy,zzz,res]=data2grid2(x,y,z,nx,ny,dx,dy,varargin)
% 
% [xxx,yyy,zzz]=data2grid2(x,y,z,nx,ny,dx,dy,xx, yy,mtd)
% puts sporadic points into a grid using the new function
% TriScatteredInterp
% 
% Inputs
% x,y,z,  coordinates of points
% nx,ny   number of grid points in new grid
% optional
% xx, yy the vector to be inputed to mesh grid
% mtd-interpolation method
% % 
% Michalis Vousdoukas 2010

if nargin==7
    
    xx=[];
    yy=[];
    
    mtd='linear';
    
elseif nargin==9
    
    xx=varargin{1};
    yy=varargin{2};
    mtd='linear';

elseif nargin==10
    
    xx=varargin{1};
    yy=varargin{2};
    mtd=varargin{3};
    
end



if isempty(xx)
    
    x1=min(x);
    x2=max(x);

    y1=min(y);
    y2=max(y);


    if isempty(dx) & ~isempty(nx)

        dx=(x2-x1)/(nx-1);
        dy=(y2-y1)/(ny-1);

    elseif isempty(dx) & isempty(nx)

        nx=100;
        ny=100;

        dx=(x2-x1)/(nx-1);
        dy=(y2-y1)/(ny-1);

    end
   
    
    xx=[x1:dx:x2];
    yy=[y1:dy:y2];

end
% figure(1)

% scatter(x,y,5,z)


[xxx,yyy]=meshgrid(xx,yy);

% make grid for plotting on matlab
F = TriScatteredInterp(x,y,z,mtd);

zzz=F(xxx,yyy);

res.xl=[min(xx) max(xx)];
res.yl=[min(yy) max(yy)];
res.z=zzz;
res.x=xxx;
res.y=yyy;

% 
% figure
% % mesh and contour plots
% mesh(xx2,yy2,z2)
% 
% % print -dtiff bathy_plot_combined
% 
% ccc=[-100 0 100 1000];
% figure
% contour(xx2,yy2,z2,ccc)
% colorbar
% print -dtiff contour_plot