Remove unneeded cast, reduce duplication, move declarations to their fir...

...st use.