R: SGM code updated by Vince.