Almost working with better performance, but lines 146 and 147 cause a segfault. I need to figure out why