% funzione che definisce i dati per l'estensimetro 2D, in particolare
% tempo (Time2DCrL) e Dato (Crack2D)

function [Time2DCrL,Crack2D,NTCCrack2D,Err2DCrackLink,ErrNTC2DCrackLink] = ...
    defDati2DCrL(Dati2DCrackLink,DatiNTC2DCrackLink,Err2DCrackLink,ErrNTC2DCrackLink,...
    r2DCrL,Nodo2DCrackLink,Ch2DCrL,CrL2D_NTC,Ndatidespike,FileName)

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

CrL2D_Or = cell2mat(Nodo2DCrackLink(:,6));

[r,c] = size(Dati2DCrackLink);
Ncorr = 0;

% Elimino gli eventuali Not a Number
for a = 2:r
    ntc = 1;
    control = 1;
    for b = 2:c
        check = isnan(Dati2DCrackLink(a,b));
        if check == 1
            Dati2DCrackLink(a,b) = Dati2DCrackLink(a-1,b);
            Err2DCrackLink(a,b-1) = 1;
            Ncorr = Ncorr+1;
        end
        if control == 1
            if CrL2D_NTC(ntc) == 1 % La prima colonna è una data
                check = isnan(DatiNTC2DCrackLink(a,ntc));
                if check == 1
                    DatiNTC2DCrackLink(a,b) = DatiNTC2DCrackLink(a-1,ntc);
                    ErrNTC2DCrackLink(a,b-1) = 0.5;
                    Ncorr = Ncorr+1;
                end
            end
            control = control+1;
            ntc = ntc+1;
        end
    end
end

text = ['' num2str(Ncorr) ' NaN of 2D Crack Link corrected by defDati2DCrL function'];
fprintf(fileID,fmt,text);

Time2DCrL = Dati2DCrackLink(:,1); % data
Crack2D = Dati2DCrackLink(:,2:end); 
NTCCrack2D = zeros(r,r2DCrL);
b = 2; % colonna del primo dato
for s = 1:r2DCrL
    if Ch2DCrL(s,1) == 1 || Ch2DCrL(s,1) >= 2 %Solo fessurimetro
        if CrL2D_NTC(s,1)==1 % si legge anche il termometro
            NTCCrack2D(:,s) = DatiNTC2DCrackLink(:,b); % dati NTC
        end
        b = b+1;
    end
end

Num_Dati = Ndatidespike; % numero di dati per il despike
if Num_Dati > r
    Num_Dati = r;
end

i = 1;
cont = 1;
X = zeros(r,r2DCrL);
Y = zeros(r,r2DCrL);
while i <= 2*r2DCrL
    % despiking Fessurimetri
    X(1:end-1,cont) = filloutliers(Crack2D(1:end-1,i),'linear','movmedian',Num_Dati);  
    X(end,cont) = Crack2D(end,i);
    Y(1:end-1,cont) = filloutliers(Crack2D(1:end-1,i+1),'linear','movmedian',Num_Dati);
    Y(end,cont) = Crack2D(end,i+1);
    i = i+2;
    cont = cont+1;
end

if CrL2D_Or == 12
    X_Corr = X;
    Y_Corr = Y;
elseif CrL2D_Or == 21
    X_Corr = Y;
    Y_Corr = X;
end

i = 1;
cont = 1;
while i <= 2*r2DCrL    
      Crack2D(:,i) = X_Corr(:,cont);
      Crack2D(:,i+1) = Y_Corr(:,cont);
      i = i+2;
      cont = cont+1;
end

text = 'Data of 2D Crack Link defined correctly. defDati2DCrL function closed';
fprintf(fileID,fmt,text);
fclose(fileID);
end