Rewrite to remove duplication and improve