Cleaned up code, introduced use of const and references.