Major refactoring: separated code into model and controller