function mud = sedirpt(name)
% SEDIRPT Read Micromeritics SediGraph .RPT report files
% input: filename (string)
% output: structure with data from the .RPT "Report by Size" table
%
% D. Nowacki nowacki@uw.edu 15 July 2014 
data = rptbysizeload([name '.rpt']);

data = cell2mat(data);

avgdia = data(:,3);
massfreq = data(:,5);
phi = -1*log2(avgdia*.001);

% Set all negative mass frequencies to zero
massfreq(massfreq < 0) = 0;

totalmass = sum(massfreq);

% account for percents not summing to 100%
multifactor = 100 / totalmass;

massfreq_corrected = massfreq * multifactor;

mud.avgdia = avgdia;
mud.phi = phi;
mud.massfreq = massfreq_corrected;
mud.massfreq_orig = data(:,5);
mud.percentfiner = data(:,4);
mud.std = data(:,6);

end

function data = rptbysizeload(name)
% Function to load the Report by Size data from the SediGraph .RPT outpu

fid = fopen(name);

tmp = fgetl(fid);
while ischar(tmp)
    if strcmp(tmp, '------') % this line indicates the start of the Report by Size Table
        break;
    end
    tmp = fgetl(fid);
end

% The Report by Size Table is formatted like so:
%                                       Cumulative                 Cum Mass   
%     High         Low       Average       Mass          Mass      Standard   
%   Diameter    Diameter    Diameter      Finer       Frequency    Deviation  
%     (µm)        (µm)        (µm)      (Percent)     (Percent)    (2 tests)  
%
% This will keep reading the table data until it reaches a blank line
data = textscan(fid, '%f %f %f %f %f %f');

fclose(fid);

end