using freep and removing redundant code