Refactor with josevalim's help