
function G = grid_form(Xmin,Xmax,Xcell,Ymin,Ymax,Ycell)

%GRID_FORM makes a grid of coordinate values within a box of a 
%specified size. The (approximate) cell size is also specified 
%and the procedure then computes an even cell division within
%the box which best approximates the desired cell size.

% grid_form(0,3,1,1,4,1) yields column stacking of:

% 
%      4
%      3
%      2
%      1
%        0 1 2 3
    

%Written by: TONY E. SMITH, 2/7/01

%INPUTS:    Xmin = minimum X-coordinate value
%			Xmax = maximum X-coordinate value
%           Xcell = cell size on X axis
%			Ymin = minimum Y-coordinate value
%			Ymax = maximum Y-coordinate value
%           Ycell = cell size on Y axis

%OUTPUT: G = [X,Y] = matrix of grid coordinates

%SCREEN DISPLAY: The 4x4 grid in the upper left corner
%                of the full grid is shown for a visual
%                consistency check.


% Xnum = round((Xmax-Xmin)/Xcell);
% Ynum = round((Ymax-Ymin)/Ycell);
% 
% Sx = (Xmax-Xmin)/Xnum;
% Sy = (Ymax-Ymin)/Ynum;

dbstop if error

% First make an regular version of the grid by extending upper end.

r = (Xmax - Xmin)/Xcell;

Xnum = ceil(r);

Xupper = Xmin + Xnum*Xcell;

r = (Ymax - Ymin)/Ycell;

Ynum = ceil(r);

Yupper = Ymin + Ynum*Ycell;

s1 = [Xmin:Xcell:Xupper]';
u1 = length(s1);
U1 = ones(u1,1);

s2 = [Yupper:-Ycell:Ymin]';
u2 = length(s2);
U2 = ones(u2,1);

S(:,1) = kron(s1,U2);
S(:,2) = kron(U1,s2);

X = S(:,1) ;
Y = S(:,2) ;

G = [X,Y];

%Screen Plot of Grid (Upper Left Corner)

Cx = zeros(16,1);
Cy = zeros(16,1);

for i=1:4
   for j = 1:4
      Cx(j + (i-1)*4) = X(j + (i-1)*(Ynum+1));
      Cy(j + (i-1)*4) = Y(j + (i-1)*(Ynum+1));
   end
end

plot(Cx,Cy,'.r','MarkerSize',20)




