Refactor to avoid memory leak