answer from tex xchange included - to be improved for the different cases