Segfault and efficiency fixes