Move and clean up utils.lua.
Refactor all code to new API; several minor changes/bug fixes.