refactoring, segmentation fault fix, bags in tests fix