Move logic to model. Add some unit testing