Copied and adapted from the master branch, with thanks to umarcor <unai.martinezcorral@ehu.eus> who did the original work.