Added tests and fixed some edge case bugs