Implementing restart and shutdown features and some refactoring