Modified code to use new .toMat functionality.