added an acknowledgement to Giacamo Vianello who wrote code on which some of this is based.