using implementation described on 1c7c554 (gracias Fabricio)