/* This file is part of cardwords
   (c) 1998 1999 Tobias Peters
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

   */

// cardwords_searchwordmusts.cc

#include "cardwords_searchwordmusts.hh"

void
CardWords_SearchWordMusts::increment (void)
{
  iterator iter = end();
  
  if (iter != begin()) {
    CardWords_SearchWordMust must;
    iterator old;
    bool finished = false;
  
    --iter; // because there is nothing at *end();
    
    do {
      if (iter == begin()) {
        // last time in the loop
        finished = true;
      }
      must = *iter;
      must.first++;
      insert(must); // will be inserted after iter, so --iter will not run
                    // over it again.
      old = iter;
      if (!finished) {
        --iter; // Decrement the iterator while it is valid.
      }
      erase (old);
    } while (!finished);
  }
}

// checks if the word follows the musts:
bool
CardWords_SearchWordMusts::check_word (const CardWords_String & word) const
{
  const_iterator iter;
  size_t         length = word.length();
  
  for (iter = begin(); iter != end(); ++iter) {
    // loop through all musts
    if (iter->first > length) {
      // this must does not apply to this word anymore, it is out of its
      // range, as will be any following musts, because they are sorted
      // in the map. This means, we are done now:
      break;
    }
    assert (iter->first != length); // This would be a bug in the programm,
    // because it should have been avoided to add a word with this length
    // in CardWords_Dictionary::find_possible_words(). A Comment from there:
    // " means we can not have a word of length currentLength (1-based),
    // because there is already a char on the table at position
    // currentLength(0-based)"

    if (iter->second // CardWords_Char of the must
        != word[iter->first] // CardWords_Char at the must position
        //                      in the word
        ) {
      // Found a must that is not followed by the word:
      return false;
    }

    // everything ok here, go check for the next must
  }

  // Every applying must has been checked now. The word is ok.
  return true;
}
