Fixed bugs in writing to grid files