Generalize path manipulation and make it more robust