% funzione che definisce i dati per la Barretta Estensimetrica, in particolare
% tempo (TimeCrL) e Dato (Crack)

function [TimeCrL,Crack,NTCCrack,ErrCrackLink] = defDatiCrL(DatiCrackLink,...
    DatiNTCCrackLink,ErrCrackLink,ChCrL,CrL_NTC,rCrL,Ndatidespike,FileName)

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

[r,c] = size(DatiCrackLink);
Ncorr = 0;
% Elimino gli eventuali Not a Number
for a = 2:r
    for b = 2:c
        check = isnan(DatiCrackLink(a,b));
        if check == 1
            DatiCrackLink(a,b) = DatiCrackLink(a-1,b);
            ErrCrackLink(a,b-1) = 1;
            Ncorr = Ncorr+1;
        end
        if CrL_NTC(b-1) == 1 % La prima colonna è una data
            check = isnan(DatiNTCCrackLink(a,b));
            if check == 1
                DatiNTCCrackLink(a,b) = DatiNTCCrackLink(a-1,b);
                if ErrCrackLink(a,b-1) == 0
                    ErrCrackLink(a,b-1) = 0.5;
                else
                    ErrCrackLink(a,b-1) = 1;
                end
                Ncorr = Ncorr+1;
            end
        end
    end
end

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

TimeCrL = DatiCrackLink(:,1); % data  
Crack = zeros(r,rCrL);
NTCCrack = zeros(r,rCrL);
b = 2; % colonna del primo dato
for s = 1:rCrL
    Crack(:,s) = DatiCrackLink(:,b);
    if ChCrL(s,1) == 1 || ChCrL(s,1) >= 2 % Solo fessurimetro
        if CrL_NTC(s,1)==1 % si legge anche il termometro
            NTCCrack(:,s) = DatiNTCCrackLink(:,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
for i = 1:rCrL
    % despiking accelerometri
    Crack(1:end-1,i) = filloutliers(Crack(1:end-1,i),'linear','movmedian',Num_Dati);     
end

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