Updated for Ruby 2.1, some refactoring.