Cleaned up code, took care of some edge cases.