Rewrote pretty much everything...doesn't segfault now:)