More efficient version to avoid memory leaks and segfaults