fix many bugs, see the google doc for details