% Read in data
iDir = uigetdir; % Select folder containing data xlsx files
iDir = [iDir,'\'];
inatEnto = readtable([iDir,'Supplemental_File_1.xlsx'],'Sheet',1);
outDir = iDir;

% Grab longitude, latitude and location labels
entoLat = inatEnto{:,'latitude'};
entoLong = inatEnto{:,'longitude'};
entoLab = inatEnto{:,'place_guess'};
entoSpec = inatEnto{:,'scientific_name'};
entoErr = inatEnto{:,'positional_accuracy'};
eTime = inatEnto{:,'observed_on'};
eTime = eTime(~isnat(eTime));

% Find empty and NaN cells, these samples will be excluded since they don't
% have geographic coordinates
emptyCells = cellfun(@isempty,entoLab);
nanCells = isnan(entoLat);
skip = emptyCells + nanCells;
keep = ~skip;

% Remove data without coordinates
entoLong = entoLong(keep);
entoLat = entoLat(keep);
entoLab = entoLab(keep);
entoSpec = entoSpec(keep);
entoErr = entoErr(keep);

% Use entoErr to scale entoMarker size
entoMark = repmat(5,1,length(entoErr));

% Grab unique species names for labeling
uniqSpec = unique(entoSpec);
approvedSpec = {'Entomophthora brevinucleata',...
                'Entomophthora byfordii',...
                'Entomophthora chromaphidis',...
                'Entomophthora culicis',...
                'Entomophthora ferdinandii',...
                'Entomophthora grandis',...
                'Entomophthora helvetica',...
                'Entomophthora israelensis',...
                'Entomophthora leyteensis',...
                'Entomophthora muscae',...
                'Entomophthora philippinensis',...
                'Entomophthora planchoniana',...
                'Entomophthora rivularis',...
                'Entomophthora scatophagae',...
                'Entomophthora schizophorae',...
                'Entomophthora simulii',...
                'Entomophthora syrphi',...
                'Entomophthora trinucleata',...
                'Entomophthora erupta',...
                'Entomophthora thripidum',...
                'Entomophthora weberi',...
                'Entomophthora'};

% Filter out un-recognized Entomophthora species (things that have wrong
% genus)
ct = 1;
includeSpec = cell(1);

cellfind = cellFind;   

for i=1:numel(uniqSpec)
    if ~isempty(find(cellfun(cellfind(uniqSpec{i}),approvedSpec))) || isempty(uniqSpec{i})
        includeSpec{ct} = uniqSpec{i};
        ct = ct+1;
    end
end
%%         
figure;
worldmap 'world'
hold on;

% Plot coastlines
landColor = [46/255 46/255 46/255];
load coast
h = geoshow(lat,long,'DisplayType','polygon','FaceColor',landColor);

% Determined proposed Ento range based on current sightings
proposedLat = lat;
proposedLong = long;
proposedLat(proposedLat>max(entoLat)) = max(entoLat);
proposedLat(proposedLat<min(entoLat)) = min(entoLat);
proposedLat(lat<-60) = nan; % anything below this latitude needs to be nan or you will have a line going through Pacific Ocean
proposedLat(isnan(lat)) = nan;
proposedLong(isnan(proposedLat)) = nan; % nan values between lat and long must match!

colors = [239 86 117;    %pink
          113,200,247;   %blue
          255 166 0;     %marigold
          239 220 32;    %yellow 
          142, 113, 247; % purple
          158, 242, 119; %green
          200, 200, 200]; 
colors = colors/255;                  

plotHandles = {};

espp = find(strcmp(includeSpec,'Entomophthora'));
emus = find(strcmp(includeSpec,'Entomophthora muscae'));
[eNums1,eNums2] = deal(1:length(includeSpec));
eNums1(espp) = [];
eNums2(emus) = [];
eNums = intersect(eNums1,eNums2);
markerShapes = {'o','d','s'};
colorNum = 1;
shapeNum = 1;
ct = 1;
legList = NaN(1,length([espp,emus,eNums]));

for i = [espp,emus,eNums]
    specInd = strcmp(entoSpec,includeSpec{i});
    plotHandles{ct} = scatterm(entoLat(specInd),entoLong(specInd),entoMark(specInd),colors(colorNum,:),markerShapes{shapeNum},'Visible','on','MarkerFaceColor',colors(colorNum,:));
    plotHandles{ct}.Children.MarkerFaceAlpha = 0.9;
    plotHandles{ct}.Children.MarkerEdgeAlpha = 1;
    plotHandles{ct}.DisplayName = includeSpec{i};
    
    colorNum = colorNum+1;
    if colorNum > length(colors)
        colorNum = 3;
        shapeNum = shapeNum+1;
    end
    
    legList(ct) = plotHandles{ct};
    
    ct = ct+1;
end

legend(legList,'Location','southoutside','NumColumns',3,'FontSize',12,'FontAngle','italic');           
legend boxoff;
    
set(gcf,'PaperUnits','inches','PaperPosition',[0 0 12 9]);
print(strcat(outDir,'Ento map.png'),'-dpng');
close();

%% Prepare data for seasonality plot (abundance of taxa observations over time)

% Grab month and day info from timestamps (iNaturalist data only)
eSplit = NaN(3,length(eTime));
eNew = cell(1,length(eTime));
for i=1:length(eTime)
    eSplit(1:3,i) = split(string(eTime(i)),'/');
    eSplit(3,i) = "2020";
    eNew{i} = strcat(num2str(eSplit(1,i)),'/',num2str(eSplit(2,i)),'/',num2str(eSplit(3,i)));
end

entoObs = datetime(eNew);
entoObs = sort(entoObs);

% Pull observation times for diptera, from iNaturalist (all, not just
% research grade, regardless of whether they have geo coordinates)
inatDip = readtable([iDir,'Supplemental_File_1.xlsx'],'Sheet',2);
dTime = inatDip{:,'observed_on'};
dTime = dTime(~isnat(dTime));  % remove any entries where no observation date is given

dipObs = horzcat(repmat(2020,length(dTime),1),month(dTime),day(dTime));  % convert all dates to 2020, to compare across months rather than by year
dipObs = datetime(dipObs);

%% Plot abundance of taxa observations over time
figure;
hold on;
yyaxis left;
ltgray = [92/255 92/255 92/255];
histogram(datenum(entoObs),52,'FaceColor',landColor,'FaceAlpha',1,'EdgeColor',ltgray,'Normalization','probability');
ylabel('Weekly observations');
set(gca,'YTick',[],'YColor','k');

dipColor = [0 0 1];

yyaxis right;
h1 = histfit(datenum(dipObs),52,'kernel');
h1(1).FaceAlpha = 0;
h1(1).EdgeColor = 'none';
h1(1).Visible = 'off';
h1(2).Color = dipColor;
h1(2).LineStyle = '--';
set(gca,'YTick',[],'YColor','none');

% % Set xticks to label each month
[xticksDate, xticksNum, xticklabels] = deal(cell(1,12));
for i=1:length(xticksDate)
    xticksDate{i} = datetime(strcat(num2str(i),'/1/2020'));
    xticksNum{i} = datenum(xticksDate{i});
    xticklabels(i) = month(datetime(xticksDate{i}),'short');
end
xticksNum = cell2mat(xticksNum);
set(gca,'xtick',xticksNum,'xticklabel',xticklabels);

xlim([min(xticksNum) max(xticksNum)]);

legend({'Entomophthora','','Diptera'});
legend box off;

set(gcf,'PaperUnits','inches','PaperPosition',[0 0 6.5 1.7]);
print(strcat(outDir,'Ento seasonality.png'),'-dpng');
close();

function x = cellFind 

    x = @(string)(@(cell_contents)(strcmp(string,cell_contents)));

end