refactored grid functions. fixed 2 bugs