fixed memory leaks and permission errors