More refactoring, seems to be working now