Fixed the segfault issue, + some refactoring