Improved debugging and refactored for modularity