finished refactor, added Nan-assisted version for reference