Cleanup logic. Add test.

Cleaned up the logic. Added a test.