Fix many bugs and minor improvements