Completed implementation, equivalent to the one in Monifu (scala).