Refactoring and an attempt to debug seg fault