Made implementation more general