The implementation is based on this paper.