Reorganized some code to have better encapsulation