function []=step05a_short_write_nc(MITprof,fileOut)

%-----------------
%function ()=step05a_short_write_nc(MITprof,fileOut)
% input: MITprof structure
%        fileOut (full path and name)
% output:none, MITprof is written out to fileOut (nc file)
%
% 07-Jun-2013: augmented info related to tiles. use this from now on instead of step05_write_nc.m
% after ~/matlab_gcmfaces/MITprof/profiles_IO_v2/MITprof_create.m
%addpath('/data4/atnguyen/matlab_gcmfaces/MITprof/profiles_misc');
%-----------------

flagT=isfield(MITprof,'prof_T');
flagS=isfield(MITprof,'prof_S');
flagU=isfield(MITprof,'prof_U');
flagV=isfield(MITprof,'prof_V');
flagPT=isfield(MITprof,'prof_ptr');
flagSSH=isfield(MITprof,'prof_ssh');
flagBP=isfield(MITprof,'prof_bp');

nLev=length(MITprof.prof_depth);
MITprof.prof_depth=reshape(MITprof.prof_depth,length(MITprof.prof_depth),1);
nProf=length(MITprof.prof_point);
iPROF=nProf; iDEPTH=nLev; iINTERP=1;

%22.jun.2015: seems like prof_descr needs to be char and not cell
% use these 2 functions to swap back and forth: a=char(b) and b=cellstr(a)
if(iscell(MITprof.prof_descr)>0);MITprof.prof_descr=char(MITprof.prof_descr);end;
lTXT=size(MITprof.prof_descr,2); fillval=double(-9999);

%06.Mar.2014: check Tweight and Sweight here, make sure it's zero and not -9999
%18.Jun.2015: check Uweight and Vweight here, make sure it's zero and not -9999/nan
%22.Jun.2015; check T,S,U,V here to make sure -9999 and not NaN. 
%             Also mask out weights to zeros where T,S,U,V are -9999

varstr={'T','S','U','V'};
for ivar=1:size(varstr,2);
  eval(['fflag=flag' varstr{ivar} ';']);
  if(fflag==1);
    clear temp tempweight
    eval(['temp=MITprof.prof_' varstr{ivar} ';']);
    eval(['tempweight=MITprof.prof_' varstr{ivar} 'weight;']);

    eval(['MITprof.prof_' varstr{ivar} 'flag=zeros(size(temp));']);
    clear ii;ii=find(isnan(tempweight)==1);if(length(ii)>0);tempweight(ii)=0;end;
    clear ii;ii=find(tempweight(:)<0);if(length(ii)>0);tempweight(ii)=0;end;
    clear ii;ii=find(isnan(temp)==1);if(length(ii)>0);temp(ii)=fillval;tempweight(ii)=0;end;

%13.Feb.2017: add : Also mask out weights to zeros where T,S,U,V are -9999
    clear ii;ii=find(temp(:)<-9000);if(length(ii)>0);tempweight(ii)=0;end;

    eval(['MITprof.prof_' varstr{ivar} '=temp;']);
    eval(['MITprof.prof_' varstr{ivar} 'weight=tempweight;']);
  end;
end;

%=============list of variables that will actually be in the file==============%
             list_vars=           {'prof_T','prof_Tweight','prof_Testim','prof_Terr','prof_Tflag'};
if(flagS==1);list_vars=[list_vars {'prof_S','prof_Sweight','prof_Sestim','prof_Serr','prof_Sflag'}];end;
if(flagU==1);list_vars=[list_vars {'prof_U','prof_Uweight','prof_Uestim','prof_Uerr','prof_Uflag'}];end;
if(flagV==1);list_vars=[list_vars {'prof_V','prof_Vweight','prof_Vestim','prof_Verr','prof_Vflag'}];end;

list_vars_plus=[{'prof_depth','prof_descr','prof_date','prof_YYYYMMDD','prof_HHMMSS',...
    'prof_lon','prof_lat','prof_basin','prof_point'}...
    list_vars];

%profiles_process_main_v2/profiles_prep_mygrid.m
list1d={'prof_interp_XC11','prof_interp_YC11','prof_interp_XCNINJ','prof_interp_YCNINJ'};
list2d={'prof_interp_i','prof_interp_j','prof_interp_lon','prof_interp_lat','prof_interp_weights'};
listAll={list1d{:},list2d{:}};

%==========masters table of variables, units, names and dimensions=============%

mt_v={'prof_depth'}; mt_u={'me'}; mt_n={'depth'}; mt_d={'iDEPTH'};
%mt_v=[mt_v '']; mt_u=[mt_u ' ']; mt_n=[mt_n '']; mt_d=[mt_d ''];
mt_v=[mt_v 'prof_date'];     mt_u=[mt_u ' ']; mt_n=[mt_n 'Julian day since Jan-1-0000'];                           mt_d=[mt_d 'iPROF'];
mt_v=[mt_v 'prof_YYYYMMDD']; mt_u=[mt_u ' ']; mt_n=[mt_n 'year (4 digits), month (2 digits), day (2 digits)'];     mt_d=[mt_d 'iPROF'];
mt_v=[mt_v 'prof_HHMMSS'];   mt_u=[mt_u ' ']; mt_n=[mt_n 'hour (2 digits), minute (2 digits), second (2 digits)']; mt_d=[mt_d 'iPROF'];
mt_v=[mt_v 'prof_lon'];      mt_u=[mt_u ' ']; mt_n=[mt_n 'Longitude (degree East)'];                               mt_d=[mt_d 'iPROF'];
mt_v=[mt_v 'prof_lat'];      mt_u=[mt_u ' ']; mt_n=[mt_n 'Latitude (degree North)'];                               mt_d=[mt_d 'iPROF'];
mt_v=[mt_v 'prof_basin'];    mt_u=[mt_u ' ']; mt_n=[mt_n 'ocean basin index (ecco 4g)'];                           mt_d=[mt_d 'iPROF'];
mt_v=[mt_v 'prof_point'];    mt_u=[mt_u ' ']; mt_n=[mt_n 'grid point index (ecco 4g)'];                            mt_d=[mt_d 'iPROF'];
%
mt_v=[mt_v 'prof_T'];       mt_u=[mt_u 'degree C'];      mt_n=[mt_n 'potential temperature'];                    mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Tweight']; mt_u=[mt_u '(degree C)^-2']; mt_n=[mt_n 'pot. temp. least-square weight'];           mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Testim'];  mt_u=[mt_u 'degree C'];      mt_n=[mt_n 'pot. temp. estimate (e.g. from atlas)'];    mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Terr'];    mt_u=[mt_u 'degree C'];      mt_n=[mt_n 'pot. temp. instrumental error'];            mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Tflag'];   mt_u=[mt_u ' '];             mt_n=[mt_n 'flag = i > 0 means test i rejected data.']; mt_d=[mt_d 'iPROF,iDEPTH'];
%
if(flagS==1);
mt_v=[mt_v 'prof_S'];       mt_u=[mt_u 'psu'];      mt_n=[mt_n 'salinity'];                                 mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Sweight']; mt_u=[mt_u '(psu)^-2']; mt_n=[mt_n 'salinity least-square weight'];             mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Sestim'];  mt_u=[mt_u 'psu'];      mt_n=[mt_n 'salinity estimate (e.g. from atlas)'];      mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Serr'];    mt_u=[mt_u 'psu'];      mt_n=[mt_n 'salinity instrumental error'];              mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Sflag'];   mt_u=[mt_u ' '];        mt_n=[mt_n 'flag = i > 0 means test i rejected data.']; mt_d=[mt_d 'iPROF,iDEPTH'];
end;
%
if(flagU==1);
mt_v=[mt_v 'prof_U'];       mt_u=[mt_u 'm/s'];      mt_n=[mt_n 'eastward velocity comp.'];                  mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_U'];       mt_u=[mt_u 'm/s'];      mt_n=[mt_n 'eastward velocity comp.'];                  mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_U'];       mt_u=[mt_u 'm/s'];      mt_n=[mt_n 'eastward velocity comp.'];                  mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Uweight']; mt_u=[mt_u '(m/s)^-2']; mt_n=[mt_n 'east. v. least-square weight'];             mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Uestim'];  mt_u=[mt_u 'm/s'];      mt_n=[mt_n 'east. v. (e.g. from atlas)'];               mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Uerr'];    mt_u=[mt_u 'm/s'];      mt_n=[mt_n 'east. v. instrumental error'];              mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Uflag'];   mt_u=[mt_u ' '];        mt_n=[mt_n 'flag = i > 0 means test i rejected data.']; mt_d=[mt_d 'iPROF,iDEPTH'];
end;
if(flagV==1)
mt_v=[mt_v 'prof_V'];       mt_u=[mt_u 'm/s'];      mt_n=[mt_n 'northward velocity comp.'];                 mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Vweight']; mt_u=[mt_u '(m/s)^-2']; mt_n=[mt_n 'north. v. least-square weight'];            mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Vestim'];  mt_u=[mt_u 'm/s'];      mt_n=[mt_n 'north. v. (e.g. from atlas)'];              mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Verr'];    mt_u=[mt_u 'm/s'];      mt_n=[mt_n 'north. v. instrumental error'];             mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_Vflag'];   mt_u=[mt_u ' '];        mt_n=[mt_n 'flag = i > 0 means test i rejected data.']; mt_d=[mt_d 'iPROF,iDEPTH'];
end;
if(flagPT==1);
mt_v=[mt_v 'prof_ptr'];       mt_u=[mt_u 'X'];      mt_n=[mt_n 'passive tracer'];                   mt_d=[mt_d 'iPROF,iDEPTH'];
mt_v=[mt_v 'prof_ptrweight']; mt_u=[mt_u '(X)^-2']; mt_n=[mt_n 'pass. tracer least-square weight']; mt_d=[mt_d 'iPROF,iDEPTH'];
end;
%
if(flagBP==1);
mt_v=[mt_v 'prof_bp'];       mt_u=[mt_u 'cm'];      mt_n=[mt_n 'bottom pressure'];                mt_d=[mt_d 'iPROF'];
mt_v=[mt_v 'prof_bpweight']; mt_u=[mt_u '(cm)^-2']; mt_n=[mt_n 'bot. pres. least-square weight']; mt_d=[mt_d 'iPROF'];
end;
if(flagSSH==1);
mt_v=[mt_v 'prof_ssh'];       mt_u=[mt_u 'cm'];      mt_n=[mt_n 'sea surface height'];      mt_d=[mt_d 'iPROF'];
mt_v=[mt_v 'prof_sshweight']; mt_u=[mt_u '(cm)^-2']; mt_n=[mt_n 'ssh least-square weight']; mt_d=[mt_d 'iPROF'];
end;

%=============================create the file=================================%
% write the netcdf structure

global useNativeMatlabNetcdf;
if isempty(useNativeMatlabNetcdf); useNativeMatlabNetcdf = ~isempty(which('netcdf.open')); end;
%if(useNativeMatlabNetcdf);ncmodestr='CLOBBER';else;ncmodestr='CLOBBER';end;
ncmodestr='CLOBBER';
ncid=nccreate(fileOut,ncmodestr);

aa=sprintf(['Format: MITprof netcdf. This file was created using \n' ...
    'the matlab toolbox which can be obtained (see README) from \n'...
    'http://mitgcm.org/viewvc/MITgcm/MITgcm_contrib/gael/profilesMatlabProcessing/']);
ncputAtt(ncid,'','description',aa);
ncputAtt(ncid,'','date',date);

ncdefDim(ncid,'iPROF',iPROF);
ncdefDim(ncid,'iDEPTH',iDEPTH);
ncdefDim(ncid,'lTXT',lTXT);
ncdefDim(ncid,'iINTERP',iINTERP);

for ii=1:length(list_vars_plus);
    jj=find(strcmp(mt_v,list_vars_plus{ii}));
    if ~isempty(jj);
        if strcmp(mt_d{jj},'iPROF,iDEPTH');
            ncdefVar(ncid,mt_v{jj},'double',{'iDEPTH','iPROF'});%note the direction flip
            %ncdefVar(ncid,mt_v{jj},'double',{'iPROF','iDEPTH'});
        else;
            ncdefVar(ncid,mt_v{jj},'double',{mt_d{jj}});
        end;
        ncputAtt(ncid,mt_v{jj},'long_name',mt_n{jj});
        ncputAtt(ncid,mt_v{jj},'units',mt_u{jj});
        ncputAtt(ncid,mt_v{jj},'missing_value',fillval);
        ncputAtt(ncid,mt_v{jj},'_FillValue',fillval);
    else;
        if strcmp(list_vars_plus{ii},'prof_descr')
            ncdefVar(ncid,'prof_descr','char',{'lTXT','iPROF'});%think this is a mistake
            %ncdefVar(ncid,'prof_descr','char',{'iPROF','lTXT'});
            ncputAtt(ncid,'prof_descr','long_name','profile description');
        else
            warning([list_vars_plus{ii} ' not included -- it is not a MITprof variable']);
        end
    end;
end;

for ii=1:length(list1d); ncdefVar(ncid,list1d{ii},'double',{'iPROF'});end;
for ii=1:length(list2d); ncdefVar(ncid,list2d{ii},'double',{'iINTERP','iPROF'});end;

ncclose(ncid);

%===========================write data ======================================%
% write to file:
nc=ncopen(fileOut,'write');
vars=ncvars(nc);
list_vars=intersect(vars,list_vars_plus);
for ii=1:length(list_vars);
    fprintf('%i ',ii);
    varname=list_vars{ii};
    data=getfield(MITprof,varname);
    if(isnumeric(data)>0);spval=ncgetFillVal(nc,varname);end;
    if isnumeric(data)
        if isempty(spval),
            warning(['no FillVal for ' varname ': use of -9999 default value']);
            spval=double(-9999);
        end
        data(isnan(data))=spval;
        MITprof=setfield(MITprof,varname,data);
    end
    ncputvar(nc,varname,data);
end
for ii=1:length(listAll);ncputvar(nc,listAll{ii},getfield(MITprof,listAll{ii}));end;

ncclose(nc);


%%%%%%%%% done %%%%%%%%%

clear mt_* list_vars* nLev fillval ii jj lTXT nProf aa data spval varname vars
return
