function [field,x,y]=hopsgui_depthslicev(filein,depth,time,var)

%       USAGE: [field,x,y]=hopsgui_kslicev(filein,depth,time,var)
%
% HOPS_DEPTHSLICEV  Returns a matrix containing a horizontal slice (field),
%   of the v componetn o the velocity and the  position (x,y) at a 
%   specified depth and time step from an HOPS output (PE) file. 
%   The HOPS model is a sigtma model, what mean that to pass form the
%    the output file to depth levels is necesary an interpolation, this
%    have been optimized using the matlab vectors.
%
% 		filein -- the .nc file
% 		time -- time of teh simulatio
%		var -- string with the variable name
%		depth -- depth where the slice is taken
%
%  Pedro Velez (UIB), July 1999



x=getnc(filein,'vgrid3',[-1 -1 1 1],[-1 -1 1 1],1,1,2);
y=getnc(filein,'vgrid3',[-1 -1 1 2],[-1 -1 1 2],1,1,2);
zgrid3=getnc(filein,'vgrid3',[-1 -1 -1 3],[-1 -1 -1 3],1,1,2);
uz=getnc(filein,var,[time -1 -1 -1 2],[time -1 -1 -1 2],1,1,2);
uz(find(uz==0))=NaN;
	
[ny,nx,nz]=size(zgrid3);
uz=reshape(uz,nx*ny,nz)';
zlev=reshape(zgrid3,nx*ny,nz)';

% find all the values of zlev that are less than the requested depth
% zind consists of zeros and ones.  One if the cell depth is less
% than (below) the requested z level, zero if cell level is greater.

zind=zlev < depth;

% find the indices IK of the cells that are just above the required level 

dz=diff(zind);
dz(nz,:)=zeros(size(dz(nz-1,:)));
ik=find(dz==1);

% find the indices ISUM where the requested depth is between two data values
isum=find(sum(dz));
field=zeros(nx*ny,1);

% Do linear interpolation
field(isum)=uz(ik)+(uz(ik+1)-uz(ik)).*(depth-zlev(ik))./(zlev(ik+1)-zlev(ik));

% put back in matrix form
field=reshape(field,ny,nx);
field(find(field==0))=NaN;
land=getnc(filein,'landv',[-1 -1],[-1 -1],1,1,1);
field(find(land~=2))=NaN;


