fix memleaks and logic flaw