function figurePosition = visualFigPlacement(figIndex, numFigures)%
%VISUALFIGPLACEMENT Controls placement of Characterisitic Power Plots on
% customer screen
%

% Copyright 2020 The MathWorks, Inc.

gRoot = groot;
% Calculations are performed in pixels
gUnitsOriginal = gRoot.Units;
gRoot.Units = 'pixels';
figPosition = get(0,'defaultFigurePosition');
aspectRatio = figPosition(4)/figPosition(3);

monitorPos = min(get(0,'MonitorPositions'),[],1);
figOffset = round((monitorPos(1,3)-monitorPos(1,1))*20/1560);

% Insure figures fit within monitor screen
[minRatio, min_idx] = min(                                              ...
    (monitorPos(3:4)-(numFigures+1)*figOffset)/2.1  ./  figPosition(3:4));
if minRatio<1
    if min_idx==1
        figPosition(3) = monitorPos(3)/2.1;
        figPosition(4) = figPosition(3)*aspectRatio;
    else
        figPosition(4) = monitorPos(4)/2.1;
        figPosition(3) = figPosition(4)/aspectRatio;
    end
end

figUpperRight = figPosition(1:2)+figPosition(3:4)           +           ...
    figOffset*[(numFigures+1) 0];
% Test figure right x-position
if figUpperRight(1)>monitorPos(1,3)
    % Adjust figure bottom left x-position
    figPosition(1) = monitorPos(1,3)-figPosition(3)         -           ...
        figOffset*(numFigures+1);
elseif figPosition(1)<figOffset
    figPosition(1) = figOffset;
end
% Test figure right y-position
if figUpperRight(2)>monitorPos(1,4)
    % Adjust figure bottom left y-position
    figPosition(2) = monitorPos(1,4)-figPosition(4);
elseif figPosition(2)<(numFigures+2)*figOffset
    figPosition(2) = (numFigures+2)*figOffset;
end

figurePosition = [figPosition(1)+figIndex*figOffset,                    ...
    figPosition(2)-figIndex*figOffset, figPosition(3), figPosition(4)];

% Reset global figure units
gRoot.Units = gUnitsOriginal;