Fixing references, refactoring some functions