Refactor code to prevent invalid index