function [ xmin, xmax, n ] = com_grd(data, col)
%  1.  NAME
%
%  com_grd - Find a common grid for different datasets
%
%  2.  SYNOPSIS
%
%  [xmin, xmax, n] = com_grd(data, col )
%
%  3.  DESCRIPTION
%
%  This Matlab function looks at the maximum of the minimum grid points,
%  and the minimum of the maximum grid points to determine the boundaries
%  for the common grid. It calculates then the mean value of grid points
%  within this new range. Results can be used for function new_grid(3m)
%  to generate a new regular grid common to all datasets.
%
%  Data do not need to have the same amount of columns, however they
%  should all have their grid points in the column specified by parameter
%  col.
%
%  4.  PARAMETERS
%
%     data
%        A cell array containing all the datasets to compare together.
%        These are columnar data,where each column corresponds to the
%        values of a variable along different grid points.
%
%     col
%        Number to the column containing the grid points.
%
%  5.  RETURNS
%
%     xmin
%        Lowest boundary for the common range.
%
%     xmax
%        Highest boundary for the common range.
%
%     n Advised number of points to use within the common range. This is
%        the mean
%        value of data within the common range.  function "
%
%  6.  AUTHORS
%
%  Pierre Jaccard, Geophysical Institute, University of Bergen, 1999
%

%--- Initializations:
nf = length(data);
if nf < 1,
	error([ 'Input cell array of data is empty' ]);
end

%--- Check that x is within column range of data:
for f=1:nf,
	if col > size(data{f},2),
		error([ 'Column number outside range' ]);
	end
end

%--- Get the most included range:
xmin = -Inf;
xmax = +Inf;
for f=1:nf,
	xmin = max([ xmin, min(data{f}(:,col)) ]);
	xmax = min([ xmax, max(data{f}(:,col)) ]);
end

%--- Get the mean number of values within this range:
n = [];
for f=1:nf,
	ii = find( (data{f}(:,col) >= xmin) & (data{f}(:,col) <= xmax));
	tmp = data{f}(ii,col);
	%--- Remove duplicate entries:
	tmp = unique(tmp);
	n = [ n, length(tmp) ];
end
n = round(mean(n));

return;


