There's a lot of duplication of this bracket counting loops...