Initial version of code to answer https://www.biostars.org/p/112049/