function status=oct_write_mask(Gname,rmask,umask,vmask,pmask)
% OCT_WRITE_MASK write mask variables into NetCDF using octave-oct_netcdf
status=0;
ncid = netcdf.open(Gname,'NC_WRITE');

% helper to ensure var exists (define if needed)
function ensure_var(varname,dimY,dimX,longname)
  try
    vid = netcdf.inqVarID(ncid,varname);
  catch
    % define variable
    netcdf.reDef(ncid);
    dimYid = netcdf.inqDimID(ncid,dimY);
    dimXid = netcdf.inqDimID(ncid,dimX);
    varid = netcdf.defVar(ncid,varname,netcdf.getConstant('NC_DOUBLE'),[dimYid dimXid]);
    netcdf.putAtt(ncid,varid,'long_name',longname);
    netcdf.endDef(ncid);
  end
end

% ensure mask vars
ensure_var('mask_rho','eta_rho','xi_rho','mask on RHO-points');
ensure_var('mask_u','eta_u','xi_u','mask on U-points');
ensure_var('mask_v','eta_v','xi_v','mask on V-points');
ensure_var('mask_psi','eta_psi','xi_psi','mask on PSI-points');

% write variables
netcdf.putVar(ncid,netcdf.inqVarID(ncid,'mask_rho'),rmask);
netcdf.putVar(ncid,netcdf.inqVarID(ncid,'mask_u'),umask);
netcdf.putVar(ncid,netcdf.inqVarID(ncid,'mask_v'),vmask);
netcdf.putVar(ncid,netcdf.inqVarID(ncid,'mask_psi'),pmask);

netcdf.close(ncid);
status=1;
return
