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

function [TimeSM,Stress,NTCStress,ErrStressMeter] = defDatiSM(DatiStressMeter,...
    DatiNTCStressMeter,ErrStressMeter,ChSM,SM_NTC,rSM,Ndatidespike,FileName)

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

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

text = ['' num2str(Ncorr) ' NaN of Stress Meter corrected by defDatiSM function'];
fprintf(fileID,fmt,text);

TimeSM = DatiStressMeter(:,1); % data    
Stress = zeros(r,rSM);
NTCStress = zeros(r,rSM);
b = 2; % colonna del primo dato
for s = 1:rSM
    Stress(:,s) = DatiStressMeter(:,b); % dati
    if ChSM(s,1) == 1 || ChSM(s,1) >= 2 %Solo Stress M
        if SM_NTC(s,1)==1 % si legge anche il termometro
            NTCStress(:,s) = DatiNTCStressMeter(:,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:rSM
    % despiking accelerometri
    Stress(:,i) = filloutliers(Stress(:,i),'linear','movmedian',Num_Dati);     
end

text = 'Data of Stress Meter defined correctly. defDatiSM function closed';
fprintf(fileID,fmt,text);
fclose(fileID);
end