Improved bracket matching and space calculation