Adaptation of BDGK code from Sandro.