Refactor app to avoid memory leak