segfault fixes and file handling