Refactor task.lua to make the code easier to read/maintain