close all, clear all

leggenda = 1;

%% Setup tempo

startTime = datenum('Aug 13, 2010  12:35:00.0000'); % anno mese giorno ora minuti secondi
dt = datenum('Jan 0, 0000  0:08:00.0000'); % tempo di campionamento

datestr(startTime,'HH:MM:SS:FFF dd/mm');
datestr(dt,'HH:MM:SS:FFF dd/mm');

path = '';

%% load csv files
files = dir((fullfile(path,'*.dat')));

start = 1;

for j = 1:length(files)
    data = load(fullfile(path,files(j).name));
    
    id = data(start:end,1);
    temperatureR = data(start:end,2);
    humidityR = data(start:end,3);
    totalRadiationR = data(start:end,4);
    activeRadiationR = data(start:end,5);
    internalVoltageR = data(start:end,6);

    log_ric(j).id = id;
    log_ric(j).temperature = -39.60 + 0.01*temperatureR;                                    % [C]
    log_ric(j).humidity = -4 + 0.0405*humidityR + (-2.8 * 10^-6)*(humidityR.^2);            % [%]
    log_ric(j).humidity_true = (log_ric(j).temperature - 25) .* (0.01 + 0.00008*humidityR) + log_ric(j).humidity; % [%]
    log_ric(j).activeRadiation = 0.625 * 1e6 * (activeRadiationR/100000) * 1000;            % [lux]
    log_ric(j).totalRadiation = 0.769 * 1e5 * (totalRadiationR/100000) * 1000;              % [lux]
    log_ric(j).internalVoltage = internalVoltageR/4096 * 3;                                 % [V]
    log_ric(j).name = files(j).name;
end
m = inf;
for j = 1:length(files)
    if ( length( log_ric(j).temperature ) < m)
        m = length( log_ric(j).temperature);
    end
end
for j = 1:length(files)
    log_ric(j).id = log_ric(j).id(1:m);
    log_ric(j).temperature = log_ric(j).temperature(1:m);
    log_ric(j).humidity = log_ric(j).humidity(1:m);
    log_ric(j).humidity_true = log_ric(j).humidity_true(1:m);
    log_ric(j).activeRadiation = log_ric(j).activeRadiation(1:m);
    log_ric(j).totalRadiation = log_ric(j).totalRadiation(1:m);
    log_ric(j).internalVoltage = log_ric(j).internalVoltage(1:m);                            % [V]
end

save LOG_DATA_RICERT log_ric;

for j = 1:length(files) 
    fid = fopen([log_ric(j).name(1,1:end-4) '.txt'], 'w');
    fprintf(fid, 'ID\tTemp\tHumidity\tHum_Real\tAct_Rad\tTot_Rad\tVolt\n');
    for k=1:m
        id = log_ric(j).id(k);
        temperature = log_ric(j).temperature(k);
        humidity = log_ric(j).humidity(k);
        humidity_true = log_ric(j).humidity_true(k);
        activeRadiation = log_ric(j).activeRadiation(k);
        totalRadiation = log_ric(j).totalRadiation(k);
        internalVoltage = log_ric(j).internalVoltage(k);
        fprintf(fid, '%d\t %5.2f\t %f\t %f\t %g\t %g\t %4.2f\n', id,temperature,humidity,...
            humidity_true,activeRadiation,totalRadiation,internalVoltage);
    end
    fclose(fid);
end
