Some bugs and memory laek fixes, remove duplicated codes.