Fix reference error, minor refactoring