I think you need to change the 19s on lines 95 and 97 to MAPH%-1 and MAPW%-1 respectively. This will limit the amount of READs done. So instead of... FOR FORY%=0 TO 19 FOR FORX%=0 TO 19 ...write this... FOR FORY%=0 TO MAPH%-1 FOR FORX%=0 TO MAPW%-1