fix the algorithm, add comments and refactors message delivery