Added some function comments and slight refactoring