From this article, it seems to me that the proposed implementation of @gdalle is already correct, isn’t it?