Performance improvements, simplifications and bug fixes.

Signed-off-by: Ross Allan <rallanpcl@gmail.com>