@ruimalheiro can you add some comments as to what the following logic is doing?  It's not immediately obvious the need for the code, or what input parameter formats are accepted by this function.