Improve logic and documentation