Reorganized code, removed memory leaks