function [ success ] = startEndToa(pFilename, pTrajectory, pSoundSources)
%STARTENDTOA Saves the given data in start end toa format.
%   Saves start and ending position of the given float.
%
%   Parameters:
%       pFilename (string) The destination filename.
%       pSoundSources (struct) The sound sources loaded using
%           artoa.load.soundsource function.
%       pTrajectory (struct) The trajectory data according to the memory
%           data format specification, see projects wiki.


%% Initialize return variables
success = false;

%% Initialize variables required for processing and defaults
noSoundSource = 'No SoSo';
dataString = '';

%% Parameter check

parameterError = false;


if (~isstring(pFilename) && ~ischar(pFilename))
    warning([mfilename ': Given filename is neither a string nor a char!']);
    parameterError = true;
end
if (~isstruct(pSoundSources))
    warning([mfilename ': Given sound source data is not a struct!']);
    parameterError = true;
end
if (~isstruct(pTrajectory))
    warning([mfilename ': Given trajectory data is not a struct!']);
    parameterError = true;
end

if (parameterError)
    return;
else
    clear parameterError;
end


%% Collect data
indexStart = find( ...
    pTrajectory.toaData.toaDate == min(pTrajectory.toaData.toaDate) ...
);
indexEnd = find( ...
    pTrajectory.toaData.toaDate == max(pTrajectory.toaData.toaDate) ...
);

% Collect toa
startToa = pTrajectory.toaData.toa(indexStart);
endToa = pTrajectory.toaData.toa(indexEnd);
% Collect toa date
startToaDate = pTrajectory.toaData.toaDate(indexStart);
endToaDate = pTrajectory.toaData.toaDate(indexEnd);

% Collect sound source names
startSources = pTrajectory.toaData.soundSource(indexStart);
endSources = pTrajectory.toaData.soundSource(indexEnd);

% Replace non selected soundsources by default string
startNotSelectedIndices = contains(startSources, '');
startSources(startNotSelectedIndices) = {noSoundSource};
endNotSelectedIndices = contains(endSources, '');
endSources(endNotSelectedIndices) = {noSoundSource};

for i = 1:length(startToa)
    dataString = [ dataString ...
        num2str(startToaDate(i)) ' ' ...
        num2str(startToa(i)) ' ' ...
        startSources{i} ' ' ...
        num2str(endToaDate(i)) ' ' ...
        num2str(endToa(i)) ' ' ...
        endSources{i} newline ...
    ];
end


%% Save to file
saveToFile(pFilename, '', dataString);

%% Update return variable
success = true;


%% Nested functions

    function saveToFile(pFilename, pHeader, pData)
        fid = fopen(pFilename, 'w');
        fprintf(fid, pHeader);
        fprintf(fid, pData);
        fclose(fid);
    end

end
