//-----------------------------------------------------------------------------
//----Checks that for every open bracket there's a corresponding closed one
//----This is not the same as balanced brackets
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define OPEN_BRACKETS  "{[(<"
#define CLOSE_BRACKETS "}])>"
//-----------------------------------------------------------------------------
int main(int argc,char *argv[]) {

    char *Open;
    char *Close;
    int Index;

    if (argc != 2) {
        printf("Usage: BalanceBrackets <string>\n");
        exit(EXIT_FAILURE);
    }

    Open = Close = argv[1];
//----Loop until no open bracket or error
    while (Open != NULL && Close != NULL) {
        printf("Now it's %s\n",Open);
//----See if there's another open bracket
        if ((Open = strpbrk(Open,OPEN_BRACKETS)) != NULL) {
            printf("Found open  %c\n",*Open);
//----Determine the corresponding close bracket
            Index = strchr(OPEN_BRACKETS,*Open) - OPEN_BRACKETS;
            printf("Look for %c\n",CLOSE_BRACKETS[Index]);
//----Look for a corresponding close bracket
            if ((Close = strrchr(Open,CLOSE_BRACKETS[Index])) != NULL) {
                printf("Found close %c\n",*Close);
//----If found, then reduce the string
                *Close = '\0';
                Open++;
            } else {
                Close = NULL;
            }
        }
    }

//----If exited because no open bracket, then OK
    if (Open == NULL) {
        printf("Balanced\n");
    } else {
        printf("Unbalanced\n");
    }
                
    exit(EXIT_SUCCESS);
}
//-----------------------------------------------------------------------------
