fix mem leaks and open files