Implementation code for least squares matching