private Vector<Tuple> findAllTuples(TupleTemplate t, boolean remove, int expected) {
    Vector<Tuple> allTuples = new Vector<Tuple>();
    Vector<Tuple> matchingTuples = new Vector<Tuple>();

    synchronized (tuples) {
      // for(;;) {
      Collection<Vector<Tuple>> c = tuples.values();

      for (Vector<Tuple> v : c) {
        if (v != null) allTuples.addAll(v);
      }

      /*System.out.println("Template: " + t.toString());
      for(Tuple tpl : allTuples)
          System.out.println(tpl.toString());*/

      for (Tuple tuple : allTuples) {
        if (t.matches(tuple)) {
          matchingTuples.addElement(tuple);

          if (remove) {
            tuples.remove(tuple);
          }
        }

        if (matchingTuples.size() >= expected) {
          tuples.notifyAll();
          /*System.out.println("TupleSpaceImpl - returned vals: "
          + matchingTuples.size()
          + " of " + expected);*/
          return matchingTuples;
        }
      }

      /*if(matchingTuples.size() < expected) {
              if(block) {
                  try {
                      tuples.wait(1000);
                  } catch(InterruptedException ie) {
                      return matchingTuples;
                  }
              } else {
                  return matchingTuples;
              }
          }
      }*/
      /*System.out.println("TupleSpaceImpl - returned vals: "
      + matchingTuples.size()
      + " of " + expected);*/
      return matchingTuples; // remove if above commented code being used
    }
  }
  /*
   * Returns first tuple found which matches given template. Otherwise,
   * returns null.
   */
  private Tuple findTuple(TupleTemplate t, boolean remove, boolean block) {
    // System.out.println("Handling request for template "+t.toString());

    Vector<Tuple> vals = tuples.get(generateKey(t));

    while (vals == null) {
      if (block) {
        synchronized (tuples) {
          try {
            tuples.wait();
          } catch (InterruptedException e) {
            return null;
          }
        }
      } else {
        return null;
      }

      vals = tuples.get(generateKey(t));
    }

    synchronized (vals) {
      Tuple result = null;

      for (; ; ) {
        for (Tuple i : vals) {
          if (t.matches(i)) {
            result = i;

            if (remove) vals.remove(result);

            return result;
          }
        }

        if (block) {
          try {
            vals.wait(1000);
          } catch (InterruptedException e) {
            return null;
          }
        } else {
          return result;
        }
      }
    }
  }