Clean up the code, add some additional documentation and address edge cases.