Refactored and simplified a bit for better code quality.