Several bugs and improvements