More efficient 'dot product' and other minor refactoring