}
Sequence seq;
Sequence result;
Item item;
if (contextItem != null)
{contextSequence = contextItem.toSequence();}
if (contextSequence == null || contextSequence.isEmpty())
{result = Sequence.EMPTY_SEQUENCE;}
//If we have one argumment, we take it into account
if (getSignature().getArgumentCount() > 0)
{seq = getArgument(0).eval(contextSequence, contextItem);}
//Otherwise, we take the context sequence and we iterate over it
else
{seq = contextSequence;}
if (seq == null)
{throw new XPathException(this, ErrorCodes.XPDY0002, "Undefined context item");}
if (seq.isPersistentSet())
{result = new ExtArrayNodeSet(seq.getItemCount());}
else
{result = new ValueSequence(seq.getItemCount());}
for (final SequenceIterator i = seq.iterate(); i.hasNext(); ) {
item = i.nextItem();
if (!Type.subTypeOf(item.getType(), Type.NODE))
{throw new XPathException(this, ErrorCodes.XPTY0004, "Item is not a node; got '" + item + "'", seq);}
final Sequence s = item.toSequence();
if (s.isPersistentSet()) {
final NodeProxy p = s.toNodeSet().get(0);
result.add(new NodeProxy(p.getDocument()));
} else {
if (seq.hasOne() && item.getType() == Type.ATTRIBUTE) {
result.add(item);
} else {
result.add(((NodeImpl)item).getDocument());
}
}