Improved performance, cleaned up code and fixed bugs.

Grid now uses dictionary instead of list.