sophia: refactoring and code cleanup