Main Hapre algorithm