fix many bugs and add some new functions