Fixed segfault.
Some optimizations and fixes.