fixed memory leak, cleaned up code