Some bug fixing and improvements