function [GI_AngoloKL,GI_NumKL,GI_DateKL,ATTIVA,FIG,FIG_ENG] = report_KL(rKL,m,...
    NodoKlinoLink,toolrif,unitrif,datarif,contunit,Font_caption,Font_tools,...
    siteID,DT,DT_ENG,FIG,FIG_ENG,br,status,ATTIVA,activeEN,colonna4,conn,FileName)

fileID = fopen(FileName,'a');
fmt = '%s \r';
text = 'report_KL function started';
fprintf(fileID,fmt,text);

import mlreportgen.dom.*
import mlreportgen.report.*

% Make sure DOM is compilable
makeDOMCompilable()

GI_AngoloXKL = [];
GI_AngoloYKL = [];
GI_AngoloKL = [];
GI_NumKL = [];
GI_DateKL = [];
NODATA(m,1) = 0;
check = 0;
while check == 0   
    if status(m,1) == 1
        if ATTIVA == 1
            ATTIVA = 0;
            testo = Paragraph('Catena non ancora installata o inattiva.');
            add(DT,testo);
            if activeEN == 1
                testo = Paragraph('Array not installed or inactive.');
                add(DT_ENG,testo);
            end
        end
        check = 1;
    elseif status(m,1) == 3
        if ATTIVA == 1
            ATTIVA = 0;
            testo = Paragraph(['Monitoraggio completato. Invitiamo a visitare la '...
                'piattaforma web per la visione dei dati storici.']);
            add(DT,testo);
            if activeEN == 1
                testo = Paragraph(['Monitoring completed. Please log into the web-based platform '...
                    'to access the complete dataset.']);
                add(DT_ENG,testo);
            end
        end
        check = 1;
    else
        KE = Section();
        if activeEN == 1
            KE_EN = Section();
        end
        titolo = 1;
        
        if strcmp(char(colonna4(m+1,1)),'Klino Array D2W') == 1 % Clinometro Wi-Fi
            comando = ['select Date, Time, UnitName, ToolNameID, BatLevel, Temperature from RawDataView where Date >= ''' ...
                datarif ''' and UnitName = ''' char(unitrif) ''' and ToolNameID = '''...
                char(toolrif) ''' and NodeNum = 1 '];
            curs = exec(conn,comando);
            curs = fetch(curs);
            BatTemp = curs.Data;
            [~,cc] = size(BatTemp);
            if cc ~= 1 %ci sono dati riferiti all'ultimo mese/periodo di interesse
                DataPlot = [BatTemp(:,1) BatTemp(:,2)];
                % sistemo date, batteria e temperatura
                [rD,~] = size(DataPlot);
                T = [cell2mat(DataPlot(:,1)) repmat(' ', [rD,1]) cell2mat(DataPlot(:,2))];
                Date = datenum(T);
                Batteria = cell2mat(BatTemp(:,5));
                Temperatura = cell2mat(BatTemp(:,6));
                    
                % testo introduttivo
                testoB1 = Paragraph(['I valori di tensione di alimentazione del modulo Wi-Fi registrati '...
                    'durante il periodo di monitoraggio sono riportati di seguito. Il corretto funzionamento '...
                    'del sistema ' char(232) ' assicurato per una carica superiore a 7 V. L''ultimo dato '...
                    'disponibile ' char(232) ' pari a ' num2str(Batteria(end,1)) ' V.']);
                testoB2 = Paragraph(['Il modulo integra al proprio interno un termometro '...
                    'per monitorate la temperatura di esercizio ed identificare eventuali '...
                    'anomalie. I dati di temperatura registrati sono riportati di seguito.']);
                testoB1.HAlign = 'justify';
                testoB2.HAlign = 'justify';
                    
                % grafico batteria
                figure(19)
                plot(Date,Batteria);
                hold on
                title('Batteria e Temperatura del D2W');
                xlabel('Data [gg/mm/aaaa]');
                ylabel('Livello di Batteria [V]');
                ylim([floor(min(Batteria(:,1))) ceil(max(Batteria(:,1)))]);
                
                yyaxis right
                GMUX = plot(Date,Temperatura,':','LineWidth',1.1);
                ylim([floor(min(Temperatura(:,1))) ceil(max(Temperatura(:,1)))]);
                ylabel(['Temperatura [' char(176) 'C]']);
                set(gca,'YColor','k');
                str(1,1) = cellstr('Batteria');
                str(2,1) = cellstr('Temperatura');
                legend(str,'Location','northwest');
                h = gca;
                h.XAxis.MinorTick = 'on';
                datetick('x','dd/mm/yyyy','keepticks','keeplimits');
                xtickangle(20);
                grid on
                grid minor
                xlim([Date(1)-1 Date(end)+1]);
                    
                TempName = char(strcat('Report',siteID,'-', contunit,'-', num2str(m) ,'-D2W.png'));
                saveas(GMUX,TempName);
                ChartGMUX = Image(TempName);
                ChartGMUX.Style = {Height('8cm'),HAlign('center')};
                if Batteria(end,1) > 6.5
                    TempNameB = char(strcat('B_13.jpg'));
                elseif Batteria(end,1) > 6
                    TempNameB = char(strcat('B_12.jpg'));
                elseif Batteria(end,1) > 5.8
                    TempNameB = char(strcat('B_115.jpg'));
                elseif Batteria(end,1) > 5.6
                    TempNameB = char(strcat('B_11.jpg'));
                else
                    TempNameB = char(strcat('B_10.jpg'));
                end
                Batt = Image(TempNameB);
                Batt.Style = {Height('4cm'),HAlign('center')};
                    
                lot = Table({ChartGMUX, Batt});
                lot.TableEntriesStyle = {HAlign('center'),VAlign('middle')};
                lot.Style = {ResizeToFitContents(false),Width("100%")};
                grps(1) = TableColSpecGroup;
                grps(1).Span = 2;
                specs(1) = TableColSpec;
                specs(1).Span = 1;
                specs(1).Style = {Width("80%")};
                specs(2) = TableColSpec;
                specs(2).Span = 1;
                specs(2).Style = {Width("20%")};
                grps(1).ColSpecs = specs;
                lot.ColSpecGroups = grps;
                    
                lot_cap = Paragraph(['Fig. ' num2str(FIG) ' - Livello di carica della batteria e temperatura del '...
                    'D2W registrati durante il periodo di riferimento']);
                FIG = FIG+1;
                lot_cap.Style = {HAlign('center'),FontSize(Font_caption),Italic(1),Color('midnightblue')};
                Batt = Section();
                sezBATT = Heading3('D2W - Batteria e Temperatura');
                sezBATT.Style = {FontSize(Font_tools),Bold(1),Italic(1)};
                Batt.Title = sezBATT;
                add(DT,sezBATT);
                add(DT,testoB1);
                add(DT,testoB2);
                add(DT,lot);
                add(DT,lot_cap);
                add(DT,br);
                close(figure(19));
                    
                if activeEN == 1
                    testoB1 = Paragraph(['The following chart reports the D2W battery level trend recorded '...
                        'during the reference time period. '...
                        'The correct functioning of the data acquisition system is guaranteed for a '...
                        'minimum level of 7 V. The last available data is equal to ' num2str(Batteria(end,1)) ' V.']);
                    testoB2 = Paragraph(['The module equips also a thermometer that allows the monitoring '...
                        'of the working temperature and the identification of eventual malfunctioning. The same '...
                        'chart displays also temperature data recorded.']);
                    testoB1.HAlign = 'justify';
                    testoB2.HAlign = 'justify';
                    
                    % grafico batteria
                    figure(19)
                    plot(Date,Batteria);
                    hold on
                    title('D2W battery level and temperature');
                    xlabel('Date [dd/mm/yyyy]');
                    ylabel('Battery Level [V]');
                    ylim([floor(min(Batteria(:,1))) ceil(max(Batteria(:,1)))]);
                        
                    yyaxis right
                    GMUX = plot(Date,Temperatura,':','LineWidth',1.1);
                    ylim([floor(min(Temperatura(:,1))) ceil(max(Temperatura(:,1)))]);
                    ylabel(['Temperature [' char(176) 'C]']);
                    set(gca,'YColor','k');
                    str(1,1) = cellstr('Battery');
                    str(2,1) = cellstr('Temperature');
                    legend(str,'Location','northwest');
                    h = gca;
                    h.XAxis.MinorTick = 'on';
                    datetick('x','dd/mm/yyyy','keepticks','keeplimits');
                    xtickangle(20);
                    grid on
                    grid minor
                    xlim([Date(1)-1 Date(end)+1]);
                        
                    TempName = char(strcat('Report',siteID,'-', contunit,'-D2W_ENG.png'));
                    saveas(GMUX,TempName);
                    ChartGMUX = Image(TempName);
                    ChartGMUX.Style = {Height('8cm'),HAlign('center')};
                    Batt = Image(TempNameB);
                    Batt.Style = {Height('4cm'),HAlign('center')};
                    
                    lot = Table({ChartGMUX, Batt});
                    lot.TableEntriesStyle = {HAlign('center'),VAlign('middle')};
                    lot.Style = {ResizeToFitContents(false),Width("100%")};
                    grps(1) = TableColSpecGroup;
                    grps(1).Span = 2;
                    specs(1) = TableColSpec;
                    specs(1).Span = 1;
                    specs(1).Style = {Width("80%")};
                    specs(2) = TableColSpec;
                    specs(2).Span = 1;
                    specs(2).Style = {Width("20%")};
                    grps(1).ColSpecs = specs;
                    lot.ColSpecGroups = grps;
                        
                    lot_cap = Paragraph(['Fig. ' num2str(FIG_ENG) ' - Battery level and temperature recorded '...
                        'by the D2W during the reference time period']);
                    FIG_ENG = FIG_ENG+1;
                    lot_cap.Style = {HAlign('center'),FontSize(Font_caption),Italic(1),Color('midnightblue')};
                    Batt_ENG = Section();
                    sezBATT_ENG = Heading3('D2W - Battery and temperature');
                    sezBATT_ENG.Style = {FontSize(Font_tools),Bold(1),Italic(1)};
                    Batt_ENG.Title = sezBATT_ENG;
                    add(DT_ENG,sezBATT_ENG);
                    add(DT_ENG,testoB1);
                    add(DT_ENG,testoB2);
                    add(DT_ENG,lot);
                    add(DT_ENG,lot_cap);
                    add(DT_ENG,br);
                    close(figure(19));
                end
            end
        end
        
        for k = 1:rKL(m,1)
            NodeNum = num2str(NodoKlinoLink(k,m));
            comando = ['select EventDate, EventTime, XShift, YShift, T_node from ElabDataView where EventDate >= ''' ...
                datarif ''' and  ToolNameID = ''' char(toolrif) ''' and UnitName = ''' char(unitrif) ...
                ''' and NodeNum = ''' NodeNum ''' '];
            curs = exec(conn,comando);
            curs = fetch(curs);
            Dati = curs.Data;
            % Modifico il formato di data e ora
            [rD,rC] = size(Dati);
            if rC ~= 1
                T = [cell2mat(Dati(:,1)) repmat(' ', [rD,1]) cell2mat(Dati(:,2))];
                Date = datenum(T); % Data
                TiltX(:,k) = cell2mat(Dati(:,3)); % asse x
                TiltY(:,k) = cell2mat(Dati(:,4)); % asse y
                TempKL(:,k) = cell2mat(Dati(:,5)); % temperatura
                if k == 1 % Il primo lo scrivo e creo la variabile di controllo
                    check = 1;
                else
                    [rS,~] = size(TiltX(:,k-1));
                    if rD ~= rS
                        NODATA(m,1) = 2;
                        check = 0;
                        break
                    else
                        check = 1;
                    end
                end
            else
                NODATA(m,1) = 1;
                check = 1;
            end
            if NODATA(m,1) == 0
                % grafico inclinazione-tempo asse X,Y NELL'ULTIMO MESE
                figure(1)
                subplot(2,1,1); % (righe colonne posizione)
                pbaspect([3 1 1]);
                yyaxis left
                plot(Date,TiltX(:,k));
                MAX = max(TiltX(:,k));
                MIN = min(TiltX(:,k));
                if MIN > -0.1 && MAX < 0.1
                    ylim([-0.1 0.1]);
                end
                if isnan(TempKL(:,k)) == 0
                    yyaxis right
                    hold on
                    plot(Date,TempKL,':','LineWidth',1.1);
                    yyaxis right
                    ylabel(['Temperatura [' char(176) 'C]']);
                    set(gca,'YColor','k');
                end
                xlim([Date(1)-1 Date(end)+1]);
                title(['Inclinazione clinometro ' NodeNum ' - asse X']);
                xlabel('Data [gg/mm/aaaa]');
                yyaxis left
                ylabel(['Inclinazione [' char(176) ']']);
                set(gca,'YColor','k');
                
%                 str(1,1) = cellstr('Tilt X');
%                 str(2,1) = cellstr('Temperature');
%                 legend(str,'Location','southwest','FontSize',9);
                
                h = gca;
                h.XAxis.MinorTick = 'on';
                datetick('x','dd/mm/yyyy','keepticks','keeplimits');
                xtickangle(20);
                grid on
                grid minor
                
                hold off
                subplot(2,1,2)
                pbaspect([3 1 1]);
                yyaxis left
                InclY = plot(Date,TiltY(:,k));
                MAX = max(TiltY(:,k));
                MIN = min(TiltY(:,k));
                if MIN > -0.1 && MAX < 0.1
                    ylim([-0.1 0.1]);
                end
                if isnan(TempKL) == 0
                    yyaxis right
                    hold on
                    InclY = plot(Date,TempKL(:,k),':','LineWidth',1.1);
                    yyaxis right
                    ylabel(['Temperatura [' char(176) 'C]']);
                    set(gca,'YColor','k');
                end
                xlim([Date(1)-1 Date(end)+1]);
                title(['Inclinazione clinometro ' NodeNum ' - asse Y']);
                xlabel('Data [gg/mm/aaaa]');
                yyaxis left
                ylabel(['Inclinazione [' char(176) ']']);
                set(gca,'YColor','k');
                h = gca;
                h.XAxis.MinorTick = 'on';
                datetick('x','dd/mm/yyyy','keepticks','keeplimits');
                xtickangle(20);
                grid on
                grid minor
                
%                 str(1,1) = cellstr('Tilt Y');
%                 str(2,1) = cellstr('Temperature');
%                 legend(str,'Location','southwest');
                
                legendaKL = Image(('legendaKL.png'));
                legendaKL.Style = {Height('0.4cm'),HAlign('center')};
                
                TempName = char(strcat('Report',siteID,'-', char(toolrif),'-Klino', NodeNum, '.png'));
                saveas(InclY,TempName);
                ChartKL = Image(TempName);
                ChartKL.Style = {ScaleToFit};
                ChartKL_cap = Paragraph(['Fig. ' num2str(FIG) ' - Inclinazione in direzione '...
                    'strumentale X e Y registrata dal sensore MEMS '...
                    'del nodo ' NodeNum ' durante il periodo temporale di riferimento']);
                FIG = FIG+1;
                ChartKL_cap.Style = {HAlign('justify'),FontSize(Font_caption),Italic(1),Color('midnightblue')};
                if titolo == 1
                    sezKlino = Heading3('Klino Link');
                    sezKlino.Style = {OuterMargin('0in','0in','0.15in','0in'),FontSize(Font_tools),Bold(1),Italic(1)};
                    KE.Title = sezKlino;
                    add(DT,sezKlino);
                    if activeEN == 0
                        titolo = 0;
                    end
                end
                if k == 1
                    testo = Paragraph(['I grafici seguenti riportano i valori di inclinazione assoluta misurati '...
                        'nel periodo temporale di riferimento lungo gli assi strumentali X e Y dai clinometri '...
                        'presenti in sito.']);
                    testo.HAlign = 'justify';
                    add(DT,testo);
                end
                testo2 = Paragraph(['Il nodo numero ' NodeNum ' ha rilevato un''inclinazione massima lungo l''asse X '...
                    'pari a ' num2str(round(max(TiltX(:,k)),2),'%0.2f') '' char(176) ' ed un valore minimo pari a '...
                    num2str(round(min(TiltX(:,k)),2), '%0.2f') '' char(176) ', per una variazione massima uguale a '...
                    num2str(round(max(TiltX(:,k)),2)-round(min(TiltX(:,k)),2), '%0.2f')...
                    char(176) '. Per quanto riguarda l''asse Y, i valori massimi e minimi sono rispettivamente '...
                    ' pari a ' num2str(round(max(TiltY(:,k)),2), '%0.2f') '' char(176) ' e ' num2str(round(min(TiltY(:,k)),2), '%0.2f')...
                    char(176) ', con una variazione massima di ' num2str(round(max(TiltY(:,k)),2)-round(min(TiltY(:,k)),2), '%0.2f')...
                    char(176) ' di inclinazione.']);
                testo2.HAlign = 'justify';
                add(DT,testo2);
                add(DT,ChartKL);
                add(DT,legendaKL);
                add(DT,ChartKL_cap);
                add(DT,br);
                close(figure(1));
                
                if activeEN == 1
                    % grafico inclinazione-tempo asse X,Y NELL'ULTIMO MESE
                    figure(1)
                    subplot(2,1,1); % (righe colonne posizione)
                    pbaspect([3 1 1]);
                    yyaxis left
                    plot(Date,TiltX(:,k));
                    if isnan(TempKL(:,k)) == 0
                        yyaxis right
                        hold on
                        plot(Date,TempKL,':','LineWidth',1.1);
                        yyaxis right
                        ylabel(['Temperature [' char(176) 'C]']);
                        set(gca,'YColor','k');
                    end
%                     str(1,1) = cellstr('Tilt X');
%                     str(2,1) = cellstr('Temperature');
%                     legend(str,'Location','southwest');
                
                    xlim([Date(1)-1 Date(end)+1]);
                    title(['Tilt ' NodeNum ' - X axis']);
                    xlabel('Date [dd/mm/yyyy]');
                    yyaxis left
                    ylabel(['Tilt [' char(176) ']']);
                    set(gca,'YColor','k');
                    
                    h = gca;
                    h.XAxis.MinorTick = 'on';
                    datetick('x','dd/mm/yyyy','keepticks','keeplimits');
                    xtickangle(20);
                    grid on
                    grid minor
                    
                    hold off
                    subplot(2,1,2)
                    pbaspect([3 1 1]);
                    yyaxis left
                    InclY = plot(Date,TiltY(:,k));
                    if isnan(TempKL) == 0
                        yyaxis right
                        hold on
                        InclY = plot(Date,TempKL(:,k),':','LineWidth',1.1);
                        yyaxis right
                        ylabel(['Temperature [' char(176) 'C]']);
                        set(gca,'YColor','k');
                    end
                    xlim([Date(1)-1 Date(end)+1]);
                    title(['Tilt ' NodeNum ' - Y axis']);
                    xlabel('Date [dd/mm/yyyy]');
                    yyaxis left
                    ylabel(['Tilt [' char(176) ']']);
%                     str(1,1) = cellstr('Tilt Y');
%                     str(2,1) = cellstr('Temperature');
%                     legend(str,'Location','southwest');
                    
                    set(gca,'YColor','k');
                    h = gca;
                    h.XAxis.MinorTick = 'on';
                    datetick('x','dd/mm/yyyy','keepticks','keeplimits');
                    xtickangle(20);
                    grid on
                    grid minor
                    
                    TempName = char(strcat('Report',siteID,'-', char(toolrif),'-Klino', NodeNum, '_ENG.png'));
                    saveas(InclY,TempName);
                    ChartKL = Image(TempName);
                    ChartKL.Style = {ScaleToFit};
                    ChartKL_cap = Paragraph(['Fig. ' num2str(FIG_ENG) ' - Tilt recorded by MEMS sensor '...
                        'during the reference monitoring period along X and Y instrumental axes of node '...
                         NodeNum '']);
                    FIG_ENG = FIG_ENG+1;
                    ChartKL_cap.Style = {HAlign('justify'),FontSize(Font_caption),Italic(1),Color('midnightblue')};
                    if titolo == 1
                        if activeEN == 0
                            KE_ENG.Title = sezKlino;
                            add(DT_ENG,sezKlino);
                            titolo = 0;
                        end
                    end
                    if k == 1
                        testo = Paragraph(['The following graphs show the tilt angles recorded along X and Y '...
                            'instrumental axes during the reference monitoring period.']);
                        testo.HAlign = 'justify';
                        add(DT_ENG,testo);
                    end
                    testo2 = Paragraph(['Node number ' NodeNum ' highlighted a maximum and a minimum tilt of '...
                        num2str(round(max(TiltX(:,k)),2),'%0.2f') '' char(176) ' and '...
                        num2str(round(min(TiltX(:,k)),2),'%0.2f') '' char(176) ' respectively, along X axis. '...
                        'The angle variation equals ' num2str(round(max(TiltX(:,k)),2)-round(min(TiltX(:,k)),2), '%0.2f')...
                        char(176) '. Y axis showed maximum and minimum values equal to '...
                        num2str(round(max(TiltY(:,k)),2), '%0.2f') '' char(176) ' and ' num2str(round(min(TiltY(:,k)),2), '%0.2f')...
                        char(176) '. The variation is ' num2str(round(max(TiltY(:,k)),2)-round(min(TiltY(:,k)),2), '%0.2f')...
                        char(176) '.']);
                    testo2.HAlign = 'justify';
                    add(DT_ENG,testo2);
                    add(DT_ENG,ChartKL);
                    add(DT_ENG,legendaKL);
                    add(DT_ENG,ChartKL_cap);
                    add(DT_ENG,br);
                    close(figure(1));
                end
            else
                if ATTIVA == 1
                    testo = Paragraph('Non sono presenti dati relativi al periodo temporale considerato.');
                    ATTIVA = 0;
                    add(DT,testo);
                    if activeEN == 1
                        testo = Paragraph('No data available for the reference time period.');
                        add(DT_ENG,testo);
                        if m == 1
                            add(DT_ENG,br);
                        end
                    end
                    check = 1;
                end
            end
        end
        if rC ~= 1
            var1 = max(abs(TiltX-TiltX(1,:)));
            varX = max(var1);
            indX = find(var1 == varX);
            var2 = max(abs(TiltX-TiltX(1,:)));
            varY = max(var2);
            indY = find(var2 == varX);
            MAX = max(varX,varY);
            indM = find(max(varX,varY)==MAX);
            if indM == 1 % X
                GI_AngoloXKL = TiltX(:,indX)-TiltX(1,indX);
                GI_AngoloYKL = TiltY(:,indX)-TiltY(1,indX);
                GI_NumKL = NodoKlinoLink(indX,m);
                GI_DateKL = Date;
            else % Y
                GI_AngoloXKL = TiltX(:,indY)-TiltX(1,indY);
                GI_AngoloYKL = TiltY(:,indY)-TiltY(1,indY);
                GI_NumKL = NodoKlinoLink(indY,m);
                GI_DateKL = Date;
            end
        end
    end
end
if isempty(GI_AngoloXKL) == 0
    GI_AngoloKL(:,1) = GI_AngoloXKL;
    GI_AngoloKL(:,2) = GI_AngoloYKL;
end

text = 'report_KL function executed correctly';
fprintf(fileID,fmt,text);
fclose(fileID);

end