rewrite logic part and some bug fix.