Purification of Single and Entangled Photons by Wavepacket Shaping