cleaned up code and tried to used sparse arrays