rebased the old patch. changed a bit to avoid performance concerns.