function [ sceneSchedule ] = manageOverlapping( sceneSchedule,minSpace )

% This program was written by Mathias Rossignol & Grégoire Lafay
% is Copyright (C) 2015 IRCAM <http://www.ircam.fr>
%
% This program is free software: you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the Free
% Software Foundation, either version 3 of the License, or (at your option)
% any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
% or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
% for more details.
%
% You should have received a copy of the GNU General Public License along
% with this program.  If not, see <http://www.gnu.org/licenses/>.

% get sceneSchedule index in order to have position in ascending order

positions= [sceneSchedule.position];
isBackground= [sceneSchedule.isBackground];
[~,index]=sort(positions(logical(~isBackground)));
index=index+length(isBackground(isBackground==1));
idFlag=zeros(length(unique([sceneSchedule.classId])),1);

endPos=0;
index2remove=[];
for jj = index    
    if(sceneSchedule(jj).position > endPos)
        endPos= sceneSchedule(jj).position+sceneSchedule(jj).duration;
        idFlag(sceneSchedule(jj).classId)=1;
    elseif(2*sceneSchedule(jj).duration>endPos-(sceneSchedule(jj).position+sceneSchedule(jj).duration) || idFlag(sceneSchedule(jj).classId)==0)
        sceneSchedule(jj).position=endPos+minSpace;
        endPos= sceneSchedule(jj).position+sceneSchedule(jj).duration;
        idFlag(sceneSchedule(jj).classId)=1;
     else
         index2remove=[index2remove jj];
    end  
end

sceneSchedule(index2remove)=[];