Refine code and clean memory