More code refactoring

Warning may break things, please test.