added better freeing of memory