The idea of this code has been implemented in more details here: