#include "condense.h"
#include "sharing.h"
static const unsigned int condense_MIN_LITERALS_FOR_FILTER = 4;
BOOL condense_Condense(const SCLSTATE State, CLAUSE Clause)
{
  FOLSTATE folstate;
  SUBSTSTATE subststate;
  SYMBSTATE symbstate;
  TERMSTATE termstate;
  BOOL lhs_condensed;
  TERM lhs, rhs;
  unsigned int i, j, n, start, end, condensed;
  if (
    clause_GetConclusionLiterals(Clause) < 2 &&
    clause_GetPremiseLiterals(Clause) < 2
  ) {
    return FALSE;
  }
  subststate = state_GetSubststate(State);
  termstate = state_GetTermstate(State);
  folstate = state_GetFolstate(State);
  symbstate = state_GetSymbstate(State);
  misc_ASSERT(clause_GetVariables(Clause) <= subst_MaxVars(state_GetSubststate(State)));
  n = clause_GetFolLiterals(Clause);
  condensed = 0;
  for (i = 0; i < n; i++) {
    lhs = (TERM) Clause[i];
    lhs_condensed = FALSE;
    Clause[i] = (uintptr_t) NULL;
    clause_RangeFolLiterals(Clause, clause_LiteralIsPositive(Clause, i), &start, &end);
    for (j = start; j < end; j++) {
      if (i == j) {
        continue;
      }
      rhs = (TERM) Clause[j];
      if (rhs == NULL) {
        continue;
      }
      subst_ContextStart(subststate, symbstate);
      lhs_condensed = subst_FolTermMatchTerms(
        subststate,
        symbstate,
        termstate,
        folstate,
        lhs, (TYPING) NULL,
        rhs, (TYPING) NULL
      );
      if (!lhs_condensed) {
        subst_ContextStop(subststate);
        continue;
      }
      subst_ContextStackStart(subststate);
      if (n - condensed >= condense_MIN_LITERALS_FOR_FILTER) {
        lhs_condensed = subsume_ContextFilter(State, Clause, Clause);
        if (!lhs_condensed) {
          subst_ContextStackStop(subststate);
          subst_ContextStop(subststate);
          continue;
        }
      }
      lhs_condensed = subsume_ExistsMatcherFromIndex(State, Clause, Clause, 0);
      subst_ContextStackStop(subststate);
      subst_ContextStop(subststate);
      if (lhs_condensed) {
        condensed++;
        term_Delete(termstate, lhs);
        break;
      }
    }
    if (!lhs_condensed) {
      Clause[i] = (uintptr_t) lhs;
    }
  }
  if (condensed > 0) {
    clause_RemoveNullLiterals(Clause);
    clause_NormalizeVars(subststate, termstate, Clause);
  }
  return condensed;
}
