Fix a bug with reloading the stage and some code refactoring