Changed code to prevent memory leaks.