Relocate some code form header to source file. Cleanup.
Try to fix random segfaults on exit