Added comments and tweaked some functions.

Added detailed comments explaining each function and tweaked the
behavior of some functions.