

%% -----------------% 
%  Size Adjustments %
%-------------------% 

% close all
% clc

% Figure size
fig.xPos     = 100;
fig.yPos     = 10;
fig.width    = 1655;
fig.height   = 1007;
fig.Position = [fig.xPos fig.yPos fig.width fig.height];

% Axes size
gh  = 0.6;                  % great axis height
sh  = gh/3;                  % small axis height
ar  = fig.height/fig.width;  % aspect ratio (to get square axes)
gw  = gh*ar;                 % great axis width
sw  = sh*ar;                 % small axis width
ch  = 0.025;                 % center height
cw  = ch*ar;                 % center width
bh  = 0.115;                 % bottom margin height
lw  = bh*ar;                 % left margin
th  = 1-bh-sh-ch-gh;         % top margin (not used, just as diagnostic)
rw  = 1-lw-sw-2*cw-2*gw;     % right margin (not used, just as diagnostic)
wr  = 1.0;                   % wind rose scale factor
cbh = 0.02;                  % color bar height

% Position of main axes 
ax.Pos1  = [lw                           	bh + sh + ch            gw         	gh];    % top left
ax.Pos2  = [lw +   gw +   cw                bh + sh + ch            sw         	gh];    % top center
ax.Pos3  = [lw +   gw + 2*cw +   sw         bh + sh + ch            gw        	gh];    % top right
ax.Pos4  = [lw                            	bh                	    gw      	sh];    % bottom left
ax.Pos6  = [lw +   gw + 2*cw +   sw         bh                	    gw      	sh];    % bottom right

% Position of wind roses
ax.Pos1b = [lw               + 2*sw         bh + gh + ch         wr*sw       wr*sh];    % top left (corner)
ax.Pos3b = [lw + 2*gw + 2*cw                bh + gh + ch         wr*sw       wr*sh];    % top right (corner)
% Position of color bars
ax.Pos5  = [lw +   gw +   cw                bh + sh - cbh       sw         cbh];    % bottom center


% Axes limits
xLim  = xLimits{iVar};          % limits of x axiss
yLim  = yLimits{iVar};          % limits of main y axis
y2Lim = y2Limits{iVar};         % limits of secondary x axis
y4Lim = y4Limits{iVar};         % limits of secondary y axis
y6Lim = y4Lim;                  % limits of secondary y axis
x1    = xLim(1);                % x axis minimum
x2    = xLim(2);                % x axis maximum
y1    = yLim(1);                % y axis minimum
y2    = yLim(2);                % y axis maximum


% 2dHist settings
nx  = numBinX(iVar);             % number of bins in x direction (2d)  
ny  = numBinY(iVar);             % number of bins in y direction (2d)  
nx1 =  nx;                       % number of bins in x direction (1d)
ny1 =  ny;                       % number of bins in y direction (1d)
dx  = x2-x1;                     % axis width
dy  = y2-y1;                     % axis height
xw  = dx/nx;                     % bin width (2d)
yw  = dy/ny;                     % bin height (2d)
xw1 = dx/nx1;                    % bin width (1d)
yw1 = dy/ny1;                    % bin height (1d)
xc  = (x1+xw/2):xw:(x2-xw/2);    % center of x ticks
yc  = (y1+yw/2):yw:(y2-yw/2);    % center of x ticks

% Tick settings
nP      = 3;                        % tick number of percentage axis
xt      = xtLen(iVar);             	% xtick length
yt      = ytLen(iVar);            	% ytick length
yt2     = y2Lim(2)/nP;           	% secondary ytick length
yt4     = y4Lim(2)/nP;           	% secondary ytick length
yt6     = yt4;                   	% secondary ytick length
xTicks  = x1 :xt :x2;               % xticks
yTicks  = y1 :yt :y2;               % yticks
yTicks2 = y2Lim(1):yt2:y2Lim(2);  	% secondary yticks
yTicks4 = y4Lim(1):yt4:y4Lim(2);  	% secondary yticks
yTicks6 = y6Lim(1):yt6:y6Lim(2);  	% secondary yticks


% Font size
fontSize = 38;

% Define colors
redFaceCol  = [0.863 0.608 0.482];
blueFaceCol = [171/255 203/255 245/255];


% Create figure
Fig1 = figure('Color','White','units','points','Position',fig.Position,...
         'PaperPositionMode','auto','PaperOrientation','landscape');
     

%% -----------------% 
%     Subplot 1     %
%-------------------% 
ax1 = subplot('Position',ax.Pos1);

% Create histogram
[hist1, histS] = hist2dplot(xS,yS,x1,y1,nx,ny,dx/nx,dy/ny,contSwi);
%histS = ndhist(xS,yS);

histVecS = histS(:);
if(whiteDots)
    nMax   = perc/100*length(histVecS);
    yIdx   = nan(nMax,1);
    xIdx   = yIdx;
    maxVal = yIdx;
    maxIdx = yIdx;
    for i = 1:nMax
        [maxVal(i),maxIdx(i)]    = max(histVecS);
        [yIdx(i), xIdx(i)] = ind2sub(size(histS),maxIdx(i));
        histVecS(maxIdx(i)) = NaN;
    end
    x = xc(xIdx);
    y = yc(yIdx);
    fit1 = fit(x',y','a*x+b','StartPoint',[1 0]);
    
end

hold on; box on; grid on

ax1.FontSize    = fontSize-2;
ax1.FontName    = 'Verdana';
ax1.Layer    = 'top';
ax1.XTickLabel  = '';
ax1.XTick       = xTicks;
ax1.YTick       = yTicks;
ytLab           = ax1.YTickLabel;
ytLab(skipYTick(iVar):2:end)  = {''};



epsw =  0.01;           % minor position correction in x direction
epsh = -0.04;           % minor position correction in y direction

if(sameColBar)
    if(isequal(colMap1,colMap2))
        caxis([0 0.27]);
    else
        colBar1              = colorbar('North');
        colBar1.Position     = ax.Pos5;
        %colBar1.Position(2)  = ax.Pos5(2) + ax.Pos5(4) + 0.01;
        histMax              = 0.45;
        colBar1.Limits       = [0 histMax];
        colBar1.Ticks        = 0:histMax/n:histMax;
        switch colMapCol
            case 'rbCo'
                hist1.LevelList      = colBar1.Ticks;
        end
        colBar1.TickLabels   = '';
        caxis([0 histMax]);
    end
    
else
    idx = idx + 1;
    maxList(idx) = max(max(histS));
    colBar1              = colorbar('North');
    colBar1.FontSize     = fontSize-6;
    colBar1.FontName     = 'Verdana';
    colBar1.Position     = ax.Pos5;
    histMax              = histMaxS(iVar);
    colBar1.Limits       = [0 histMax];
    colBar1.Ticks        = 0:histMax/n:histMax;
    cBtickLab            = arrayfun(@num2str,colBar1.Ticks *100,'un',0);
    cBtickLab(2:2:end)   = {''};
    cBtickLab(end-1)     = {['>' cBtickLab{end-1}]};
    colBar1.TickLabels   = cBtickLab;
    caxis([0 histMax]);
end
colormap(ax1, colMap1)
colBar1.FontSize     = fontSize-18;
colBar1.FontName     = 'Verdana';

hold on

if(whiteDots)
    sc1   = scatter(xc(xIdx),yc(yIdx),'.');
    sc1.MarkerFaceColor = 'none';
    sc1.MarkerEdgeColor = 'w';
    sc1.MarkerEdgeAlpha = 1;

    ax1.XLim  = xLim;
    ax1.YLim  = yLim;
    ax1.Color = 'none';
    ax1.XTickLabel = '';
    ax1.YTickLabel = '';

    hold on
end

% generate zero line
if y1 < 0 && y2 > 0  
    line1b = plot(xLim,[0 0]);
    line1b.Color     = 'k';
    line1b.Color(4)  = 0.1;
    line1b.LineStyle = '-';
    line1b.LineWidth = 3;
    legend('off')
end

if(whiteDots)
    line1  = plot(fit1);
    line1.Color = 'k';
    line1.LineWidth = 1.5;
    line1.LineStyle = '--';
    legend('off');xlabel('');ylabel('');
end


if(obsRegression)
    line1c  = line([x1 x2],[obsReg(x1) obsReg(x2)]);
    line1c.Color = pale(newColor(9),0.2);
    line1c.LineWidth = 2;
    legend('off');xlabel('');ylabel('');
end

fit1a = fit(WspdS,dataS,'a*x+b','StartPoint',[1 0]);
disp(['Teq = '  num2str(-fit1a.b/fit1a.a) '°C'])
line1a  = plot(fit1a);
line1a.Color = 'k';
line1a.LineWidth = 1.5;
line1a.LineStyle = '--';
legend('off');xlabel('');ylabel('');



if(funcLegend)
    leg1 = legend([line1a]);
    leg1.FontSize  = fontSize-6;
    leg1.FontName  = 'Verdana';
    leg1.Color     = 'white';
    leg1.EdgeColor = 'white';
    leg1.String{1} = functionLabel(fit1a.a,fit1a.b);
    leg1.Location  = 'NorthWest';
end

yLab1 = ylabel(yLabels{iVar});
yLab1.FontSize = fontSize-2;
ax1.YTickLabels = ytLab;

xtext = 31;
ytext = 6.8;
text1 = text(xtext,ytext,'(a)');
text1.FontName = 'Verdana';
text1.FontSize = fontSize-6;



%__________________________
%       Subplot 2
%__________________________


ax2 = subplot('Position',ax.Pos2);
hold on; box on; grid on
view(90,-90)

% Axis settings
ax2.FontSize      = fontSize-2;
ax2.FontName      = 'Verdana';
ax2.XLim          = yLim;
ax2.YLim          = y2Lim;
ax2.YTick         = yTicks2;
ax2.XTick         = yTicks;
ax2.XTickLabel    ='';
ax2.YAxisLocation = 'right';

%%% Line 1 %%%

% Compute histogram
MaxyC      =  (y1+yw1/2) : yw1 : max(X2);
histCounts = hist(X2, MaxyC);
% Normalize (percent) histogram counts
normCounts = histCounts / sum(histCounts) * 100;

% Plot histogram (bar plot)
bar2a = bar(MaxyC, normCounts, 'BarWidth',1);

% Choose color and alpha
bar2a(1).FaceColor = blueFaceCol;
bar2a.EdgeColor    = 'k';


% Compute Propability Density Function (PDF) 
[xSort,idxSort] = sort(X2);     % sort x values
ySort           = Y2(idxSort);  % sort pdf(x) values

pVal = yw1 * 100;    % density was computed per bin width, convert in percent


if(~ismember(iVar,4))
    % Plot PDF
    line2a  = plot(xSort, ySort * pVal);   
    % Plot settings 
    line2a.Color     = pale(newColor(1),-0.1);
    line2a.LineWidth = 2;
end


%%% Line 2 %%%

% Compute histogram
MaxyC      =  (y1+yw1/2) : yw1 : max(X1);
histCounts = hist(X1, MaxyC);
% Normalize (percent) histogram counts
normCounts = histCounts / sum(histCounts) * 100;

% Plot histogram (bar plot)
bar2b = bar(MaxyC, normCounts, 'BarWidth',1);

% Choose color and alpha
bar2b(1).FaceColor = redFaceCol;
bar2b.EdgeColor    = 'k';
alpha(bar2b,0.6);

% Compute Propability Density Function (PDF) 
[xSort,idxSort] = sort(X1);     % sort x values
ySort           = Y1(idxSort);  % sort pdf(x) values

pVal = yw1 * 100;    % density was computed per bin width, convert in percent

if(~ismember(iVar,4))
    % Plot PDF
    line2b  = plot(xSort, ySort * pVal);   
    % Plot settings 
    line2b.Color     = newColor(7);
    line2b.LineWidth = 2;
end

% Add percent sign
yTickLab      = ax2.YTickLabel;
for i=1:size(yTickLab,1)
   percentLab{i}=[yTickLab{i} '%'];
end
percentLab(2:2:end) = {''};
ax2.YTickLabel = percentLab;


% Draw grid on top of bars
clearvars axes
ax2b            = axes;
ax2b.Position   = ax.Pos2;
ax2b.Layer      = 'top';
view(90,-90)
ax2b.XLim       = ax2.XLim;
ax2b.YLim       = ax2.YLim;
ax2b.Color      = 'none';
ax2b.YTick      = yTicks2;
ax2b.XTick      = yTicks;
ax2b.XTickLabel = '';
ax2b.YTickLabel = '';
grid on

% Legend
leg2           = legend(ax2b,[bar2b bar2a],legStr);
leg2.Color     = 'white';
leg2.EdgeColor = 'white';
leg2.Location  = 'NorthEast';
leg2.FontSize  = fontSize-13;
leg2.FontName  = 'Verdana';





%__________________________
%       Subplot 3
%__________________________

% Create axes of subplot
ax3   = subplot('Position',ax.Pos3);

% Plot 2d histogram
[hist3, histW] = hist2dplot(xW,yW,x1,y1,nx,ny,dx/nx,dy/ny,contSwi);


histVecW = histW(:);

hold on; box on; grid on
ax3.FontSize = fontSize-2;
ax3.FontName = 'Verdana';
ax3.Layer    = 'top';

ax3.XTickLabel = '';
ax3.YTickLabel = '';
ax3.XTick      = xTicks;
ax3.YTick      = yTicks;

colBar3 = colorbar('North');

if(sameColBar)
    ax.Pos5(2)           = bh + 3/4*sh - cbh;
    colBar3.Position     = ax.Pos5;
    histMax              = 0.45;
    colBar3.Limits       = [0 histMax];
    colBar3.Ticks        = 0:histMax/n:histMax;
    switch colMapCol
        case 'rbCo'
            hist3.LevelList      = colBar3.Ticks;
    end
    cBtickLab            = arrayfun(@num2str,colBar1.Ticks *100,'un',0);
    cBtickLab(2:2:end)   = {''};
    cBtickLab(end-1)     = {'>0.4'};
    colBar3.TickLabels   = cBtickLab;
    caxis([0 histMax]);
else
    idx = idx + 1;
    maxList(idx) = max(max(histW));
    ax.Pos5(2)           = bh + 2/3*sh - cbh;
    colBar3.Position     = ax.Pos5;
    histMax              = histMaxW(iVar);
    colBar3.Limits       = [0 histMax];
    colBar3.Ticks        = 0:histMax/n:histMax;
    cBtickLab            = arrayfun(@num2str,colBar3.Ticks *100,'un',0);
    cBtickLab(2:2:end)   = {''};
    cBtickLab(end-1)     = {['>' cBtickLab{end-1}]};
    colBar3.TickLabels   = cBtickLab;
    caxis([0 histMax]);
end
colBar3.FontSize     = fontSize-18;
colBar3.FontName     = 'Verdana';
colBar3.Label.String = {'Normalized Freq.'; '[% per K^{2}]'};
colBar3.Label.FontSize = fontSize-10;

colormap(ax3, colMap2)


ax3.XLim  = xLim;
ax3.YLim  = yLim;
ax3.Color = 'none';
ax3.XTickLabel = '';
ax3.YTickLabel = '';

hold on

% generate zero line
if y1 < 0 && y2 > 0  
    line3b = plot(xLim,[0 0]);
    line3b.Color     = 'k';
    line3b.Color(4)  = 0.1;
    line3b.LineStyle = '-';
    line3b.LineWidth = 3;
    legend('off')
end


if(obsRegression)
    line3c  = line([x1 x2],[obsReg(x1) obsReg(x2)]);
    line3c.Color = pale(newColor(9),0.2);
    line3c.LineWidth = 2;
    legend('off');xlabel('');ylabel('');   
end


fit3a = fit(WspdW,dataW,'a*x+b','StartPoint',[1 0]);
disp(['Teq = '  num2str(-fit3a.b/fit3a.a) '°C'])
line3a  = plot(fit3a);
line3a.Color = 'k';
line3a.LineWidth = 1.5;
line3a.LineStyle = '--';
legend('off');xlabel('');ylabel('');

if(funcLegend)
    leg3 = legend([line3a]);
    leg3.FontSize  = fontSize-6;
    leg3.FontName  = 'Verdana';
    leg3.Color     = 'white';
    leg3.EdgeColor = 'white';
    leg3.String{1} = functionLabel(fit3a.a,fit3a.b);
    leg3.Location  = 'NorthWest';
end

text3 = text(xtext,ytext,'(b)');
text3.FontName = 'Verdana';
text3.FontSize = fontSize-6;

%__________________________
%       Subplot 4
%__________________________

% Create axes of subplot
ax4 = subplot('Position',ax.Pos4);
hold on; box on; grid on

% Axis settings
ax4.FontSize    = fontSize-2;
ax4.FontName    = 'Verdana';
ax4.XLim        = xLim;
ax4.YLim        = y4Lim;
ax4.YTick       = yTicks4;
ax4.XTick      = xTicks;
xtLab           = ax4.XTickLabel;
xtLab(skipXTick(iVar):2:end)  = {''};
ax4.XTickLabels = xtLab;

% Label of x axis
xLab4 = xlabel(xLabels{iVar});
xLab4.FontSize = fontSize-2;

% Compute histogram 
MaxxC      = (x1+xw1/2) : xw1 : max(X3);
histCounts = hist(X3, MaxxC);
% Normalize (percent) histogram counts
normCounts = histCounts / sum(histCounts) * 100;

% Plot histogram (bar plot)
bar4 = bar(MaxxC, normCounts, 'BarWidth',1);

% Choose color and alpha
bar4(1).FaceColor = redFaceCol;
bar4.EdgeColor    = 'k';
alpha(bar4,0.6);

% Compute Propability Density Function (PDF) 
[xSort,idxSort] = sort(X3);     % sort x values
ySort           = Y3(idxSort);  % sort pdf(x) values

pVal = xw1 * 100;    % density was computed per bin width, convert in percent

if(~ismember(iVar,[2 3]))
    % Plot PDF
    line4  = plot(xSort, ySort * pVal);   
    % Plot settings 
    line4.Color     = newColor(7);
    line4.LineWidth = 2;
end

% Add percent sign
yTickLab      = ax4.YTickLabel;
for i=1:size(yTickLab,1)
   percentLab{i}=[yTickLab{i} '%'];
end
percentLab(2:2:end) = {''};
ax4.YTickLabel = percentLab;

% Draw grid on top of bars
clearvars axes
ax4b            = axes('Position', ax.Pos4, 'Layer','top');
ax4b.XLim       = ax4.XLim;
ax4b.YLim       = ax4.YLim;
ax4b.XTickLabel = '';
ax4b.YTickLabel = '';
ax4b.Color      = 'none';
ax4b.YTick      = yTicks4;
grid on

%__________________________
%       Subplot 6
%__________________________


% Create axes of subplot
ax6 = subplot('Position',ax.Pos6);
hold on; box on; grid on

% Axis settings
ax6.FontSize    = fontSize-2;
ax6.FontName    = 'Verdana';
ax6.XLim        = xLim;
ax6.YLim        = y6Lim;
ax6.YTick       = yTicks6;
ax6.XTick       = xTicks;
ax6.XTickLabels = xtLab;

% Label of x axis
xLab6 = xlabel(xLabels{iVar});
xLab6.FontSize = fontSize-2;

% Compute histogram 
MaxxC      = (x1+xw1/2) : xw1 : max(X4);
histCounts = hist(X4, MaxxC);
% Normalize (percent) histogram counts
normCounts = histCounts / sum(histCounts) * 100;

% Plot histogram (bar plot)
bar6 = bar(MaxxC, normCounts, 'BarWidth',1);

% Choose color and alpha
bar6(1).FaceColor = blueFaceCol;
bar6.EdgeColor    = 'k';

% Compute Propability Density Function (PDF) 
[xSort,idxSort] = sort(X4);     % sort x values
ySort           = Y4(idxSort);  % sort pdf(x) values

pVal = xw1 * 100;    % density was computed per bin width, convert in percent

if(~ismember(iVar,[2 3]))
    % Plot PDF
    line6  = plot(xSort, ySort * pVal);   
    % Plot settings 
    line6.Color     = pale(newColor(1),-0.1);
    line6.LineWidth = 2;
end

ax6.YTickLabel = '';

% Draw grid on top of bars
clearvars axes
ax6b            = axes('Position', ax.Pos6, 'Layer','top');
ax6b.XLim       = ax6.XLim;
ax6b.YLim       = ax6.YLim;
ax6b.XTickLabel = '';
ax6b.YTickLabel = '';
ax6b.Color      = 'none';
ax6b.YTick      = yTicks6;
grid on

% Export file to pdf or png
if(sameColBar)
    printStr = 'sameScale';
else
    printStr = 'diffScale';
end

if(printSwitch)
    drucken(['./Plots/' expStr{iVar}  '.' colStr '.' printStr '.png']);
end

function funcStr = functionLabel(aParam,bParam,numDig)
    if nargin > 2
        strOpt = ['%1.' num2str(numDig) 'f'];
    else
        strOpt = '%1.2f';
    end

    if aParam > 0
        aStr = ['  ' num2str(abs(aParam),strOpt)];
    else
        aStr = [char(8211) num2str(abs(aParam),strOpt)];
    end

    if bParam > 0
        bStr = ['+ ' num2str(abs(bParam),strOpt)];
    else
        bStr = [char(8211) ' ' num2str(abs(bParam),strOpt)];
    end

    funcStr = ['f(x) = ' aStr 'x ' bStr];
end

function y = obsReg(x)

    y = -0.27.*x+7.83;
end
