Added direction detection (up or down) for bracket matching