Comment and refactor the distribution algorithm

Added comments, renamed variables and rearranged some statements.