New version from Marcos. Previous version did not contain
all the logic.