% mat2asc_met.m
% read OceanSite netcdf met variables to ascii column file  
% reference: matlabroot/toolbox/netcdf/ncutility/nudump.m
clear all;

experiment='stratus';
eyr={'200010';'200110';'200210';'200311';'200412';'200510';'200610';'200710'};
nexp=8;

experiment='whots';
eyr={'200408';'200507';'200606';'200706'};
nexp=4;

experiment='ntas';
eyr={'200103';'200203';'200302';'200402';'200502'};
nexp=5;

for index=2:nexp;

OTSHOME = ['/volumes/buoy_disk/users/shared/OceanSITES/' experiment '/'];
OTS_nc_in = ['OS_' experiment '_' eyr{index} '_M.nc' ];
OTS_asc_out = ['OS_' experiment '_' eyr{index} '_M.asc' ];

% such as convert OS_stratus_200710_M.nc to OS_stratus_200710_M.asc

addpath(OTSHOME);
addpath([matlabroot '/toolbox/netcdf']);
addpath([matlabroot '/toolbox/netcdf/ncutility']);
addpath([matlabroot '/toolbox/netcdf/nctype']);

% OceanSite ncfile % Open NetCDF file.

infile=[OTSHOME OTS_nc_in];
outfile=[OTSHOME OTS_asc_out];

disp(['infile: ' infile]);
disp(['outfile: ' outfile]);

nc = netcdf(infile, 'nowrite');

[ndims, nvars, ngatts, recdim] = size(nc);

dims = dim(nc); ndims = length(dims);
vars = var(nc); nvar = length(vars);
gatts = att(nc); ngatts = length(gatts);

for i = 1:nvar;
    cmd = sprintf('%s = vars {%d} (:);', name(vars{i}),i);
    eval (cmd);
end

fid = fopen(outfile,'w');

fprintf (fid,'%% %s:\n',OTS_asc_out);
fprintf (fid,'%% Global attributes:\n');
for i = 1:ngatts
   varid = -1;
   attnum = i-1;
   attname = name(gatts{i});
   attvalue = gatts{i}(:);
   fprintf(fid, '%%    %s = %s\n', attname, num2str(attvalue));
end
fprintf(fid, '%%\n');
fprintf(fid, '%% Variables:\n');

s_name=[];
s_units=[];
s_format=[];
for j = 1:nvars;
   varid = j-1;
   varname = name(vars{j});
   if strcmp(varname,'time')
      s_name = [s_name '  YEAR  MONTH DAY  HOUR MINUTE SECOND'];
   elseif (strcmp(varname, 'depth')==1 | ...
	  strcmp(varname, 'latitude')==1 | ...
          strcmp(varname, 'longitude')==1) 
          s_name=s_name; % do not add to s_name
   else
      s_name=[s_name '  ' varname];
   end
   varname = strrep(varname, '''', '''''');
   theDatatype = datatype(vars{j});
   theDatatype = ['nc' theDatatype];
   dims = dim(vars{j});
   ndims = length(dims);
   atts = att(vars{j});
   natts = length(atts);
   s = ['%    ' theDatatype ' ' varname];
   for i = 1:ndims
      dimname = name(dims{i});
      dimname = strrep(dimname, '''', '''''');
      dimlen = ncsize(dims{i});
      if i == 1, s = [s '(']; end
      if i > 1, s = [s, ', ']; end
      s = [s  dimname];
      if i == ndims, s = [s ')']; end
   end
   s = [s ';'];
   elements = prod(ncsize(vars{j}));
   s = [s ' ' int2str(elements) ' element'];
   if elements ~= 1, s = [s 's']; end
   s = [s '.'];
   fprintf(fid, '%s\n', s);
   for i = 1:natts
      attnum = i-1;
      theDatatype = datatype(atts{i});
      theDatatype = ['nc' theDatatype];
      attname = name(atts{i});
      if strcmp(attname, '_FillValue')
         continue;
      end
      if any(attname ~= '_')
         while attname(1) == '_'
            attname = [attname(2:length(attname)) attname(1)];
         end
      end
      attname = strrep(attname, '''', '''''');
      attlen = ncsize(atts{i});
      attvalue = atts{i}(:);
      s = ['%        ' varname ':' attname ' = ' theDatatype];
      t = mat2str(attvalue);
      t = ['(' t ')'];
      s = [s t ';'];
      fprintf(fid, '%s\n', s);
      if strcmp(attname, 'units')
         if strcmp(varname,'time')
             s_units = [s_units ' (utc) (utc) (utc) (utc) (utc) (utc)'];
         elseif (strcmp(varname, 'depth')==1 | ...
             strcmp(varname, 'latitude')==1 | ...
             strcmp(varname, 'longitude')==1) 
             s_units=s_units; % do not add to s_units
         else
            if strcmp(t,'(degree_C)')
               t='(degC)';
            elseif strcmp(t,'(millibars)')
               t='(mbar)';
            elseif strcmp(t,'(percent)')
               t='(%)';
            elseif strcmp(t,'(mm/hour)')
               t='(mm/h)';
            elseif strcmp(t,'(W m-2)')
               t='(Wm-2)';
            elseif strcmp(t,'(meters/second)')
               t='(m/s)';
            elseif strcmp(t,'(1)')
               t='(PSU)';
            end
            s_units = [s_units ' ' t];
         end
      end
      if strcmp(attname, 'format')
         s_format = [s_format '   ' t];
         t1=regexprep(t,'[()]','');
         format{j}=t1;
      end
   end
   s = '%';
   fprintf(fid, '%s\n', s);
end
fprintf (fid,'%%\n');

% print depth, latitude, and longitude
for j=1:nvars;
    varname = name(vars{j});
    if (strcmp(varname, 'depth')==1) 
       fprintf(fid, '%%  %s=%10.3f\n', varname, vars{j}(1)); 
    elseif(strcmp(varname, 'latitude')==1 | ...
            strcmp(varname, 'longitude')==1)
       fprintf(fid, '%%  %s=%10.4f\n', varname, vars{j}(1));   
    end
end

fprintf (fid,'%%\n');

fprintf (fid, '%%%s\n',s_name);
fprintf (fid, '%%%s\n',s_units);

fprintf (fid,'%%\n');

mdate=time+datenum(1950,1,0); % time is days since 1950,1,1
[yr,mon,day,hr,mn,sc]=datevec(mdate);

% find second column with values near 60 and near zero
ff=find(sc>=59.9); % round up 60s to 1min
if(length(ff)>0)
   sc(ff)=0;
   mn(ff)=mn(ff)+1;
end
ff=find(sc <= 0.00001); % round up 7.63e-06 to 0sec
if(length(ff)>0)
   sc(ff)=0;
end
%set up fprintf format for variable matrix 
%form data column into matrix mvars: length(varibles)xlength(time)
for j=1:nvars;
   varname = name(vars{j});
   if (strcmp(varname, 'depth')==1 | ...
         strcmp(varname, 'latitude')==1 | ...
           strcmp(varname, 'longitude')==1)
         continue;  % skip
   end
   if strcmp(varname, 'time')
       m_format='%4.4d %2.2d %2.2d %2.2d %2.2d %2.2d';
       mvars=[yr';mon';day';hr';mn';sc'];
   else
       m_format=[m_format ' %' format{j}];
       mvars=[mvars;vars{j}'];
   end
end
m_format=[m_format '\n'];

% write the entire matrix out at once to avoid the for loop
eval(['fprintf(fid,''' m_format ''',mvars);']);

fclose(fid);
clear infile outfile nc vars mdate fid m_format mvars
end
