function [x,y,data]=oct_read_data_tpxo(datafile,dataname,itide,lon,lat,type,dl)
% oct_read_data_tpxo: procedural netcdf replacement for read_data_tpxo

ncid = netcdf.open(datafile,'NC_NOWRITE');

% Get variables lon/lat
lon_var = ['lon_', type];
lat_var = ['lat_', type];
lonid = netcdf.inqVarID(ncid, lon_var);
latid = netcdf.inqVarID(ncid, lat_var);
X = netcdf.getVar(ncid, lonid);
Y = netcdf.getVar(ncid, latid);

lonmin=min(min(lon))-dl;
lonmax=max(max(lon))+dl;
latmin=min(min(lat))-dl;
latmax=max(max(lat))+dl;

j=find(Y>=latmin & Y<=latmax);
i1=find(X-360>=lonmin & X-360<=lonmax);
i2=find(X>=lonmin & X<=lonmax);
i3=find(X+360>=lonmin & X+360<=lonmax);
x=cat(1,X(i1)-360,X(i2),X(i3)+360);
y=Y(j);

% Read data variable
varid = netcdf.inqVarID(ncid, dataname);
[varname,xtype,dimids,natts] = netcdf.inqVar(ncid,varid);
ndims = length(dimids);

data = [];
if ~isempty(i2)
  if ndims==2
    data = squeeze(netcdf.getVar(ncid,varid,j(1):j(end),i2(1):i2(end)));
  elseif ndims==3
    data = squeeze(netcdf.getVar(ncid,varid,itide-1,j(1):j(end),i2(1):i2(end)));
  elseif ndims==4
    data = squeeze(netcdf.getVar(ncid,varid,itide-1,0,j(1):j(end),i2(1):i2(end)));
  else
    error(['Bad dimension number ',num2str(ndims)])
  end
end
if ~isempty(i1)
  if ndims==2
    d1 = squeeze(netcdf.getVar(ncid,varid,j(1):j(end),i1(1):i1(end)));
  elseif ndims==3
    d1 = squeeze(netcdf.getVar(ncid,varid,itide-1,j(1):j(end),i1(1):i1(end)));
  elseif ndims==4
    d1 = squeeze(netcdf.getVar(ncid,varid,itide-1,0,j(1):j(end),i1(1):i1(end)));
  else
    error(['Bad dimension number ',num2str(ndims)])
  end
  data = cat(2,d1,data);
end
if ~isempty(i3)
  if ndims==2
    d3 = squeeze(netcdf.getVar(ncid,varid,j(1):j(end),i3(1):i3(end)));
  elseif ndims==3
    d3 = squeeze(netcdf.getVar(ncid,varid,itide-1,j(1):j(end),i3(1):i3(end)));
  elseif ndims==4
    d3 = squeeze(netcdf.getVar(ncid,varid,itide-1,0,j(1):j(end),i3(1):i3(end)));
  else
    error(['Bad dimension number ',num2str(ndims)])
  end
  data = cat(2,data,d3);
end

netcdf.close(ncid);
[x,y]=meshgrid(x,y);
end
