Code cleanup, move some parts to model