Recoded the border checking code