Refactor code, start index with 0 and remove use of detach