function ncMicrocat(filename, ncFilename)
% ncMicrocat - Convert a concatenated oasis microcat file to netcdf
%
% This assumes the file is in the usual Oasis format. The file will have the
% following columns: dayOfYear temp(C) conductivity ctdTime
%
% Use as: ncMicrocat(filename, ncFilename)
%
% Inputs: filename = name of the microcat data file to read
%         ncFilename = the name of the netcdf file to create

% Brian Schlining
% 16 May 2000

%===========
% Open File
%===========
if ~nargin | isempty(filename)
   [infile inpath] = uigetfile('*.*','Select microcat data file',0,0);
   if infile == 0
      return                            % Return if CANCEL is selected
   end
   filename = [inpath infile];
   if nargin < 2 | isempty(ncFilename)
      [p f ext] = fileparts(filename);
      ncFilename = [p f '.nc'];
   end
   
end

fid = fopen(filename, 'rt');

if fid <= 0
   error(['Unable to open ' filename])
else
   outfile = netcdf(ncFilename, 'clobber');
   if isempty(outfile)
      fclose(fid);
      error(['Unable to create ' ncFilename]);
   end
   
end


%========================
% Set defualt parameters
%========================
n     = 0;              % Line counter
R     = 4.2914;         % Conductivity ratio denominator
depth = 1;              % Depth of microcat in dbar

%=================================================================
% Construct Netcdf schema for a single microcat on eqpac moorings
%=================================================================
[Year Month Day]     = datevec(now);
dateS                = sprintf('%02i/%02i/%04i', Month, Day, Year);

outfile.conventions  = 'MBARI/timeSeries/mooring/microcat';
outfile.creationDate = dateS;
outfile.lastModified = dateS;
%mooring              = input('Enter mooring ID (All CAPS): '); % Needed to specify mooring location
mooring='EP1';
fprintf(1,'Creating netcdf schema')
outfile.mooring      = mooring;
outfile.description  = 'Moored microcat CTD data from the Equatorial Pacific';

% Give location based on user input
switch lower(mooring)
case 'ep1'
   outfile.longitude = '155W';
   outfile.latitude  = '0';
   lon = -150;
   lat = 0;
case 'ep2'
   outfile.longitude = '170W';
   outfile.latitude  = '2S';
   lon = -170;
   lat = -2;
end

outfile.waterDepth             = '4000m';
outfile.keywords               = 'salinity, temperature, microcat';
outfile.instumentType          = 'Serial microcat';

outfile('latitude')            = 1;                     % Dimension
outfile{'latitude'}            = ncdouble('latitude');  % Specify Co-ordinate variable dimensions
outfile{'latitude'}.long_name  = 'Latitude';
outfile{'latitude'}.units      = 'degrees_north (+N/-S)';
outfile{'latitude'}(:)         = lat;

outfile('longitude')           = 1;                     % Dimension
outfile{'longitude'}           = ncdouble('longitude'); % Specify Co-ordinate variable dimensions
outfile{'longitude'}.long_name = 'Longitude';
outfile{'longitude'}.units     = 'degrees_east (+E/-W)';
outfile{'longitude'}(:)        = lon;

outfile('depth')               = 1;                     % Dimension
outfile{'depth'}               = ncdouble('depth'); % Specify Co-ordinate variable dimensions
outfile{'depth'}.long_name     = 'Depth';
outfile{'depth'}.units         = 'meters';
outfile{'depth'}.positive      = 'down';
outfile{'depth'}(:)            = 1.5;

outfile('time')                = 0;                     % Define Unlimited dimension
outfile{'time'}                = ncdouble('time');
outfile{'time'}.long_name      = 'time GMT';
outfile{'time'}.units          = 'seconds since 1970-01-01 00:00:00';

outfile{'temp'}                = ncfloat('time','latitude','longitude','depth');
outfile{'temp'}.long_name      = 'Temperature';
outfile{'temp'}.units          = 'Celsius';
outfile{'temp'}.symbol         = 'T';
outfile{'temp'}.FillValue_     = -999;
outfile{'temp'}.missing_value  = -999;

outfile{'sal'}                = ncfloat('time','latitude','longitude','depth');
outfile{'sal'}.long_name      = 'Salinity';
outfile{'sal'}.units          = 'psu';
outfile{'sal'}.symbol         = 'S';
outfile{'sal'}.FillValue_     = -999;
outfile{'sal'}.missing_value  = -999;

fprintf(1,'...completed\n')

%====================
% Read the data file
%====================
numOfLines = 200000;                   % Specify memory capacity
fprintf(1,'Reading microcat data.')
dayOfYear = ones(numOfLines,1)*-999;
year = dayOfYear;                      % Initialize memory
temp = dayOfYear;                      % Initialize memory
C    = dayOfYear;                      % Initialize memory
dateS = cell(numOfLines,1);            % Initialize memory

while ~feof(fid)                       % Loop through each line of the file
   s = fgetl(fid);
   buf = sscanf(s, '%f %f, %f');       % Grab the first three values
   if (length(buf) == 3)
      n = n + 1;
      temp(n) = buf(2);                % Temperature is second value on the line
      C(n)    = buf(3);                % Conductivity is the third value on the line
      mdy     = stringtokenizer(s, 3, ',');
      buf     = stringtokenizer(s, 4, ',');
      if isempty(buf)
         fprintf(1, 'Recoverable time increment error on line %i.\n  The line, "%s", is not the expected format.\n  Manually edit %s and restart ncMicrocat.\n', n, s, filename)
         return
      end
      
      hms     = stringtokenizer(buf, 1);
      dateS{n}  = [mdy ' ' hms];
   
      if ~rem(n,1000)
         fprintf(1,'.')
      end
   else
      fprintf(1, 'Data Error on line %i.\n  The line, "%s" is not the expected format.\n', n+1, s);
      fprintf(1, '  Not enough data exists in this line to allow for data recovery.\n')
      fprintf(1, '  This line is being ignored. Line counter is decremented to account for this error.\n')
   end
   
end
fclose(fid);

fprintf(1,'completed\n')

fprintf(1,'Processing data.')
%time = jul2date(dayOfYear, year);
dateS = char(dateS(1:n));
sdn  = datenum(dateS);
utc  = sdn2utc(sdn);
temp = temp(1:n);
%save ncMicrocat_tmp utc temp C depth
sal  = salin_(C(1:n)./R, temp, depth);
sal(find(isnan(sal))) = -999;
outfile{'time'}(1:length(utc)) = utc;
%for i = 1:length(sdn)
%   outfile{'time'}(i) = utc(i);
%   if ~rem(i, 1000)
%      fprintf(1, '.');
%   end
%
%end

outfile{'temp'}(:) = temp;
outfile{'sal'}(:)  = sal;

fprintf(1,'...completed\n')

ncquit(outfile);

