reformat and refactor engine.js