function fixedFilePath = oncwavfilefix( sourceFilePath, doFastFix )
%---------------------------------------------------------------------
% oncwavfilefix
%
% Fast fix: updates the chunk size and data size in the wav head of the given sourceFilePath, returns the same file. This function just calls wavchunksizefix.m
%           with some extra error handling. If you like, you can use wavchunksizefix.m directly on your files. 
% Slow fix: reads in a wav file, updates some parameters, fixes some issues (chunk size or doubly zippeed),
%           writes out with proper wav file header to a new file.
% Taken from gethydrophoneDP.m, uses wavchunksizefix.m
%
% Syntax:   fixedFilePath = oncwavfilefix( sourceFilePath, doFastFix )
%
% Input:    sourceFilePath - char array / string
%           doFastFix - logical, controls what method is done
%
% Output:   fixedFilePath
%
% Date/Author:  20181116, Ben Biffard
% wavchunksizefix courtesy of MathWorks Support Team, see more information here:
% http://www.mathworks.com/matlabcentral/answers/92303-why-do-i-receive-an-error-about-incorrect-chunk-size-when-using-wavread-in-matlab
%---------------------------------------------------------------------

%% inputs
if nargin == 0
    sourceFilePath = 'C:\Users\bbiffard\Downloads\ICLISTENHF1333_20160930T235600.888Z.wav';
    disp(['Running test case sourceFilePath = ' sourceFilePath])
end
if nargin < 2
    doFastFix = true;
end
if nargin > 2
    error('ONC:oncwavfilefix:badInput', 'Bad inputs for oncwavfilefix, need 0, 1 or 2 inputs.');
end

fixedFilePath = '';

%% fixes
if doFastFix
    %% fast fix - I thought I had to do a bunch of editting to the header, but our existing wavchunksizefix does the trick
    disp(['Running fast wav file fix on ' sourceFilePath])
    try
        wavchunksizefix(sourceFilePath)
        fixedFilePath = sourceFilePath;
    catch err
        warning('ONC:oncwavfilefix:noFastFix', ['File ' sourceFilePath ' wasn''t fixed with fast methond, trying slow method...']);
        rethrow(err)
    end
else
    %% slow fix - read it and write it out
    disp(['Running slow wav file fix on ' sourceFilePath ', this involves reading in the wav file and writing it out with improved ONC metadata...'])
    try
        Hinfo = audioinfo(sourceFilePath);
        if Hinfo.TotalSamples <= 0
            warning('ONC:oncwavfilefix:noData', ['File ' sourceFilePath ' is empty. Skipping...']);
            return
        end
        [H.data, H.sampleFrequency] = audioread(sourceFilePath);
        H.numBits = Hinfo.BitsPerSample;
        clear Hinfo
    catch err
        if ~isempty(strfind(lower(err.message), 'chunk'))
            wavchunksizefix(sourceFilePath)
            Hinfo = audioinfo(sourceFilePath);
            [H.data, H.sampleFrequency] = audioread(sourceFilePath);
            H.numBits = Hinfo.BitsPerSample;
            clear Hinfo
            warning('ONC:oncwavfilefix:badWavChunkSize', ['File ' sourceFilePath ' had a bad chunk size, but we rescued it.']);
        elseif ~isempty(strfind(err.identifier, 'FileTypeNotSupported')) % attempt to rescue doubly zipped files!
            tryGZfile = [sourceFilePath '.gz'];
            copyfile(sourceFilePath, tryGZfile)
            sourceFilePath = gunzip(tryGZfile);
            sourceFilePath = sourceFilePath{1};
            try
                Hinfo = audioinfo(sourceFilePath);
                [H.data, H.sampleFrequency] = audioread(sourceFilePath);
                H.numBits = Hinfo.BitsPerSample;
                clear Hinfo
                delete(tryGZfile);
                warning('ONC:oncwavfilefix:doublyZippedFile', ['File ' sourceFilePath ' was doubly zipped but we rescued it.']);
            catch
                warning('ONC:oncwavfilefix:FileTypeNotSupported', ['File ' sourceFilePath ' is not supported by audioread, it''s probably corrupt, skipping it.']);
                return
            end
        else
            rethrow(err)
        end
    end
    
    [~, titleName, ~] = fileparts(sourceFilePath);
    fixedFilePath = [sourceFilePath(1:end-4) '-fixed' sourceFilePath(end-3:end)];
    audiowrite(fixedFilePath, H.data, H.sampleFrequency, 'BitsPerSample', H.numBits, 'Title', titleName, 'Artist', 'Ocean Networks Canada', 'Comment', 'WAV header chuck size and data size have been corrected');
    % HinfoFixed = audioinfo(fixedFilePath);
    % Hinfo
    % HinfoFixed
end