porting #668 to master branch