Refactoring mage code