function [ww] = readncTHOON(file,k2,Pcoefs,savefile)
% Read information for netCDF files from the THOON WireWalker. Format as
% struct with properties that allow for easy recalc of k0 and pH through
% CanyonB

% Set default values if only 'file' is provided
if nargin < 2
    k2 = nan;
end
if nargin < 3
    Pcoefs = [];
end
if nargin < 4
    savefile = 0;
end

info = ncinfo(file);

% Initialize the struct to store the data
ww = struct;

% Function to sanitize field names
ModifiedFieldName = @(name) regexprep(name, '[^a-zA-Z0-9]', '_');

% Loop through each variable and read its data
for i = 1:length(info.Variables)
    varname = info.Variables(i).Name;
    ModifiedVarName = ModifiedFieldName(varname);
    ww.(ModifiedVarName) = ncread(file, varname);
    ww.(ModifiedVarName) = ww.(ModifiedVarName)';
end

% Parse the string containing the reference time as datetimePart
fn = fieldnames(ww);
idx = contains(fn,'Time');

datetimeStr = info.Variables(idx).Attributes.Value;
if length(datetimeStr) < 30
    datetimeStr = info.Variables(idx).Attributes(5).Value; % Quick fix. 
    % Need method for finding the 'units' attribute.
end


parts = strsplit(datetimeStr, ' since '); % split at 'since '
datetimePart = parts{2};

% Convert the datetime string to a datetime object
try
    refdatetime = datetime(datetimePart, 'InputFormat', 'yyyy-MM-dd HH:mm:ss.SSSSSS');
catch
    try
        refdatetime = datetime(datetimePart, 'InputFormat', 'yyyy-MM-dd HH:mm:ss');
    catch
        disp('uh oh wrong datetime format')
    end
end
timeInSeconds = seconds(double(ww.Time) / 1000);

% Datetime
ww.Datetime = refdatetime + timeInSeconds;
ww.Datetime.TimeZone = 'UTC';

% Datenum
ww.Datenum = datenum(ww.Datetime);

% Lat/Lon coordinates
try
    names = {info.Attributes(:).Name}.';
    lat_idx = contains(names,'mooring_lat');
    lon_idx = contains(names,'mooring_lon');
    lat = info.Attributes(lat_idx).Value;
    lon = info.Attributes(lon_idx).Value;
catch % THOON station 2 lat/lon
    lat = 41.055362; 
    lon = -124.268412;
    disp('No lat/lon found in nc file. Using default lat/lon for station 2')
end

ww.Latitude = ones(size(ww.Datetime))*lat;
ww.Longitude = ones(size(ww.Datetime))*lon;

% Depth
try
    ww.Depth = ww.Depth';
catch
    ww.Depth = [];
end

% Density
try
    ww.rho = density(ww.Practical_Salinity, ww.Temperature) - 1000; % kg/m^3
catch
    try
        ww.rho = density(ww.Absolute_Salinity, ww.Conservative_Temperature) - 1000; % kg/m^3
        disp('rho calculated with absolute salinity and conservative temperature')
    catch
        disp('not enough inputs to calculate rho')
    end
end
% Lab calculated k2 for specific sensor
ww.k2 = k2;

% Lab calculated Pcoefs for specific sensor
ww.Pcoefs = Pcoefs;

filename = char(file);
filename = filename(1:end-3);
% Save the struct as a .mat file
if savefile==1
    save([filename,'.mat'], 'ww');
end
end