Fixed memory leaks and refactored little bit