function log2nc(logname, ncname)
% LOG2NC - Convert an AUV log data file to netcdf.
%
% Use as: log2nc(logname, ncname)
%
% Inputs: logname = The log to be converted to netcdf
% Output: ncname = The name of the netcdf file to be created.

% Brian Schlining
% $Id: log2nc.m,v 1.2 2003/08/08 17:07:39 brian Exp $

nc = netcdf(ncname, 'clobber');
if isempty(nc)
    error(['Failed to create ' ncname '. Check that you have write permission.']);
end

% Open the log file, get the device name from the header
fid = fopen(logname, 'r', 'l');
s = fgetl(fid); 
instrumentName = stringtokenizer(s, 3);

% Generate the standard global attributes using null values
nc.title = ncchar('AUV data');
nc.created = ncchar(datestr(now, 31));
nc.source = ncchar(logname);
nc.history0 = ncchar([datestr(now, 31) ': Netcdf file generated in matlab using log2nc']);
nc.deploymentName = ncchar('null');
nc.instrumentId = ncchar('null');
nc.instrumentName = ncchar(instrumentName);
nc.instrumentType = ncchar('null');
nc.instrumentMfg = ncchar('null');
nc.instrumentSerialNumber = ncchar('null');
nc.instrumentModel = ncchar('null');

% AUV files alwasy have a single dimension of time
nc('time') = 0;

% Generate the netcdf schema
i = 0;
while(~feof(fid))
    s = fgetl(fid);  
    i = i + 1;
    if (strcmp(stringtokenizer(s, 2), 'begin'))
        break    
    end
    
    % Parse the variable info
    data(i).type = stringtokenizer(s, 2);
    data(i).shortName = stringtokenizer(s, 3);
    data(i).format = stringtokenizer(s, 4);
    data(i).longName = stringtokenizer(s, 2, ',');
    switch data(i).shortName
        case 'time'
            data(i).units = 'seconds since 1970-01-01 00:00:00Z';
        otherwise         
            data(i).units = stringtokenizer(s, 3, ',');
    end
    
    % Map the dataformats correctly   
    switch lower(data(i).type)
        case {'float'}
            data(i).type = 'float32'; 
            nc{data(i).shortName} = ncfloat('time');
        case {'integer'}
            data(i).type = 'int32';
            nc{data(i).shortName} = ncint('time');
        case {'short'}
            data(i).type = 'int16';
            nc{data(i).shortName} = ncshort('time');
        otherwise
            data(i).type = 'double'; 
            nc{data(i).shortName} = ncdouble('time');
    end
    
    % Create variable attributes
    nc{data(i).shortName}.long_name = ncchar(data(i).longName);
    nc{data(i).shortName}.units = ncchar(data(i).units);
    
end

% Read the data from the log. This is SLOW!!
% Need to preallocate memory first
j = 0;
while (~feof(fid))
    j = j + 1;
    try 
        for i=1:length(data)
            data(i).data(j) = fread(fid, 1, data(i).type);
        end 
    catch
        break    
    end
end
fclose(fid);

% Write the data to the netcdf
% Have to assign values to time a special way
nc{'time'}(1:length(data(1).data)) = data(1).data;

% All other values 
for i=2:length(data)
    nc{data(i).shortName}(:) = data(i).data;
end

close(nc);


