Solving #1590

Took defining some helper functions and a bit of function renaming, to do it cleanly.

@ruimalheiro can you take a look and add some tests?