Further adaption of Ron Van den Branden's code