%-------------------------%
%   Read siteCEBa Ouput   %
%-------------------------%

clc;                % Refresh Command Window
clear;              % clear Workspacepwd
close all;          % close all Figures
format long g       % 14 decimal places

addpath(genpath('../../Functions')) % Load functions
physicalConstants



siteName    = 'trop';             % choose between trop thar and dice
surfScheme  = 'CEBa';
expID       = 'WatStr1';
onlyDiff    = true;

inputFolder   = './Input/';


switch siteName
    case 'trop'
        startNum    = datenum('01-Sep-2001');
        finalNum    = datenum('31-Oct-2003 23:45:00');
        siteFolder  = 'siteCEBa/outdata/Tropics/'; 
    case 'thar'
        startNum  = datenum('01-Jan-2006');
        finalNum  = datenum('31-Dec-2014 23:45:00');
        siteFolder  = 'siteCEBa/outdata/Tharandt/';
        siteFolder  = 'siteCEBa/outdata/DICE/';
    otherwise
        error('Site not avaiblable!')
end

inputFolder = [inputFolder siteFolder]; 
inputFile   = [siteName '.' surfScheme '.' expID '.txt'];

disp('Read raw data...')
fileID    = fopen([inputFolder inputFile]);
inputData = textscan(fileID,'%s %s %s %f');
fclose(fileID);

disp('Process raw data...')
rawNames     = inputData{3};
finalVarName = rawNames(end);
varNamePos   = find(ismember(rawNames,finalVarName));
varLen   = varNamePos(1);
varName  = rawNames(1:varLen);

rawData = inputData{4};
Data    = reshape(rawData,varLen,[]);
dtTotal = size(Data,2);

rawTime = linspace(startNum,finalNum,dtTotal)';


idx1 = 1;
idx2 = length(rawTime);

rowTimes = datetime(rawTime(idx1:idx2),'ConvertFrom','datenum');
raw = array2timetable(Data(:,idx1:idx2)','RowTimes',rowTimes,'VariableNames',varName);


if(onlyDiff)
    Tair = raw.Tair;
    Tcan = raw.Tfic;
    Tcas = raw.Tfca;
    cosz = raw.cosz;
    Time = raw.Time;
end


disp('Save raw data...')

if(onlyDiff)
    save(['./Output/' inputFile(1:end-4) '.rawTemp.mat'],'Tcan','Tair','Tcas','cosz','Time')
else
    save(['./Output/' inputFile(1:end-4) '.raw.mat'],'raw')
end




