major refactoring, hopefully reordering fixes crash issue