Fix bug in cast optimisation; fixes Trac #995