tested more thoroughly, handles more edge cases