better region detection code