Fixed memory leaks and removed repeated code