After taking a look to the previous logic, I've tested several ways and I think that the last commit is working as expected, and the code is simpler than before.