fixed bug freeing memory in the wrong order