Switched to a TreeMap to handle sorting and moved some things for efficiency.