add guards to prevent writing output beyond region of image
guard against reading from invalid input