Rebased from upstream. Last commit in upstream: d78fb64

fixed bug causing fitRegionFactor to not be used and refactoring