##Windows PowerShell, 146 147 152 156 169
{$s='' -join([char[]]"$args "|%{if(32..90-eq$_){')'*(($x=$s.indexOf("$_".ToLower())+1)+$s.Length*!$x) $s=$s.substring($x)}else{"($_" $s="$_$s"}})} Passes all tests. Test script:
$tests = ("aAaAbB","(a)(a)(b)"),("abBcdDCA","(a(b)(c(d)))"),("bisSsIB","(b(i(s)(s)))"),("aAabc","(a)(a(b(c)))"),("abcdDA","(a(b(c(d))))"),("abcAaA", "(a(b(c)))(a)"),("acAC","(a(c))") "function f " + ((gc ./tags.ps1)-join"`n") | iex $tests | %{ $result = f $_[0] ("FAIL: $($_[0]):$($_[1]) - $result", 'PASS')[$result -ceq $_[1]] }