/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
#include "circuitfinder.h"
string sarr[4] = {"0","<","<=","?"};
void CircuitFinder::unblock(int U)
{
  Blocked[U - 1] = false;

  while (!B[U - 1].empty()) {
    int W = B[U - 1].front();
    B[U - 1].pop_front();

    if (Blocked[W - 1]) {
      unblock(W);
    }
  }
}


bool2 CircuitFinder::circuit(int V)
{
  bool2 F;
  F.A= false;
  F.B = false;
  Stack.push_back(V);
  Blocked[V - 1] = true;
  //bool check;
  for (int W : AK[V - 1]) {
    if (W == S) {
      F.B = cycleCheck();
      F.A = true;
      if(F.B)
          return F;
    } else if (W > S && !Blocked[W - 1]) {
      F = circuit(W);
      if(F.B)
          return F;
    }
  }

  if (F.A) {
    unblock(V);
  } else {
    for (int W : AK[V - 1]) {
      auto IT = std::find(B[W - 1].begin(), B[W - 1].end(), V);
      if (IT == B[W - 1].end()) {
        B[W - 1].push_back(V);
      }
    }
  }

  Stack.pop_back();
  return F;
}


bool CircuitFinder::cycleCheck() //here we need to check if there exists any cycle
{ // with <+<=* regex. return 1 if there is a cycle and return 0 if not.
  //cout << "circuit: ";
  int countles=0;
  bool flag = true;
  for (auto I = Stack.begin(), E = Stack.end(); I != E; ++I) {
      //checking of if the cycle have a < along with  other <=
     //cout << *I << " -> ";
//      if(I+1 != E)
//        cout << *I << sarr[relmatrix[*I -1][*(I+1) -1]];
//      else
//          cout << *I << sarr[relmatrix[*I-1][*Stack.begin()-1]] ;
    if(I+1 != E)
      {
          
	if(relmatrix[(*I)-1][(*(I+1))-1] != leq && relmatrix[(*I)-1][(*(I+1))-1] != les)
	  {
          
	    flag = false;
	  }
	else if(relmatrix[(*I)-1][(*(I+1))-1] == les)
	  countles++;
      }
    else
      {
	if(relmatrix[(*I)-1][(*Stack.begin())-1] != leq && relmatrix[(*I)-1][(*Stack.begin())-1] != les)
    {
        
	  flag = false;
    }
	else if (relmatrix[(*I)-1][(*Stack.begin())-1] == les)
	  countles ++;
        
	
      }
    
    
  }
  //cout << *Stack.begin() << std::endl;
  if( countles == 1 && flag == true)
  {// if this true then the circuit is bad
      cout << "Found a Circuit BANG!!" << endl;
      return true;
  }
    else
      return false;
   //cout << *Stack.begin() << std::endl;
}


bool CircuitFinder::run()
{
  Stack.clear();
  S = 1;
  bool2 returnval;
  while (S < N) {
    for (int I = S; I <= N; ++I) {
      Blocked[I - 1] = false;
      B[I - 1].clear();
    }
   returnval= circuit(S);
   if(returnval.B == true)
     return true;
    ++S;
  }
  return false;
}
