Cleaned up the functions to match the spec. Will add comments if I have the time to.