Clean up  and move some code