Added comments, asserts, and re-wrote the cumsum code to be more numerically stable.