porting 264329b37b2a312bb14e58a849e55ebe092d0665 from forrestv