added some comments, fixed some edge cases