This code requires the grid method tool box written by Grediac. This code can be found here:
http://www.thegridmethod.net/code
