huge refactor and cleanup for protocol 2.1-pre and to be browserify compatible and modularized