function [K,X] = normalizeCoordinateSystem(X)
% normalize the coordinate system given by X.
% ------------------------------------------------------------------------
% first check the size of X and fix it if needed
% ------------------------------------------------------------------------

if isstruct(X) % check the X input
    x = X.x; x = x(:); % grab the x and y coordinate s
	y = X.y; y = y(:); 
    if isfield(X,'z') % if z is a coordinate also include it
        z = X.z; z = z(:); % add z
        X = [x y z]; % build the X matrix 
        ndims = 3; % note that we have 3 dimensions
    else % otherwise
        X = [x y]; % make X out of x and y
        ndims = 2; % and note we have only 2 dimensions
    end
end

szX = size(X); % check size of X
if any(szX(2) == [2 3])% X is in wrong direction ,so transpose it
    X = X'; % transpose it
    szX = size(X); % check size again
end
if szX(1) == ndims % x is not in homogeneous coordinates
    X(ndims+1,:) = ones(1,szX(2)); % add a final row for homogenous coordinates
end
% ------------------------------------------------------------------------
% then find a linear operator K to normalize the cordinate system of X
% ------------------------------------------------------------------------
d = mean(X,2); % find the mean in each direction 
m = max(X,[],2)-min(X,[],2); % find the dimensions

K.inv = [m(1) 0    d(1)   % build the normalizing matrix
         0    m(2) d(2)
         0    0    1   ];


K.fwd = inv(K.inv); % invert it (we'll need this a lot so just do it once and save it!)

% ------------------------------------------------------------------------
% also compute the centered coordinate system (for jacobians)
% ------------------------------------------------------------------------
X = K.fwd*X;
end
