lots of refactoring but it segfaults
fixed seg fault