Refactored code to use a struct pointer, removed possible memory leaks