function [fld,tme]=readgcm(fnam,t,Nx,Ny,Nz,prec,nPx,nPy)

% Function [fld,tme]=readgcm(fnam,t,Nx,Ny,Nz,prec)
% read and output model field from file fnam time step t
%
% INPUTS
% fnam  input path and file name
%          naming Convention:  U_06_04.00060_00120_10
%          U for nPx=6, nPy=4, day 60 to 120 at 10-day intervals
% t     time step (default 1)
% Nx*Ny*Nz  grid dimension (default 360*224*46)
% prec  numeric precision (default 'real*4')
% nPx, nPy  number of processes in x and y direction, when specified
%           overrides filing convention default
 
%
% OUTPUTS
% fld   Nx*Ny*Nz output array
%          e.g., to contour level k, use "contourf(fld(:,:,k)'), colorbar"
% tme   model integration time in seconds corresponding to time step t

if nargin<6, prec='real*4'; end
if nargin<5
  if isempty(findstr(fnam,'KPPhbl')) Nz=46;
  else Nz=1; end
end
if nargin<4, Ny=224; end
if nargin<3, Nx=360; end
if nargin<2, t=1; end
if nargin<1, error('please specify input file name'); end

if nargin < 7
  % locate beginning filename character in path
  slash_loc=findstr('/',fnam);
  if isempty(slash_loc), slash_loc=0; end
  slash_loc=max(slash_loc);
  bar_loc=findstr('_',fnam((slash_loc+1):length(fnam)));
  bar_loc=min(bar_loc);   
  nPx=eval(fnam(slash_loc+bar_loc+(1:2)));  % number of processes in X
  nPy=eval(fnam(slash_loc+bar_loc+(4:5)));  % number of processes in Y
elseif nargin<8
  nPy=nPx;                                  % number of processes in X and Y
end

sNx=Nx/nPx;                                 % number of X points in sub-grid
sNy=Ny/nPy;                                 % number of Y points in sub-grid
if (sNx-floor(sNx))~=0 | (sNy-floor(sNy))~=0
  error('Nx/nPx and Ny/nPy must be integer')
end

switch prec
  case {'float32', 'real*4'}
    rlength=(sNx*sNy*Nz+1)*4;
  case {'float64', 'real*8'}
    rlength=(sNx*sNy*Nz+1)*8;
end

fld=zeros(Nx,Ny,Nz);
fid=fopen(fnam,'r');
if fseek(fid,nPx*nPy*(t-1)*rlength,'bof')
  error('end of file reached')
end

for j=1:nPy
  jx=((j-1)*sNy+1):(j*sNy);
  for i=1:nPx
    ix=((i-1)*sNx+1):(i*sNx);
    tme=fread(fid,1,prec);
    fld(ix,jx,:)=reshape(fread(fid,[sNx,sNy*Nz],prec),sNx,sNy,Nz);
  end
end

fid=fclose(fid);
