Major rewrite for better maintainability