Refactor code based on @rtripault 's suggestion