Factor duplicate code. Add more comments

Signed-off-by: Leonardo de Moura <leonardo@microsoft.com>