Performance improvements, simplifications and bug fixes. 

Some of these changes may be style changes, and/or the string comparisons with '==' may have been intended (although I doubt that).

Signed-off-by: Ross Allan <rallanpcl@gmail.com>