Refractor codes - might have some logic error

import new sql please.