improved removeduplicates function