Converted to coffeescript and refactored