Refactored to mostly pass jsLint