organized common part
rewrote in accordance with OpenCV reference