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

function [TimeWEL,WireExtensometer,NTCWireExtensometer,ErrWireExtensometerLink]...
    = defDatiWEL(DatiWireExtensometerLink,DatiNTCWireExtensometerLink,...
    ErrWireExtensometerLink,ChWEL,WEL_NTC,rWEL,Ndatidespike,FileName)

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

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

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

TimeWEL = DatiWireExtensometerLink(:,1); % data   
WireExtensometer = zeros(r,rWEL); % dati Wire Extensometer Link  
NTCWireExtensometer = zeros(r,rWEL);

b = 2; % colonna del primo dato
for s = 1:rWEL
    WireExtensometer(:,s) = DatiWireExtensometerLink(:,b); % dati Wire Extensometer Link
    if ChWEL(s,1) == 1 || ChWEL(s,1) >= 2 % Solo estensimetro
        if WEL_NTC(s,1)==1 % si legge anche il termometro
            NTCWireExtensometer(:,s) = DatiNTCWireExtensometerLink(:,b); % dati Extensometer Link
        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:rWEL
    % despiking Barrette Estensimetriche
    WireExtensometer(1:end-1,i) = filloutliers(WireExtensometer(1:end-1,i),'linear','movmedian',Num_Dati);    
end

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