
% http://mexcdf.sourceforge.net/downloads/10b.php
%  uses version created for Matlab R2012b

%depl info
 veh='wgTiny';
 dep='20140521';
 pCO2sysID='WG1';
 pCO2cal = [-30.27890, 0.43639, 1.09200, -0.00243, 1];
 pHcal=[-0.393812 294.35];
 BBsensor='N/A';
 BBcal=[NaN NaN; NaN NaN; NaN NaN];
 BBwl={'lambda-1','lambda-2'};

if ismac
  pre='/Volumes/';
elseif ispc
  pre='//atlas.shore.mbari.org/'; %direction of / doesn't matter
else
  pre='/mbari/';
end

%working directory
 mydir=[pre 'WaveGlider/deployment_data/' veh '/' dep '/'];
 myfile=['SV3_' dep 'QC'];

%add nctoolbox
 addpath(genpath('U:\m\mexcdf'));
 
%load final WG txt data from makeTxt_SVx.m
 data=dlmread([mydir myfile '.txt'],',',1,0);

%format
 %time to s from epoch
  time=datenum(data(:,1:6));
  esec=(time-datenum([1970 1 1]))*86400;
  data=[esec data(:,7:end)];
 %lon to degrees west
  data(:,2)=-abs(data(:,2));
 %interpolate lat,lon,depth
  data(:,2)=deNaN(data(:,2));
  data(:,3)=deNaN(data(:,3));
  data(:,10)=deNaN(data(:,10));
 %make up a 'depth' for the met sensors
  data(:,end+1)=-1; %positive down

%define variable attributes
 ctdCoords='TIME CTD_depth LATITUDE LONGITUDE';
 bbCoords='TIME CTD_depth LATITUDE LONGITUDE'; %assume depths same
 metCoords='TIME met_depth LATITUDE LONGITUDE';

 attribName={'units','long_name','standard_name','_FillValue',...
   'coordinates'};
 attrib(1,:)={'seconds since 1970-01-01','time gmt','time',-999,''};
 attrib(2,:)={'deg E','LONGITUDE','longitude',-999,''};
 attrib(3,:)={'deg N','LATITUDE','latitude',-999,''};
 attrib(4,:)={'km','cumulative distance','',-999,ctdCoords};
 attrib(5,:)={'deg','wind direction','wind_from_direction',-999,...
   metCoords};
 attrib(6,:)={'m/s','average wind speed','wind_speed',-999,...
   metCoords};
 attrib(7,:)={'m/s','maximum wind speed','',-999,metCoords};
 attrib(8,:)={'mbar','atmospheric pressure',...
   'surface_air_pressure',-999,metCoords};
 attrib(9,:)={'C','air temperature','air_temperature',-999,metCoords};
 attrib(10,:)={'m','CTD depth','depth',-999,''};
 attrib(11,:)={'C','water temperature','sea_water_temperature',...
   -999,ctdCoords};
 attrib(12,:)={'psu','salinity','sea_water_salinity',-999,ctdCoords};
 attrib(13,:)={'umol/kg','oxygen concentration','',-999,ctdCoords};
 attrib(14,:)={'',['Beta-' BBwl{1}],'',-999,bbCoords};
 attrib(15,:)={'(1/(m sr))',['bb-' BBwl{1}],'',-999,bbCoords};
 attrib(16,:)={'',['Beta-' BBwl{2}],'',-999,bbCoords};
 attrib(17,:)={'(1/(m sr))',['bb-' BBwl{2}],'',-999,bbCoords};
 attrib(18,:)={'ug/l','chlorophyll',...
   'mass_concentration_of_chlorophyll_a_in_sea_water',-999,bbCoords};
 attrib(19,:)={'uatm','pCO2 in water',...
   'surface_partial_pressure_of_carbon_dioxide_in_sea_water',-999,...
   ctdCoords};
 attrib(20,:)={'uatm','pCO2 in air',...
   'surface_partial_pressure_of_carbon_dioxide_in_air',...
   -999,metCoords};
 attrib(21,:)={'total scale','pH','',-999,ctdCoords};
 attrib(22,:)={'m','depth of met sensors','depth',-999,''};

%define variable names
 varNames={'TIME','LONGITUDE','LATITUDE','distance','wind_dir',...
   'avg_wind_spd','max_wind_spd','atm_press','air_temp',...
   'CTD_depth','water_temp','sal','O2_conc',...
   ['beta_' BBwl{1}],['bb_' BBwl{1}],['beta_' BBwl{2}],...
   ['bb_' BBwl{2}],'chl','pCO2_water','pCO2_air','pH','met_depth'};

%define Global Attributes
 globAttrib.distribution_statement=['Any use requires prior ' ...
   'approval from the MBARI CANON PI: Dr. Francisco Chavez.'];
 globAttrib.conventions='CF-1.6';
 globAttrib.Unlimited_Dimension='time';
 globAttrib.featureType='trajectory';
 globAttrib.title=['MBARI Wave Glider survey. ' ...
   'Monterey Bay, California.'];
 globAttrib.inst_type=['Wave Glider ''SV3/Tiny'''];
%  globAttrib.pHloggernum=pHloggernum;
 globAttrib.pHcal=sprintf('%s%.6f%s%.0f%s',...
   'E0 = ', pHcal(1), '  Ts = ', pHcal(2), ' K');
 globAttrib.pCO2sysID=pCO2sysID;
 globAttrib.pCO2cal=sprintf( '%s%.4f %s%.4f %s%.4f %s%.6f %s%.4f',...
   'A = ', pCO2cal(1), '  B = ', pCO2cal(2), '  C = ', pCO2cal(3), ...
   '  D = ', pCO2cal(4), '  E = ', pCO2cal(5) ); 
 globAttrib.BBsensor=BBsensor;
 globAttrib.BBcal=sprintf('%s%.8f%s%.0f%s %s%.8f%s%.0f%s %s%.8f%s%.0f',...
   [BBwl{1} ': SF = '], BBcal(1,1), '  Dark = ', BBcal(1,2), ';  ', ...
   [BBwl{2} ': SF = '], BBcal(2,1), '  Dark = ', BBcal(2,2), ';  ', ...
   'Chl: SF = ', BBcal(3,1), '  Dark = ', BBcal(3,2) );

 globAttrib.geospatial_lat_units='degree_north';
 globAttrib.geospatial_lat_min=min(data(:,3));
 globAttrib.geospatial_lat_max=max(data(:,3));
 globAttrib.geospatial_lon_units='degree_west';
 globAttrib.geospatial_lon_min=min(data(:,2));
 globAttrib.geospatial_lon_max=max(data(:,2));
 globAttrib.geospatial_vertical_min=min(data(:,22)); %met depth
 globAttrib.geospatial_vertical_max=max(data(:,10)); %ctd depth
 globAttrib.geospatial_vertical_units='m';
 globAttrib.geospatial_vertical_positive='down';
 globAttrib.time_coverage_start=datestr(time(1),'yyyy-mm-ddTHH:MM:SS');
 globAttrib.time_coverage_end=datestr(time(end),'yyyy-mm-ddTHH:MM:SS');
 
 globAttrib.processing_level=[ ...
   'Raw data has been processed and averaged to a common 10-min ' ...
   'time stamp.'];

 globAttrib.creationDate='08/03/2015';
 globAttrib.lastModified=datestr(now,'mm/dd/yyyy');

 globAttrib.source=['Monterey Bay Aquarium Research ' ...
   'Institute (MBARI), Biological Ocean Group'];
 globAttrib.institution=['Monterey Bay Aquarium Research ' ...
   'Institute (MBARI)'];
 globAttrib.site_code='MBARI';
 globAttrib.publisher_name='Monterey Bay Aquarium Research Institute';
 globAttrib.publisher_url='http://www.mbari.org/';
 globAttrib.license=['Any use requires prior approval from the ' ...
   'MBARI CANON PI: Dr. Francisco Chavez.'];
 globAttrib.citation=['MBARI provides data "as is", with no ' ...
   'warranty, express or implied, of the quality or ' ...
   'consistency. Data are provided without support and ' ...
   'without obligation on the part of the Monterey Bay ' ...
   'Aquarium Research Institute to assist in its use, ' ...
   'correction, modification, or enhancement.'];

 globAttrib.campaign_info=['Contact Francisco Chavez: ' ...
   'chfr at mbari.org'];
 globAttrib.project_info='Contact Francisco Chavez: chfr at mbari.org';
 globAttrib.data_info='Contact Jeff Sevadjian: jsevadjian at mbari.org';
 globAttrib.file_info='Contact Jeff Sevadjian: jsevadjian at mbari.org';
 globAttrib.var_desc=['10-min Wave Glider Data: ' ...
   'wind speed/direction, atmospheric pressure, air temperature, ' ...
   'water temperature, salinity, dissolved oxygen, ' ...
   'optical backscatter, chlorophyll fluorescence, ' ...
   'pCO2 in air/water, pH'];
 globAttrib.keywords=['Ocean Acidification,OA,Monterey Bay,' ...
   'Central California,Wave Glider,2015,pCO2,pH'];
 globAttrib.summary=['Observational oceanographic data obtained ' ...
   'from a mobile platform. SV3/"Tiny" Wave ' ...
   'Glider with meterological and near-ocean surface sensors to ' ...
   'monitor the concentrations of oceanic and atmospheric pCO2.'];
 globAttrib.program=['Matlab program makeNetcdf_SV3_20140521.m. ' ...
   'Input file from ' ...
   mydir myfile '.txt'];
 
 globAttrib.missing_value=-999;
 globAttrib.FillValue=-999;
%  globAttrib.id=['http://odss.mbari.org/thredds/catalog/' ...
%    'CANON_september2013/Platforms/Gliders/WG_OA/final/' ...
%    myfileOut];

%now format NaNs to -999
 f=find(isnan(data));
 data(f)=-999;
 clear f;

%create empty netcdf file on the hard drive
 nc_create_empty([mydir myfile '.nc'],'clobber');

%add dimensions
 nc_adddim([mydir myfile '.nc'],'time',0); %unlimited

%write global attributes to the nc file
 fn=fieldnames(globAttrib);
 for n=1:length(fn)
   nc_attput([mydir myfile '.nc'],nc_global,...
    fn{n},globAttrib.(fn{n}));
 end
 clear fn n;

%write 'Variables'; re-arrange to correct format
 for n=1:size(attrib,1)
   clear v;
   v.Name=varNames{n};
   v.Datatype='double';
   v.Dimension={'time'};
   for m=1:size(attrib,2)
     v.Attribute(m).Name=attribName{m};
     v.Attribute(m).Value=attrib{n,m};
   end
    nc_addvar([mydir myfile '.nc'],v);
    nc_varput([mydir myfile '.nc'],v.Name,data(:,n));
 end
 clear n m;

%check
 addpath(genpath('U:\m\'));
 setup_nctoolbox;
 ds = ncdataset([mydir myfile '.nc']);
 for n=1:length(ds.variables)
   figure;
   plot(ds.time('TIME'),ds.data(ds.variables(n)),'.-');
   title(ds.variables(n));
 end
