Further refactoring (still incomplete though)