% funzione che definisce i dati per la cella di carico, in particolare
% tempo (TimeLL), batteria (BattLL) e ADC (ADCLoad)

function [TimeLL,ADCLoad,ErrLoadLink] = defDatiLL(DatiLoadLink,ErrLoadLink,...
    Ndatidespike,rLL,FileName)

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

[r,c]=size(DatiLoadLink);
Ncorr = 0;
% Elimino gli eventuali Not a Number
for a = 2:r
    for b = 1:c
        check = isnan(DatiLoadLink(a,b));
        if check == 1
            DatiLoadLink(a,b) = DatiLoadLink(a-1,b);
            ErrLoadLink(a,b-1) = 1;
            Ncorr = Ncorr+1;
        end
    end
end

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

TimeLL = DatiLoadLink(:,1); % data
[r,c] = size(DatiLoadLink);
ADCLoad = zeros(r,rLL);

s = 1;
b = 2;
while b <= c      
      ADCLoad(:,s) = DatiLoadLink(:,b); % dati ADC
      b = b+1;
      s = s+1;
end

s = 1;
Num_Dati = Ndatidespike; % numero di dati per il despike
if Num_Dati > r
    Num_Dati = r;
end
for i = 1:rLL
    % despiking
    ADCLoad(1:end-1,s) = filloutliers(ADCLoad(1:end-1,s),'linear','movmedian',Num_Dati);
    s = s+1;
end
    
text = 'Data of Load Link defined correctly';
fprintf(fileID,fmt,text);
fclose(fileID);

end