function [ success ] = ric(pFilename, pFloatname, pCurrentCycle, pData)
%RIC Saves the given data to the filename in RIC format.
%   
%   Parameters:
%       pFilename (string) The destination filename.
%       pFloatname (string) The name of the float.
%       pCurrentCycle (string) The current cycle.
%       pData (matrix) The data that should be written to the RIC file.
%           Each line contains one set of data. The matrix format needs to
%           be the following:
%           TIME LAT LON TEMP PRES
%           The TIME needs to be in julian rafos day format.


%% Initialize return variables
success = false;

%% Initialize variables required for processing

%% Parameter check

parameterError = false;

if (~ischar(pFilename))
    warning([mfilename ': Given filename is not a string!']);
    parameterError = true;
end
if (~ischar(pFloatname))
    warning([mfilename ': Given float name is not a string!']);
    parameterError = true;
end
if (~ischar(pCurrentCycle))
    warning([mfilename ': Given current cycle is not a string!']);
    parameterError = true;
end
if (size(pData, 2) ~= 5)
    warning([mfilename ': Given data has ' site(pData, 2) ' columns, but 5 expected!']);
    parameterError = true;
end

if (parameterError)
    return;
else
    clear parameterError;
end

%% Replace all NaN with default values
defaultValue = -999;
for i = 1:size(pData, 2)
    nanIndex = find(isnan(pData(:, i)));
    if ~isempty(nanIndex)
        pData(nanIndex, i) = repmat(defaultValue, 1, size(pData, 1));
    end
    clear nanIndex;
end

%% Generate file format

offsetHour = 0.0000000001;
offsetRafosJulianDay = 2440000;

fileString = '';

for i = 1:size(pData, 1)
    ddmmyyyy = artoa.convert.rafosJulianDay(pData(i, 1));
    ddmmyyyy(3) = mod(ddmmyyyy(3), 100);
    hour = 24 * (pData(i, 1) - floor(pData(i, 1))) + offsetHour;
    minute = round(hour - floor(hour));
    second = round(minute - floor(minute));
    hour = floor(hour);
    minute = round(minute);
    fileString = [ ...
        fileString ...
        pFloatname ' - cycle ' pCurrentCycle ...
        ' ' ...
        num2str(ddmmyyyy(3), '%2.2i') ...
        num2str(ddmmyyyy(2), '%2.2i') ...
        num2str(ddmmyyyy(1), '%2.2i') ...
        num2str(hour, '%2.2i') ...
        num2str(minute, '%2.2i') ...
        num2str(second, '%2.2i') ...
        num2str(pData(i, 2), '%7.3f') ...
        num2str(pData(i, 3), '%8.3f') ...
        ' 0' ...
        ' -999.000' ...
        ' -999.000' ...
        ' ' ...
        num2str(pData(i, 4), '%7.2f') ...
        ' ' ...
        num2str(pData(i, 5), '%7.2f') ...
        ' ' ...
        num2str((pData(i, 1) + offsetRafosJulianDay), '%8.0f') ...
        '.\n' ...
    ];
end

%% Save to file

fid = fopen(pFilename, 'w');
fprintf(fid, fileString);
fclose(fid);

%% Update return variable

success = true;

end