some additional refactoring, seems to have fixed a memory error as well