function convert_grd_geo2utm(grdfile,grdfileNew)
% Converts .grd file from Lat Lon to UTM
%
% Created by: Sarah Houts

ncid = netcdf.open(grdfile, 'NC_NOWRITE');
% ncidNew = netcdf.create(grdfileNew,'NETCDF4');
ncidNew = netcdf.create(grdfileNew,'CLOBBER');

% get information on the contents of this netcdf file
[ndims, nvars, natts] = netcdf.inq(ncid);

% load dimensions - (independent variables)
dimLength = ones(ndims,1);
dimID = ones(ndims,1);
for i = 1:ndims
    [dimName{i}, dimLength(i)] = netcdf.inqDim(ncid, i-1);
    dimID(i) = netcdf.defDim(ncidNew,dimName{i},dimLength(i));
end

% load variables
varNdims = ones(nvars,1);
varNatts = ones(nvars,1);
varDatatype = ones(nvars,1);

for i = 1:nvars
    [varName{i}, varDatatype(i), dim, varNatts(i)] = netcdf.inqVar(ncid, i-1);
    assignin('base', strcat('dim', num2str(i)), dim);
    netcdf.defVar(ncidNew, varName{i}, 'double', dim);
end


% Get ranges for east and north coordinates
xRange = netcdf.getAtt(ncid,0,'actual_range');
yRange = netcdf.getAtt(ncid,1,'actual_range');
zRange = netcdf.getAtt(ncid,2,'actual_range');

% Convert ranges to UTM
Lat = yRange;
Lon = xRange;
[xRangeutm yRangeutm utmzone] = deg2utm(Lat,Lon);

netcdf.putAtt(ncidNew,0,'actual_range',xRangeutm);
netcdf.putAtt(ncidNew,1,'actual_range',yRangeutm);
netcdf.putAtt(ncidNew,2,'actual_range',zRange);

% zFill = netcdf.getAtt(ncid,2,'_FillValue');
% netcdf.putAtt(ncidNew,2,'_FillValue',NaN);
% netcdf.defVarFill(ncidNew,2,false,double(zFill));
% netcdf.defVarFill(ncidNew,2,false,NaN);

xName = netcdf.getAtt(ncid,0,'long_name');
yName = netcdf.getAtt(ncid,1,'long_name');
zName = netcdf.getAtt(ncid,2,'long_name');

netcdf.putAtt(ncidNew,0,'long_name',xName);
netcdf.putAtt(ncidNew,1,'long_name',yName);
netcdf.putAtt(ncidNew,2,'long_name',zName);

% extract data from variables
x = netcdf.getVar(ncid, 0, 0, dimLength(1));
y = netcdf.getVar(ncid, 1, 0, dimLength(2));

% convert to UTM
Lat = y;
Lon = repmat(x(1),length(y),1);
[xblah yutm utmzone1] = deg2utm(Lat, Lon);
Lat = repmat(y(1),length(x),1);
Lon = x;
[xutm yblah utmzone2] = deg2utm(Lat,Lon);
x = xutm;
y = yutm;


% Check if Z variable is depth or topo
if strncmp(zName,'Depth',5)
    z = netcdf.getVar(ncid, 2, [0 0], [dimLength(1) dimLength(2)]);
else    % Depth = -topo
    z = -netcdf.getVar(ncid, 2, [0 0], [dimLength(1) dimLength(2)]);
end

netcdf.endDef(ncidNew);


netcdf.putVar(ncidNew,0,0,dimLength(1),double(x));
netcdf.putVar(ncidNew,1,0,dimLength(2),double(y));

netcdf.putVar(ncidNew,2,[0 0],[dimLength(1) dimLength(2)],double(z));

netcdf.sync(ncidNew);

netcdf.close(ncid);
netcdf.close(ncidNew);

