fixed the nesting loops to check for the matching ']'