Probably safer to move the iterator before deleting item.

This makes also the code a bit simpler. Further work for
previous fix (crash while removing unused masks).