%% Step 1
%import the CNN model
if ~exist('','dir')           %Upon download folder will be zipped
    unzip('');                %UnZip by pasting the zip file path into both brackets
end

cnn_modelFolder = '';         %Load Model - Insert Model FilePath (this will be the unzip file path)

%specify the class names
classNames = {'Ambient','Clicks','Whistle','Vessel'}                            %Note: 0=Ambient, 1=Delphinid Tonal, 2=Biological Clicks, 3=VesselNoise

%Load Model Architecture / Weights / Training Config. note: You need matlab
%version R2022a or b to load the model in this format - may need to use the
%h5 file if using older version of matlab.
net = importTensorFlowNetwork(cnn_modelFolder,'OutputLayerType','classification','Classes',classNames)

%check the input size ([should be 224 224 3])
net.Layers(1).InputSize   

%% 
%RGB_function input parameters -set up spectrogram to tailored specs
comp_FFTSizes = [1024 2048 4096];                                                                                            %Must change depending on the dataset being used (Calculate correction factor 96000/Fs --> ceil(1024/correction factor) and repeat per channel
FS = 96000;                                                                                                                   % change per dataset in use
fMax = 48000;                                                                                                                  % Nyquist frequency
Levels = [-100 20];                                                                                                             % DB levels for spectrogram analysis
FFTSizes = comp_FFTSizes;                                                                                                    % change as necessary from correction factors
Labels = [];                                                                
Scores = [];
FileNames = [];
ImSize = [224 224];   

chunkCnt = 1;  


%%
%Step 3 Load each wav file in 3 second chunks and pass each chunk to the spectrogram processer and CNN classifier will store results per hour in results file, labelled in order of folder. 

% USER EDIT Load in Directory containing folders of daily audio recordings
theFiles = dir('/Volumes/CpodCompass/CPOD_PAM_COMPARISON_FILES/Tolsta/January/*.wav'); %Parent directory add in '**/' between january/ and /*.wav if you want to loop through all folders
Sorted_Files = natsortfiles(theFiles);                      %Ensures results are in order of file
numFiles = length(theFiles);
% if not(isfolder('/Volumes/OneTouch/Cornell_Data/Oregon/Results_Output'))
%    mkdir /Volumes/OneTouch/Cornell_Data/Oregon/Results_Output
% end

results_folder = '';  %Change results folder to desired folder 

% Start Chunk counter 

delete(gcp('nocreate')); %Uses parallel computing toolbox in Matlab, ensure installed.
parpool('local',6);

tic

%Need to comment out Aigun elements - lines 88-94 if not using airgun detector
parfor k = 1:numFiles
    baseFileName = Sorted_Files(k).name;
    thisFolder = Sorted_Files(k).folder;
    fullFileName = fullfile(thisFolder, baseFileName);
    if strfind(baseFileName, '._') %ignore all ._DS_Store files in folder
        continue
    end
    fprintf('Classifying %s...\n', baseFileName);
    info = audioinfo(fullFileName);    %returns information about the contents of the audio file
    Fs = info.SampleRate;
    chunkDuration = 3;                                                            % 3 second chunks to be fed into spectrogram processing code
    numSamplesPerChunk = chunkDuration*Fs;
    Labels = [];                                                                
    Scores = [];
    %AirLabel = [];
    %AirScores = [];
    FileNames = [];
    chunkCnt = 0;

    for startLoc = 1:numSamplesPerChunk:info.TotalSamples
        endLoc = min(startLoc + numSamplesPerChunk - 1, info.TotalSamples);
        y = audioread(fullFileName, [startLoc endLoc]);                              %read wav file
        ImOut = RGB_spectrogram(y,FFTSizes,ImSize,FS,fMax,Levels);         %Ensure RGB spectrogram code is in correct folder
        [label, scores] = classify(net, ImOut);
        Labels = [Labels; label];                                               %Concatenate label array
        Scores = [Scores; scores];
        %AirLabel = [AirLabel; air_label];
        %AirScores = [AirScores; air_scores];
        outFileName = sprintf('file_%d', chunkCnt);                                %Create FileName per chunk
        outFileName = convertCharsToStrings(outFileName);                          %Avoid concatenation error
        FileNames = [FileNames; outFileName];
        chunkCnt = chunkCnt + 3;
    end    %Concatenate name array

    FileNames(:,end) = [];
    T = table(FileNames, Labels, Scores(:,1),Scores(:,2),Scores(:,3),Scores(:,4),'VariableNames', {'Frame','Label','Ambient_Noise','Clicks','Whistle','Vessel_Noise'});
    results_name = sprintf('results_%s.csv', baseFileName(1:end-5))
    writetable(T,fullfile(results_folder, results_name)); %Change Results FileName per Run!
    chunkCnt = 0;

end   

elapsed = toc

elapsed = elapsed / 3600;
fprintf('Time Elapsed %s...\n', elapsed)

