Fix some edge cases. Cleanup code