restruct the code.
fixed some logic error.