fixed use of index_to_xy
refactored stuff into functions