refactor for greater clarity & less global ns pollution. Also fixes some encoding/parsing issues