Fixed bugs pointed out by @andjuo.