Rewrite lib/index.js

Makes it a bit more readable and easier to maintain.