hopefully finished region calculation code