////////////////////////////////////////////////////////////////////////////////
// 
// VirtualChiro.cc
//
//    produced: 19 Nov 1999 jr
// 
////////////////////////////////////////////////////////////////////////////////

#include <assert.h>

#include "VirtualChiro.hh"

namespace topcom {

  const int VirtualChiro::operator()(const basis_type&  prebasis,
				     const Permutation& lex_extension_perm) const {
    assert(lex_extension_perm.n() == no());
    assert(lex_extension_perm.k() <= no());
    Permutation basis_perm(no(), rank() - 1, prebasis);
    basis_type basis(prebasis);
    for (size_type i = 0; i < lex_extension_perm.k(); ++i) {
      if (basis.contains(lex_extension_perm[i])) {
	continue;
      }
      basis += lex_extension_perm[i];
      const int basis_sign((*this)(basis));
      if (basis_sign == 0) {
	basis -= lex_extension_perm[i];
	continue;
      }
      basis_perm.push_back(lex_extension_perm[i]);
      int perm_sign = basis_perm.sign();
      return perm_sign * basis_sign;
    }
    return 0;
  }

  const basis_type VirtualChiro::find_non_deg_basis() const {
    if (_pointsptr) {
      return _pointsptr->basis();  
    }
    else if (_complete) {
      return _chiro.find_non_deg_basis();
    }
    else {
      MessageStreams::forced() << message::lock
			       << "VirtualChiro::find_non_deg_basis() const: "
			       << "chirotope incomplete and no points given - exiting." << std::endl
			       << message::unlock;
      exit(1);
    }
  }

  const bool VirtualChiro::_recursive_find_non_deg_basis(const StairCaseMatrix&    current,
							 const basis_type&         basis,
							 const parameter_type      start,
							 const parameter_type      step,
							 basis_type&               result) const {
    for (parameter_type i = start; i < _pointsptr->no() - _pointsptr->rank() + step + 1; ++i) {
      StairCaseMatrix next = current;
      next.augment((*_pointsptr)[i]);
      const basis_type newbasis(basis + i);
      MessageStreams::debug() << message::lock
			      << "partial basis matrix:" << std::endl;
      next.pretty_print(MessageStreams::debug());
      MessageStreams::debug() << message::unlock;
      if (step + 1 == _pointsptr->rank()) {
	if (next.det() != 0) {
	  result = newbasis;
	  return true;
	}
      }
      else {
	if (next.has_no_zerocol()) {
	  MessageStreams::debug() << message::lock
				  << "VirtualChiro::_recursive_find_non_deg_basis: "
				  << "step " << step << std::endl
				  << message::unlock;
	  if (_recursive_find_non_deg_basis(next, newbasis, i + 1, step + 1, result)) {
	    return true;
	  }
	}
      }
    }
    return false;
  }

}; // namespace topcom

// eof VirtualChiro.cc
