function [x, y, z] = contoxyz(data, iz, yi)
%  1.  NAME
%
%  contoxyz - Reorder and regrid contour data
%
%  2.  SYNOPSIS
%
%  [x,y,z] = contoxyz(data, iz, yi )
%
%  3.  DESCRIPTION
%
%  This Matlab function selects specified z variables from an input
%  contour file. It also reorder the columns to have x and y the least
%  and next varying values. Data are also regridded on a specified grid
%  along y values.
%
%  4.  PARAMETERS
%
%     data
%        Array containing contour data. The x and y must be located in
%        the frist two columns,respectively.
%
%     iz Column number of the z variable to retrieve from the data
%        matrix.
%
%     yi A vector on which contour data should be interpolated. This is
%        necessary because some contour data do not have values at
%        identical y in different profiles.
%
%  5.  RETURNS
%
%     x  A vector containing x values.
%
%     y  A vector containing y values (same as yi).
%
%     z  An array containing the desired z values,interpolated on grid
%        defined by x and yi values.
%
%  6.  AUTHORS
%
%  Pierre Jaccard, Geophysical Institute, University of Bergen, 1999
%

%--- Assign indexes to columns:
ix = 1; iy = 2;

%--- Sort the matrix to have least varying x values, and next least varying
%		 variable y:
data = sortrows(data, [ix, iy]);

%--- Find the start index to each profile:
ii = 2:size(data,1);
iprf = find(data(ii,ix) ~= data(ii-1,ix));
iprf = [ iprf; size(data,1) ];

%--- Loop through the profiles:
i0 = 1;
x = []; y = []; z = [];
for i1=iprf',
	%--- Get profile data:
	prf = data(i0:i1, [ix, iy, iz]);
	%--- Interpolate profile data:
	zi = interp1(prf(:,2), prf(:,3), yi);
	%--- Save data:
	x = [ x, prf(1,1) ];
	z = [ z; zi ];
	%--- Update start index:
	i0 = i1 +1;
end
z = z';
y = yi;

return;



