refactored steps 2/7 and 3/8 a bit
refactored index type into templates for lesser memory usage
refactored step 4 to return information step 5 needs (avoids extra work in step 5)