Refactor the level generate function