refactored and fixed for polymorphic types