Fixes problem with indexing and refactors the code