Refactoring

I'm trying to break `index.js` into smaller pieces in spirit of #26. This is work in progress. Comments are welcome.