Fix screw-ups and optimize code