import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;


class main {
public static void main(final String[] args) throws Exception {
  CompactHashSet<Web> set = new CompactHashSet();
  Web web = simpleWeb();
  set.add(web);
  assertSame(web, set.find(dummyWebWithGlobalID(web.globalIDObj())));
  print("OK");
}
static Web simpleWeb() {
  Web web = new Web();
  
    web.useCLParse = false;
  
  return web;
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot

// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
//static int print_maxLineLength = 0; // 0 = unset

static boolean print_silent; // total mute if set

static Object print_byThread_lock = new Object();
static volatile ThreadLocal<Object> print_byThread; // special handling by thread - prefers F1<S, Bool>

static void print() {
  print("");
}

// slightly overblown signature to return original object...
static <A> A print(A o) {
  ping();
  if (print_silent) return o;
  String s = String.valueOf(o) + "\n";
  print_noNewLine(s);
  return o;
}

static void print_noNewLine(String s) {
  if (print_byThread != null) {
    Object f = print_byThread.get();
    if (f != null)
      if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return;
  }

  print_raw(s);
}

static void print_raw(String s) {
  s = fixNewLines(s);
  // TODO if (print_maxLineLength != 0)
  StringBuffer loc = local_log;
  StringBuffer buf = print_log;
  int loc_max = print_log_max;
  if (buf != loc && buf != null) {
    print_append(buf, s, print_log_max);
    loc_max = local_log_max;
  }
  if (loc != null) 
    print_append(loc, s, loc_max);
  System.out.print(s);
}

static void print(long l) {
  print(String.valueOf(l));
}

static void print(char c) {
  print(String.valueOf(c));
}

static void print_append(StringBuffer buf, String s, int max) {
  synchronized(buf) {
    buf.append(s);
    max /= 2;
    if (buf.length() > max) try {
      int newLength = max/2;
      int ofs = buf.length()-newLength;
      String newString = buf.substring(ofs);
      buf.setLength(0);
      buf.append("[...] ").append(newString);
    } catch (Exception e) {
      buf.setLength(0);
    }
  }
}
static RuntimeException asRuntimeException(Throwable t) {
  if (t instanceof Error)
    _handleError((Error) t);
  return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static Web dummyWebWithGlobalID(GlobalID id) {
  Web web = simpleWeb();
  web.globalID = id;
  return web;
}
static Map<Thread, Boolean> _registerThread_threads = newWeakHashMap();

static Thread _registerThread(Thread t) {
  _registerThread_threads.put(t, true);
  return t;
}

static void _registerThread() { _registerThread(Thread.currentThread()); }
static void assertSame(String msg, Object a, Object b) {
  if (a != b)
    throw fail(msg);
}

static void assertSame(Object a, Object b) {
  if (a != b)
    throw fail();
}


static String fixNewLines(String s) {
  return s.replace("\r\n", "\n").replace("\r", "\n");
}
static AtomicLong _handleError_nonVMErrors = new AtomicLong();
static AtomicLong _handleError_vmErrors = new AtomicLong();
static AtomicLong _handleError_outOfMemoryErrors = new AtomicLong();
static volatile long _handleError_lastOutOfMemoryError;
static volatile Error _handleError_lastHardError;

static void _handleError(Error e) {
  if (!(e instanceof VirtualMachineError)) {
    incAtomicLong(_handleError_nonVMErrors);
    return;
  }
  
  print("\nHARD ERROR\n");
  printStackTrace2(e);
  print("\nHARD ERROR\n");
  _handleError_lastHardError = e;
  
  incAtomicLong(_handleError_vmErrors);
  if (e instanceof OutOfMemoryError) {
    incAtomicLong(_handleError_outOfMemoryErrors);
    _handleError_lastOutOfMemoryError = sysNow();
  }
}
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map<Thread, Object> ping_actions = newWeakHashMap();

// always returns true
static boolean ping() {
  if (ping_pauseAll || ping_anyActions) ping_impl();
  return true;
}

// returns true when it slept
static boolean ping_impl() { try {
  if (ping_pauseAll && !isAWTThread()) {
    do
      Thread.sleep(ping_sleep);
    while (ping_pauseAll);
    return true;
  }
  
  if (ping_anyActions) {
    Object action;
    synchronized(ping_actions) {
      action = ping_actions.get(currentThread());
      if (action instanceof Runnable)
        ping_actions.remove(currentThread());
      if (ping_actions.isEmpty()) ping_anyActions = false;
    }
    
    if (action instanceof Runnable)
      ((Runnable) action).run();
    else if (eq(action, "cancelled"))
      throw fail("Thread cancelled.");
  }
  
  return false;
} catch (Exception __e) { throw rethrow(__e); } }
static WeakHashMap<Class, ArrayList<Method>> callF_cache = new WeakHashMap();




  static <A, B> B callF(F1<A, B> f, A a) {
    return f == null ? null : f.get(a);
  }


static Object callF(Object f, Object... args) { try {
  if (f instanceof String)
    return callMC((String) f, args);
  if (f instanceof Runnable) {
    ((Runnable) f).run();
    return null;
  }
  if (f == null) return null;
  
  Class c = f.getClass();
  ArrayList<Method> methods;
  synchronized(callF_cache) {
    methods = callF_cache.get(c);
    if (methods == null)
      methods = callF_makeCache(c);
  }
  
  int n = l(methods);
  if (n == 0) throw fail("No get method in " + getClassName(c));
  if (n == 1) return methods.get(0).invoke(f, args);
  for (int i = 0; i < n; i++) {
    Method m = methods.get(i);
    if (call_checkArgs(m, args, false))
      return m.invoke(f, args);
  }
  throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }

// used internally
static ArrayList<Method> callF_makeCache(Class c) {
  ArrayList<Method> l = new ArrayList();
  Class _c = c;
  do {
    for (Method m : _c.getDeclaredMethods())
      if (m.getName().equals("get")) {
        m.setAccessible(true);
        l.add(m);
      }
    if (!l.isEmpty()) break;
    _c = _c.getSuperclass();
  } while (_c != null);
  callF_cache.put(c, l);
  return l;
}
static boolean isFalse(Object o) {
  return eq(false, o);
}
static <A, B> Map<A, B> newWeakHashMap() {
  return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }



static Map synchroMap() {
  return synchroHashMap();
}

static <A, B> Map<A, B> synchroMap(Map<A, B> map) {
  return Collections.synchronizedMap(map);
}
static HashMap<String, List<Method>> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;

// varargs assignment fixer for a single string array argument
static Object callMC(String method, String[] arg) {
  return callMC(method, new Object[] {arg});
}

static Object callMC(String method, Object... args) { try {
  Method me;
  if (callMC_cache == null) callMC_cache = new HashMap(); // initializer time workaround
  synchronized(callMC_cache) {
    me = method == callMC_key ? callMC_value : null;
  }
  if (me != null) try {
    return me.invoke(null, args);
  } catch (IllegalArgumentException e) {
    throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
  }

  List<Method> m;
  synchronized(callMC_cache) {
    m = callMC_cache.get(method);
  }
  if (m == null) {
    if (callMC_cache.isEmpty()) {
      callMC_makeCache();
      m = callMC_cache.get(method);
    }
    if (m == null) throw fail("Method named " + method + " not found in main");
  }
  int n = m.size();
  if (n == 1) {
    me = m.get(0);
    synchronized(callMC_cache) {
      callMC_key = method;
      callMC_value = me;
    }
    try {
      return me.invoke(null, args);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
    }
  }
  for (int i = 0; i < n; i++) {
    me = m.get(i);
    if (call_checkArgs(me, args, false))
      return me.invoke(null, args);
  }
  throw fail("No method called " + method + " with matching arguments found in main");
} catch (Exception __e) { throw rethrow(__e); } }

static void callMC_makeCache() {
  synchronized(callMC_cache) {
    callMC_cache.clear();
    Class _c = (Class) mc(), c = _c;
    while (c != null) {
      for (Method m : c.getDeclaredMethods())
        if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
          m.setAccessible(true);
          multiMapPut(callMC_cache, m.getName(), m);
        }
      c = c.getSuperclass();
    }
  }
}
static long sysNow() {
  return System.nanoTime()/1000000;
}
static void incAtomicLong(AtomicLong l) {
  l.incrementAndGet();
}
// TODO: test if android complains about this
static boolean isAWTThread() {
  if (isAndroid()) return false;
  if (isHeadless()) return false;
  return isAWTThread_awt();
}

static boolean isAWTThread_awt() {
  return SwingUtilities.isEventDispatchThread();
}
static RuntimeException rethrow(Throwable e) {
  throw asRuntimeException(e);
}
static Thread currentThread() {
  return Thread.currentThread();
}
static boolean eq(Object a, Object b) {
  return a == null ? b == null : a == b || a.equals(b);
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } static long l(File f) { return f == null ? 0 : f.length(); }

static int l(Object o) {
  return o instanceof String ? l((String) o)
    : o instanceof Map ? l((Map) o)
    : l((Collection) o); // incomplete
}




  static int l(Lisp l) { return l == null ? 0 : l.size(); }

static Object call(Object o) {
  return callFunction(o);
}

// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
  return call(o, method, new Object[] {arg});
}

static Object call(Object o, String method, Object... args) {
  try {
    if (o instanceof Class) {
      Method m = call_findStaticMethod((Class) o, method, args, false);
      m.setAccessible(true);
      return m.invoke(null, args);
    } else {
      Method m = call_findMethod(o, method, args, false);
      m.setAccessible(true);
      return m.invoke(o, args);
    }
  } catch (Exception e) {
    throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
  }
}

static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
  Class _c = c;
  while (c != null) {
    for (Method m : c.getDeclaredMethods()) {
      if (debug)
        System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
      if (!m.getName().equals(method)) {
        if (debug) System.out.println("Method name mismatch: " + method);
        continue;
      }

      if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug))
        continue;

      return m;
    }
    c = c.getSuperclass();
  }
  throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName());
}

static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
  Class c = o.getClass();
  while (c != null) {
    for (Method m : c.getDeclaredMethods()) {
      if (debug)
        System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
      if (m.getName().equals(method) && call_checkArgs(m, args, debug))
        return m;
    }
    c = c.getSuperclass();
  }
  throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
}

private static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
  Class<?>[] types = m.getParameterTypes();
  if (types.length != args.length) {
    if (debug)
      System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
    return false;
  }
  for (int i = 0; i < types.length; i++)
    if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
      if (debug)
        System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
      return false;
    }
  return true;
}
static Throwable printStackTrace2(Throwable e) {
  // we go to system.out now - system.err is nonsense
  print(getStackTrace2(e));
  return e;
}

static void printStackTrace2() {
  printStackTrace2(new Throwable());
}

static void printStackTrace2(String msg) {
  printStackTrace2(new Throwable(msg));
}

/*static void printStackTrace2(S indent, Throwable e) {
  if (endsWithLetter(indent)) indent += " ";
  printIndent(indent, getStackTrace2(e));
}*/
static List _registerWeakMap_preList;

static <A> A _registerWeakMap(A map) {
  if (javax() == null) {
    // We're in class init
    if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList();
    _registerWeakMap_preList.add(map);
    return map;
  }
  
  try {
    call(javax(), "_registerWeakMap", map);
  } catch (Throwable e) {
    printException(e);
    print("Upgrade JavaX!!");
  }
  return map;
}

static void _onLoad_registerWeakMap() {
  assertNotNull(javax());
  if (_registerWeakMap_preList == null) return;
  for (Object o : _registerWeakMap_preList)
    _registerWeakMap(o);
  _registerWeakMap_preList = null;
}
static String getClassName(Object o) {
  return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}


static Boolean isHeadless_cache;

static boolean isHeadless() {
  if (isHeadless_cache != null) return isHeadless_cache;
  if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
  
  // Also check if AWT actually works.
  // If DISPLAY variable is set but no X server up, this will notice.
  
  try {
    SwingUtilities.isEventDispatchThread();
    return isHeadless_cache = false;
  } catch (Throwable e) { return isHeadless_cache = true; }
}
static Object callFunction(Object f, Object... args) {
  return callF(f, args);
}
static List<String> classNames(Collection l) {
  return getClassNames(l);
}

static List<String> classNames(Object[] l) {
  return getClassNames(Arrays.asList(l));
}
static Class javax() {
  return getJavaX();
}
static Class mc() {
  return main.class;
}
static <A> A assertNotNull(A a) {
  assertTrue(a != null);
  return a;
}

static <A> A assertNotNull(String msg, A a) {
  assertTrue(msg, a != null);
  return a;
}
static <A> List<A> synchroList() {
  return Collections.synchronizedList(new ArrayList<A>());
}

static <A> List<A> synchroList(List<A> l) {
  return Collections.synchronizedList(l);
}

static <A, B> void multiMapPut(Map<A, List<B>> map, A a, B b) {
  List<B> l = map.get(a);
  if (l == null)
    map.put(a, l = new ArrayList());
  l.add(b);
}
static String getStackTrace2(Throwable throwable) {
  return hideCredentials(getStackTrace(throwable) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
    hideCredentials(str(getInnerException(throwable)))) + "\n");
}
// extended over Class.isInstance() to handle primitive types
static boolean isInstanceX(Class type, Object arg) {
  if (type == boolean.class) return arg instanceof Boolean;
  if (type == int.class) return arg instanceof Integer;
  if (type == long.class) return arg instanceof Long;
  if (type == float.class) return arg instanceof Float;
  if (type == short.class) return arg instanceof Short;
  if (type == char.class) return arg instanceof Character;
  if (type == byte.class) return arg instanceof Byte;
  if (type == double.class) return arg instanceof Double;
  return type.isInstance(arg);
}
static void printException(Throwable e) {
  printStackTrace(e);
}
static Map synchroHashMap() {
  return Collections.synchronizedMap(new HashMap());
}

static int isAndroid_flag;

static boolean isAndroid() {
  if (isAndroid_flag == 0)
    isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
  return isAndroid_flag > 0;
}



static String getStackTrace(Throwable throwable) {
  lastException(throwable);
  StringWriter writer = new StringWriter();
  throwable.printStackTrace(new PrintWriter(writer));
  return hideCredentials(writer.toString());
}
static Throwable printStackTrace(Throwable e) {
  // we go to system.out now - system.err is nonsense
  print(getStackTrace(e));
  return e;
}

static void printStackTrace() {
  printStackTrace(new Throwable());
}

static void printStackTrace(String msg) {
  printStackTrace(new Throwable(msg));
}

/*static void printStackTrace(S indent, Throwable e) {
  if (endsWithLetter(indent)) indent += " ";
  printIndent(indent, getStackTrace(e));
}*/
static String replacePrefix(String prefix, String replacement, String s) {
  if (!startsWith(s, prefix)) return s;
  return replacement + substring(s, l(prefix));
}
static String str(Object o) {
  return o == null ? "null" : o.toString();
}

static String str(char[] c) {
  return new String(c);
}
static void assertTrue(Object o) {
  if (!(eq(o, true) || isTrue(pcallF(o))))
    throw fail(str(o));
}
  
static boolean assertTrue(String msg, boolean b) {
  if (!b)
    throw fail(msg);
  return b;
}

static boolean assertTrue(boolean b) {
  if (!b)
    throw fail("oops");
  return b;
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }

static String hideCredentials(String url) {
  return url.replaceAll("([&?])_pass=[^&\\s\"]*", "$1_pass=<hidden>");
}
static List<String> getClassNames(Collection l) {
  List<String> out = new ArrayList();
  if (l != null) for (Object o : l)
    out.add(o == null ? null : getClassName(o));
  return out;
}
static Class __javax;

static Class getJavaX() {
  return __javax;
}
static Throwable getInnerException(Throwable e) {
  while (e.getCause() != null)
    e = e.getCause();
  return e;
}


static volatile Throwable lastException_lastException;

static Throwable lastException() {
  return lastException_lastException;
}

static void lastException(Throwable e) {
  lastException_lastException = e;
}
static Object pcallF(Object f, Object... args) {
  return pcallFunction(f, args);
}


static <A, B> B pcallF(F1<A, B> f, A a) { try {
  return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }

static String substring(String s, int x) {
  return substring(s, x, l(s));
}

static String substring(String s, int x, int y) {
  if (s == null) return null;
  if (x < 0) x = 0;
  if (x > s.length()) return "";
  if (y < x) y = x;
  if (y > s.length()) y = s.length();
  return s.substring(x, y);
}


static boolean isTrue(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  if (o == null) return false;
  if (o instanceof ThreadLocal)
    return isTrue(((ThreadLocal) o).get());
  throw fail(getClassName(o));
}
static boolean startsWith(String a, String b) {
  return a != null && a.startsWith(b);
}

static boolean startsWith(String a, char c) {
  return nempty(a) && a.charAt(0) == c;
}



static boolean startsWith(List a, List b) {
  if (a == null || l(b) > l(a)) return false;
  for (int i = 0; i < l(b); i++)
    if (neq(a.get(i), b.get(i)))
      return false;
  return true;
}




static boolean neq(Object a, Object b) {
  return !eq(a, b);
}
static boolean nempty(Collection c) {
  return !isEmpty(c);
}

static boolean nempty(CharSequence s) {
  return !isEmpty(s);
}

static boolean nempty(Object[] o) {
  return !isEmpty(o);
}

static boolean nempty(Map m) {
  return !isEmpty(m);
}

static boolean nempty(Iterator i) {
  return i != null && i.hasNext();
}
static Object pcallFunction(Object f, Object... args) {
  try { return callFunction(f, args); } catch (Throwable __e) { printStackTrace2(__e); }
  return null;
}


static boolean isEmpty(Collection c) {
  return c == null || c.isEmpty();
}

static boolean isEmpty(CharSequence s) {
  return s == null || s.length() == 0;
}

static boolean isEmpty(Object[] a) {
  return a == null || a.length == 0;
}

static boolean isEmpty(Map map) {
  return map == null || map.isEmpty();
}


static class WebRelation extends WebNode {
  WebNode a, b;
  
  public void _setField(String f, Object x) {
    if (f.equals("a")) a = (WebNode) x;
    else if (f.equals("b")) b = (WebNode) x;
    else super._setField(f, x);
  }
  
  WebRelation() {}
  WebRelation(Web web, WebNode a, WebNode b) { super(web); this.a = a; this.b = b; }
}

static class Web {
  List<WebNode> nodes = new ArrayList(); // Relations are also nodes
  
  
  
  static final MultiMap<Lisp, WebNode> index = null;
  
  //Map<S, L<WebNode>> pots = new Map;
  
  //int size;
  //int flags; // TODO
  boolean useCLParse = true;
  boolean labelsToUpper;
  String title;
  Object globalID = aGlobalID();
  String source;
  boolean unverified;
  long created = nowUnlessLoading();
  
  static List onNewNode = new ArrayList(); // L<voidfunc(WebNode)>
  static List onNewLabel = new ArrayList(); // L<voidfunc(WebNode, Lisp)>
  
  static int F_useCLParse = 1;
  static int F_labelsToupper = 2;
  static int F_unverified = 3;
  
  /*bool potNotEmpty(S pot) { ret nempty(getPot(pot)); }
  
  L<WebNode> clearPot(S pot) {
    L<WebNode> l = getPot(pot);
    L<WebNode> l2 = cloneList(l);
    l.clear();
    ret l2;
  }*/
  
  /*L<WebNode> getPot(S pot) {
    L<WebNode> l = pots.get(pot);
    if (l == null)
      pots.put(pot, l = cloneList(nodes));
    ret l;
  }*/
  
  void relation(WebNode a, String arrow, WebNode b) {
    getRelation(a, b).addLabel(arrow);
  }
  
  Pair<WebNode, WebNode> relation(String a, String arrow, String b) {
    return relation(lisp(arrow, a, b));
  }
  
  Pair<WebNode, WebNode> relation(Lisp l) {
    if (l(l) == 1) {
      findNode(l.get(0)).addLabel(lisp("wvuyakuvuelmxpwp", l.head));
      return null;
    } else if (l(l) == 2) {
      String a = lisp2label(l.get(0)), b = lisp2label(l.get(1));
      if (l.is("fgvvrzypbkqomktd")) { // X is Y.
        findNode(a).addLabel(b);
        findNode(b).addLabel(a);
      }
      WebNode na = findNode(a), nb = findNode(b);
      getRelation(na, nb).addLabel(l.head);
      return pair(na, nb);
    }
    return null;
  }
  
  void relations(List<Lisp> l) {
    for (Lisp li : l) relation(li);
  }
  
  WebRelation getRelation(String a, String b) {
    return getRelation(findNode(a), findNode(b));
  }
  
  WebRelation getRelation(WebNode a, WebNode b) {
    return getRelation(pair(a, b));
  }
  
  WebRelation relation(WebNode a, WebNode b) { return getRelation(a, b); }
  WebRelation relation(Pair<WebNode, WebNode> p) { return getRelation(p); }
  
  WebRelation getRelationOpt(Pair<WebNode, WebNode> p) {
    return getRelationOpt(p.a, p.b);
  }
  
  WebRelation getRelationOpt(WebNode a, WebNode b) {
    
    for (WebNode n : nodes)
      if (n instanceof WebRelation) {
        WebRelation r = ((WebRelation) n);
        if (r.a == a && r.b == b)
          return r;
      }
    return null;
  }
  
  WebRelation getRelation(Pair<WebNode, WebNode> p) {
    WebRelation r = getRelationOpt(p.a, p.b);
    if (r == null) {
      r = _newRelation(p.a, p.b);
      
    }
    return r;
  }
  
  WebRelation _newRelation(WebNode a, WebNode b) {
    WebRelation r = new WebRelation(this, a, b);
    nodes.add(r);
    //for (L<WebNode> l : values(pots)) l.add(r);
    return r;
  }
  
  WebNode newNode() {
    WebNode node = new WebNode(this);
    nodes.add(node);
    //for (L<WebNode> l : values(pots)) l.add(node);
    return node;
  }
  
  WebNode newNode(String s) {
    WebNode node = newNode();
    node.addLabel(parseLabel(s));
    return node;
  }
  
  WebNode node(String s) { return findNode(s); }
  WebNode node(Lisp l) { return findNode(l); }

  WebNode findNode(String s) {
    return findNode(parseLabel(s));
  }
  
  WebNode findNode(Lisp l) {
    WebNode n = findNodeOpt(l);
    return n != null ? n : newNode(l);
  }
  
  WebNode findNodeOpt(Lisp l) {
    if (index != null) return first(index.get(l));
    for (WebNode n : nodes) if (n.hasLabel(l)) return n;
    return null;
  }
  
  WebNode newNode(String... labels) {
    WebNode n = newNode();
    for (String label : labels) n.addLabel(label);
    return n;
  }
  
  WebNode newNode(Lisp... labels) {
    WebNode n = newNode();
    for (Lisp label : labels) n.addLabel(label);
    return n;
  }
  
  public String toString() { return webToString(this); }
  
  void index(Lisp label, WebNode n) {
    if (index != null) index.put(label, n);
    fireNewLabel(n, label);
  }
  
  void clear() {
    clearAll(nodes, index/*, pots*/);
    
  }
  
  Lisp parseLabel(String s) {
    
      if (useCLParse) return clParse(s);
    
    return lisp(labelsToUpper ? upper(s) : s);
  }
  
  String unparseLabel(Lisp l) {
    
      if (useCLParse) return clUnparse(l);
    
    return lispHead(l);
  }
  
  List<Lisp> parseLabels(List<String> l) {
    List<Lisp> x = new ArrayList(l(l));
    for (String s : l) x.add(parseLabel(s));
    return x;
  }
  
  List<String> unparseLabels(List<Lisp> l) {
    List<String> x = new ArrayList(l(l));
    for (Lisp lbl : l) x.add(unparseLabel(lbl));
    return x;
  }
  
  void fireNewNode(WebNode node) { for (Object f : onNewNode) pcallF(f, node); }
  void fireNewLabel(WebNode node, Lisp label) { for (Object f : onNewLabel) pcallF(f, node, label); }
  
  void removeNode(WebNode n) {
    if (n == null || !nodes.contains(n)) return;
    
    n.web = null;
    
    
    
    if (index != null) for (Lisp label : n.labels())
      index.remove(label, n);
    nodes.remove(n);

    
  }
  
  void removeRelation(WebNode a, WebNode b) {
    Pair<WebNode, WebNode> p = pair(a, b);
    WebNode r = getRelationOpt(p);
    if (r == null) return;
    
    removeNode(r);
  }
  
  boolean verified() { return !unverified; }
  
  String globalID() { return strOrNull(globalID); }
  GlobalID globalIDObj() {
    return globalID instanceof String
      ? new GlobalID((String) globalID)
      : (GlobalID) globalID;
  }
  
  public int hashCode() { return globalIDObj().hashCode(); }
  public boolean equals(Object o) {
    return o instanceof Web && eq(globalIDObj(), ((Web) o).globalIDObj());
  }
}static abstract class F1<A, B> {
  abstract B get(A a);
}// Copyright (C) 2001 - 2013 The Ontopia Project
// Implements the Set interface more compactly than
// java.util.HashSet by using a closed hashtable. 

static class CompactHashSet<A> extends java.util.AbstractSet<A> {
  protected final static int INITIAL_SIZE = 3;
  protected final static double LOAD_FACTOR = 0.75;

  protected final static Object nullObject = new Object();
  protected final static Object deletedObject = new Object();
  protected int elements;
  protected int freecells;
  protected A[] objects;
  protected int modCount;
  
  CompactHashSet() {
    this(INITIAL_SIZE);
  }

  CompactHashSet(int size) {
    // NOTE: If array size is 0, we get a
    // "java.lang.ArithmeticException: / by zero" in add(Object).
    objects = (A[]) new Object[(size==0 ? 1 : size)];
    elements = 0;
    freecells = objects.length;
    modCount = 0;
  }

  CompactHashSet(Collection<A> c) {
    this(c.size());
    addAll(c);
  }

  @Override
  public Iterator<A> iterator() {
    return new CompactHashIterator<A>();
  }

  @Override
  public int size() {
    return elements;
  }

  @Override
  public boolean isEmpty() {
    return elements == 0;
  }

  @Override
  public boolean contains(Object o) {
    return find(o) != null;
  }
  
  synchronized A find(Object o) {
    if (o == null) o = nullObject;
    
    int hash = o.hashCode();
    int index = (hash & 0x7FFFFFFF) % objects.length;
    int offset = 1;

    // search for the object (continue while !null and !this object)
    while(objects[index] != null &&
          !(objects[index].hashCode() == hash &&
            objects[index].equals(o))) {
      index = ((index + offset) & 0x7FFFFFFF) % objects.length;
      offset = offset*2 + 1;

      if (offset == -1)
        offset = 2;
    }

    return objects[index];
  }

  @Override
  synchronized public boolean add(Object o) {
    if (o == null) o = nullObject;

    int hash = o.hashCode();
    int index = (hash & 0x7FFFFFFF) % objects.length;
    int offset = 1;
    int deletedix = -1;
    
    // search for the object (continue while !null and !this object)
    while(objects[index] != null &&
          !(objects[index].hashCode() == hash &&
            objects[index].equals(o))) {

      // if there's a deleted object here we can put this object here,
      // provided it's not in here somewhere else already
      if (objects[index] == deletedObject)
        deletedix = index;
      
      index = ((index + offset) & 0x7FFFFFFF) % objects.length;
      offset = offset*2 + 1;

      if (offset == -1)
        offset = 2;
    }
    
    if (objects[index] == null) { // wasn't present already
      if (deletedix != -1) // reusing a deleted cell
        index = deletedix;
      else
        freecells--;

      modCount++;
      elements++;

      // here we face a problem regarding generics:
      // add(A o) is not possible because of the null Object. We cant do 'new A()' or '(A) new Object()'
      // so adding an empty object is a problem here
      // If (! o instanceof A) : This will cause a class cast exception
      // If (o instanceof A) : This will work fine

      objects[index] = (A) o;
      
      // do we need to rehash?
      if (1 - (freecells / (double) objects.length) > LOAD_FACTOR)
        rehash();
      return true;
    } else // was there already 
      return false;
  }
  
  @Override
  synchronized public boolean remove(Object o) {
    if (o == null) o = nullObject;
    
    int hash = o.hashCode();
    int index = (hash & 0x7FFFFFFF) % objects.length;
    int offset = 1;
    
    // search for the object (continue while !null and !this object)
    while(objects[index] != null &&
          !(objects[index].hashCode() == hash &&
            objects[index].equals(o))) {
      index = ((index + offset) & 0x7FFFFFFF) % objects.length;
      offset = offset*2 + 1;

      if (offset == -1)
        offset = 2;
    }

    // we found the right position, now do the removal
    if (objects[index] != null) {
      // we found the object

      // same problem here as with add
      objects[index] = (A) deletedObject;
      modCount++;
      elements--;
      return true;
    } else
      // we did not find the object
      return false;
  }
  
  @Override
  synchronized public void clear() {
    elements = 0;
    for (int ix = 0; ix < objects.length; ix++)
      objects[ix] = null;
    freecells = objects.length;
    modCount++;
  }

  @Override
  synchronized public Object[] toArray() {
    Object[] result = new Object[elements];
    Object[] objects = this.objects;
    int pos = 0;
    for (int i = 0; i < objects.length; i++)
      if (objects[i] != null && objects[i] != deletedObject) {
        if (objects[i] == nullObject)
          result[pos++] = null;
        else
          result[pos++] = objects[i];
      }
    // unchecked because it should only contain A
    return result;
  }

  // not sure if this needs to have generics
  @Override
  synchronized public <T> T[] toArray(T[] a) {
    int size = elements;
    if (a.length < size)
      a = (T[])java.lang.reflect.Array.newInstance(
                                 a.getClass().getComponentType(), size);
    A[] objects = this.objects;
    int pos = 0;
    for (int i = 0; i < objects.length; i++)
      if (objects[i] != null && objects[i] != deletedObject) {
        if (objects[i] == nullObject)
          a[pos++] = null;
        else
          a[pos++] = (T) objects[i];
      }
    return a;
  }
  
  protected void rehash() {
    int gargagecells = objects.length - (elements + freecells);
    if (gargagecells / (double) objects.length > 0.05)
      // rehash with same size
      rehash(objects.length);
    else
      // rehash with increased capacity
      rehash(objects.length*2 + 1);
  }
  
  protected void rehash(int newCapacity) {
    int oldCapacity = objects.length;
    @SuppressWarnings("unchecked")
    A[] newObjects = (A[]) new Object[newCapacity];

    for (int ix = 0; ix < oldCapacity; ix++) {
      Object o = objects[ix];
      if (o == null || o == deletedObject)
        continue;
      
      int hash = o.hashCode();
      int index = (hash & 0x7FFFFFFF) % newCapacity;
      int offset = 1;

      // search for the object
      while(newObjects[index] != null) { // no need to test for duplicates
        index = ((index + offset) & 0x7FFFFFFF) % newCapacity;
        offset = offset*2 + 1;

        if (offset == -1)
          offset = 2;
      }

      newObjects[index] = (A) o;
    }

    objects = newObjects;
    freecells = objects.length - elements;
  }
  
  private class CompactHashIterator<T> implements Iterator<T> {
    private int index;
    private int lastReturned = -1;

    private int expectedModCount;

    @SuppressWarnings("empty-statement")
    public CompactHashIterator() {
      synchronized(CompactHashSet.this) {
        for (index = 0; index < objects.length &&
                        (objects[index] == null ||
                        objects[index] == deletedObject); index++)
          ;
        expectedModCount = modCount;
      }
    }

    @Override
    public boolean hasNext() {
      synchronized(CompactHashSet.this) {
        return index < objects.length;
      }
    }

    @SuppressWarnings("empty-statement")
    @Override
    public T next() {
      synchronized(CompactHashSet.this) {
        if (modCount != expectedModCount)
          throw new ConcurrentModificationException();
        int length = objects.length;
        if (index >= length) {
          lastReturned = -2;
          throw new NoSuchElementException();
        }
  
        lastReturned = index;
        for (index += 1; index < length &&
                         (objects[index] == null ||
                          objects[index] == deletedObject); index++)
          ;
        if (objects[lastReturned] == nullObject)
          return null;
        else
          return (T) objects[lastReturned];
      }
    }

    @Override
    public void remove() {
      synchronized(CompactHashSet.this) {
        if (modCount != expectedModCount)
          throw new ConcurrentModificationException();
        if (lastReturned == -1 || lastReturned == -2)
          throw new IllegalStateException();
        // delete object
        if (objects[lastReturned] != null && objects[lastReturned] != deletedObject) {
          objects[lastReturned] = (A) deletedObject;
          elements--;
          modCount++;
          expectedModCount = modCount; // this is expected; we made the change
        }
      }
    }
  }
}static class GlobalID {
  // We need 76 bits for 26^16 IDs
  long a;
  int b;
  
  GlobalID() {}
  GlobalID(String id) {
    assertGlobalID(id);
    BigInteger value = bigint(0);
    for (int i = 0; i < l(id); i++)
      value = plus(mul(value, 26), charDiff(id.charAt(i), 'a'));
      
    
    a = value.longValue();
    value = value.shiftRight(64);
    b = value.intValue();
  }
  
  public String toString() {
    BigInteger value = bigint(b);
    value = value.shiftLeft(32);
    value = plus(value, (a >> 32) & 0xFFFFFFFFL);
    value = value.shiftLeft(32);
    value = plus(value, a & 0xFFFFFFFFL);
    
    
    
    char[] buf = new char[16];
    for (int i = 16-1; i >= 0; i--) {
      buf[i] = charPlus('a', mod(value, 26).intValue());
      value = div(value, 26);
    }
    return str(buf);
  }
  
  public boolean equals(Object o) {
    if (!(o instanceof GlobalID)) return false;
    return ((GlobalID) o).a == a && ((GlobalID) o).b == b;
  }
  
  public int hashCode() {
    return (int) a;
  }
}

static class MultiMap<A,B> {
  Map<A, List<B>> data = new HashMap<A, List<B>>();
  
  MultiMap() {}
  MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); }
  MultiMap(MultiMap<A, B> map) { putAll(map); }

  void put(A key, B value) { synchronized(data) {
    List<B> list = data.get(key);
    if (list == null)
      data.put(key, list = _makeEmptyList());
    list.add(value);
  }}

  void addAll(A key, Collection<B> values) { synchronized(data) {
    putAll(key, values);
  }}
  
  void addAllIfNotThere(A key, Collection<B> values) { synchronized(data) {
    for (B value : values)
      setPut(key, value);
  }}
  
  void setPut(A key, B value) { synchronized(data) {
    if (!containsPair(key, value))
      put(key, value);
  }}
  
  boolean containsPair(A key, B value) { synchronized(data) {
    return get(key).contains(value);
  }}
  
  void putAll(A key, Collection<B> values) { synchronized(data) {
    for (B value : values)
      put(key, value);
  }}

  void removeAll(A key, Collection<B> values) { synchronized(data) {
    for (B value : values)
      remove(key, value);
  }}
  
  List<B> get(A key) { synchronized(data) {
    List<B> list = data.get(key);
    return list == null ? Collections.<B> emptyList() : list;
  }}

  // returns actual mutable live list
  // creates the list if not there
  List<B> getActual(A key) { synchronized(data) {
    List<B> list = data.get(key);
    if (list == null)
      data.put(key, list = _makeEmptyList());
    return list;
  }}
 
  void clean(A key) { synchronized(data) {
    List<B> list = data.get(key);
    if (list != null && list.isEmpty())
      data.remove(key);
  }}

  Set<A> keySet() { synchronized(data) {
    return data.keySet();
  }}

  Set<A> keys() { synchronized(data) {
    return data.keySet();
  }}

  void remove(A key) { synchronized(data) {
    data.remove(key);
  }}

  void remove(A key, B value) { synchronized(data) {
    List<B> list = data.get(key);
    if (list != null) {
      list.remove(value);
      if (list.isEmpty())
        data.remove(key);
    }
  }}

  void clear() { synchronized(data) {
    data.clear();
  }}

  boolean containsKey(A key) { synchronized(data) {
    return data.containsKey(key);
  }}

  B getFirst(A key) { synchronized(data) {
    List<B> list = get(key);
    return list.isEmpty() ? null : list.get(0);
  }}
  
  void putAll(MultiMap<A, B> map) { synchronized(data) {
    for (A key : map.keySet())
      putAll(key, map.get(key));
  }}
  
  int keysSize() { synchronized(data) { return l(data); }}
  
  // full size - note: expensive operation
  int size() { synchronized(data) {
    int n = 0;
    for (List l : data.values())
      n += l(l);
    return n;
  }}
  
  // expensive operation
  List<A> reverseGet(B b) { synchronized(data) {
    List<A> l = new ArrayList();
    for (A key : data.keySet())
      if (data.get(key).contains(b))
        l.add(key);
    return l;
  }}
  
  Map<A, List<B>> asMap() { synchronized(data) {
    return cloneMap(data);
  }}
  
  boolean isEmpty() { synchronized(data) { return data.isEmpty(); }}
  
  List<B> _makeEmptyList() {
    return new ArrayList();
  }
}static class WebNode implements _SetField {
  Web web;
  List<Lisp> labels = new ArrayList();
  Object visInfo; // visualisation info
  
  public void _setField(String f, Object x) {
    if (f.equals("web")) web = (Web) x;
    else if (f.equals("labels")) labels = (List) x;
    else if (f.equals("visInfo")) visInfo = x;
  }
  
  WebNode() {}
  WebNode(Web web) {
  this.web = web; web.fireNewNode(this); }
  
  void addLabel(String label) { addLabel(web.parseLabel(label)); }
  
  void addLabel(Lisp label) {
    if (setAdd(labels, label) && web != null)
      web.index(label, this);
  }
  
  void addLabels(Collection<Lisp> l) { for (Lisp lbl : l) addLabel(lbl); }
  void addStrings(Collection<String> l) { for (String lbl : l) addLabel(lbl); }
  
  boolean hasLabel(Lisp label) { return labels.contains(label); }
  boolean hasLabel(String label) { return labels.contains(web.parseLabel(label)); }
  
  public String toString() { return l(labels) == 1 ? str(first(labels)) : str(labels); }
  
  int count() { return 1 + l(labels); }
  String text() { return web.unparseLabel(first(labels)); }
  List<String> texts() { return web.unparseLabels(labels); }
  
  void relation(String arrow, String b) {
    web.getRelation(this, web.node(b)).addLabel(arrow);
  }
  
  Lisp parseLabel(String l) { return web.parseLabel(l); }
  String unparseLabel(Lisp l) { return web.unparseLabel(l); }
  
  List<Lisp> labels() { return labels; }
  boolean hasLabels() { return nempty(labels); }
  void setLabel(int i, Lisp l) { labels.set(i, l); }
  
  Object visInfo() { return visInfo; }
  void visInfo(Object o) { visInfo = o; }
}

// a Lisp-like form
static class Lisp implements Iterable<Lisp> {
  String head;
  List<Lisp> args;
  
  // O more; // additional info, user-defined
  
  Lisp() {}
  Lisp(String head) { this.head = _compactString(head); }
  Lisp(String head, Lisp... args) {
  this.head = head;
    argsForEdit().addAll(asList(args));
  }
  Lisp(String head, Collection args) {
    this.head = _compactString(head);
    for (Object arg : args) add(arg);
  }
  
  List<Lisp> argsForEdit() {
    return args == null ? (args = new ArrayList()) : args;
  }
  
  // INEFFICIENT
  public String toString() {
    if (empty())
      return quoteIfNotIdentifierOrInteger(head);
    List<String> bla = new ArrayList();
    for (Lisp a : args)
      bla.add(a.toString());
    String inner = join(", ", bla);
    if (head.equals(""))
      return "{" + inner + "}"; // list
    else
      return quoteIfNotIdentifier(head) + "(" + inner + ")";
  }

  String raw() {
    if (!isEmpty ()) throw fail("not raw: " + this);
    return head;
  }
  
  Lisp add(Lisp l) {
    argsForEdit().add(l);
    return this;
  }
  
  Lisp add(String s) {
    argsForEdit().add(new Lisp(s));
    return this;
  }
  
  Lisp add(Object o) {
    if (o instanceof Lisp) add((Lisp) o);
    else if (o instanceof String) add((String) o);
    else throw fail("Bad argument type: " + structure(o));
    return this;
  }
  
  int size() {
    return l(args);
  }
  
  boolean empty() { return main.empty(args); }
  boolean isEmpty() { return main.empty(args); }
  boolean isLeaf() { return main.empty(args); }
  
  Lisp get(int i) {
    return main.get(args, i);
  }
  
  String getString(int i) { Lisp a = get(i); return a == null ? null : a.head; }
  
  String s(int i) { return getString(i); }
  String rawOrNull(int i) {
    Lisp a = get(i); return a != null && a.isLeaf() ? a.head : null;
  }
  String raw(int i) { return assertNotNull(rawOrNull(i)); }
  boolean isLeaf(int i) { return rawOrNull(i) != null; }
  
  boolean isA(String head) {
    return eq(head, this.head);
  }

  boolean is(String head, int size) {
    return isA(head) && size() == size;
  }
  
  boolean is(String head) { return isA(head); }
  boolean headIs(String head) { return isA(head); }
  
  boolean is(String... heads) {
    return asList(heads).contains(head);
  }
  
  // check head for one of these (ignore case)
  boolean isic(String... heads) {
    return containsIgnoreCase(heads, head);
  }
  
  public Iterator<Lisp> iterator() {
    return main.iterator(args);
  }
  
  Lisp subList(int fromIndex, int toIndex) {
    Lisp l = new Lisp(head);
    l.argsForEdit().addAll(args.subList(fromIndex, toIndex)); // better to copy here I guess - safe
    return l;
  }

  public boolean equals(Object o) {
    if (o == null || o.getClass() != Lisp.class) return false;
    Lisp l = (Lisp) ( o);
    return eq(head, l.head) && (isLeaf() ? l.isLeaf()
      : l.args != null && eq(args, l.args));
  }
  
  public int hashCode() {
    return head.hashCode() + main.hashCode(args);
  }
  
  Lisp addAll(List args) {
    for (Object arg : args) add(arg);
    return this;
  }
  
  String unquoted() { return unquote(raw()); }
  String unq() { return unquoted(); }
  String unq(int i) { return get(i).unq(); }
  
  // heads of arguments
  List<String> heads() { return collect(args, "head"); }
}
static class Pair<A, B> {
  A a;
  B b;

  Pair() {}
  Pair(A a, B b) {
  this.b = b;
  this.a = a;}
  
  public int hashCode() {
    return hashCodeFor(a) + 2*hashCodeFor(b);
  }
  
  public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof Pair)) return false;
    Pair t = (Pair) o;
    return eq(a, t.a) && eq(b, t.b);
  }
  
  public String toString() {
    return "<" + a + ", " + b + ">";
  }
}

static interface _SetField {
  void _setField(String name, Object value);
}

static String aGlobalID() {
  return randomID(16);
}
// better modulo that gives positive numbers always
static int mod(int n, int m) {
  return (n % m + m) % m;
}

static BigInteger mod(BigInteger n, int m) {
  return n.mod(bigint(m));
}
static String _compactString(String s) {
  return s;
}
static String upper(String s) {
  return s == null ? null : s.toUpperCase();
}
static void clearAll(Object... l) {
  for (Object o : l) callOpt(o, "clear");
}
static <A, B> void put(Map<A, B> map, A a, B b) {
  if (map != null) map.put(a, b);
}
static <A> ArrayList<A> asList(A[] a) {
  return a == null ? new ArrayList<A>() : new ArrayList<A>(Arrays.asList(a));
}

static ArrayList<Integer> asList(int[] a) {
  ArrayList<Integer> l = new ArrayList();
  for (int i : a) l.add(i);
  return l;
}

static <A> ArrayList<A> asList(Iterable<A> s) {
  if (s instanceof ArrayList) return (ArrayList) s;
  ArrayList l = new ArrayList();
  if (s != null)
    for (A a : s)
      l.add(a);
  return l;
}

static <A> ArrayList<A> asList(Enumeration<A> e) {
  ArrayList l = new ArrayList();
  if (e != null)
    while (e.hasMoreElements())
      l.add(e.nextElement());
  return l;
}
static <A> Iterator<A> iterator(Collection<A> c) {
  return c == null ? emptyIterator() : c.iterator();
}
public static String join(String glue, Iterable<String> strings) {
  if (strings == null) return "";
  StringBuilder buf = new StringBuilder();
  Iterator<String> i = strings.iterator();
  if (i.hasNext()) {
    buf.append(i.next());
    while (i.hasNext())
      buf.append(glue).append(i.next());
  }
  return buf.toString();
}

public static String join(String glue, String... strings) {
  return join(glue, Arrays.asList(strings));
}

static String join(Iterable<String> strings) {
  return join("", strings);
}

static String join(Iterable<String> strings, String glue) {
  return join(glue, strings);
}

public static String join(String[] strings) {
  return join("", strings);
}


static String join(String glue, Pair p) {
  return p == null ? "" : str(p.a) + glue + str(p.b);
}

static String strOrNull(Object o) {
  return o == null ? null : str(o);
}
static Lisp clParse(String s) {
  List<String> tok = tok_groupRoundBrackets(s);
  if (l(tok) == 1) return null;
  Lisp l = lisp(unquote(tok.get(1)));
  for (int i = 3; i < l(tok); i += 2) {
    String t = tok.get(i);
    if (t.startsWith("(") && t.endsWith(")"))
      l.add(assertNotNull(clParse(dropFirstAndLast(t))));
    else
      l.add(lisp(aiUsing(unquote(t))));
  }
  return l;
}

static List<Lisp> clParse(List<String> l) {
  return map("clParse", l);
}

static String assertGlobalID(String s) {
  return assertPossibleGlobalID(s);
}
static String quoteIfNotIdentifier(String s) {
  if (s == null) return null;
  return isJavaIdentifier(s) ? s : quote(s);
}
// get purpose 1: access a list/array/map (safer version of x.get(y))

static <A> A get(List<A> l, int idx) {
  return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}

// seems to conflict with other signatures
/*static <A, B> B get(Map<A, B> map, A key) {
  ret map != null ? map.get(key) : null;
}*/

static <A> A get(A[] l, int idx) {
  return idx >= 0 && idx < l(l) ? l[idx] : null;
}

// default to false
static boolean get(boolean[] l, int idx) {
  return idx >= 0 && idx < l(l) ? l[idx] : false;
}

// get purpose 2: access a field by reflection or a map

static Object get(Object o, String field) {
  try {
    if (o instanceof Class) return get((Class) o, field);
    
    if (o instanceof Map)
      return ((Map) o).get(field);
      
    Field f = getOpt_findField(o.getClass(), field);
    if (f != null) {
      f.setAccessible(true);
      return f.get(o);
    }
      
    
      if (o instanceof DynamicObject)
        return ((DynamicObject) o).fieldValues.get(field);
    
  } catch (Exception e) {
    throw asRuntimeException(e);
  }
  throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}

static Object get_raw(Object o, String field) {
  try {
    Field f = get_findField(o.getClass(), field);
    f.setAccessible(true);
    return f.get(o);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

static Object get(Class c, String field) {
  try {
    Field f = get_findStaticField(c, field);
    f.setAccessible(true);
    return f.get(null);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

static Field get_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}

static Field get_findField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}

static <A> List<A> subList(List<A> l, int startIndex) {
  return subList(l, startIndex, l(l));
}

static <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
  startIndex = max(0, min(l(l), startIndex));
  endIndex = max(0, min(l(l), endIndex));
  if (startIndex > endIndex) return litlist();
  return l.subList(startIndex, endIndex);
}


static <A, B> Map<A, B> cloneMap(Map<A, B> map) {
  if (map == null) return litmap();
  // assume mutex is equal to collection
  synchronized(map) {
    return map instanceof TreeMap ? new TreeMap(map)
      : map instanceof LinkedHashMap ? new LinkedHashMap(map)
      : new HashMap(map);
  }
}
static String quoteIfNotIdentifierOrInteger(String s) {
  if (s == null) return null;
  return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
}
static String lispHead(Lisp l) {
  return l == null ? null : l.head;
}
static <A> void addAll(Collection<A> c, Collection<A> b) {
  if (c != null && b != null) c.addAll(b);
}

static <A> void addAll(Collection<A> c, A... b) {
  if (c != null) c.addAll(Arrays.asList(b));
}
static String lisp2label(Lisp l) {
  return l.isLeaf() ? l.head : clUnparse(l);
}
static Object first(Object list) {
  return empty((List) list) ? null : ((List) list).get(0);
}

static <A> A first(List<A> list) {
  return empty(list) ? null : list.get(0);
}

static <A> A first(A[] bla) {
  return bla == null || bla.length == 0 ? null : bla[0];
}

static <A> A first(Iterable<A> i) {
  if (i == null) return null;
  Iterator<A> it = i.iterator();
  return it.hasNext() ? it.next() : null;
}

static Character first(String s) { return empty(s) ? null : s.charAt(0); }


static <A, B> A first(Pair<A, B> p) {
  return p == null ? null : p.a;
}

static String webToString(Web web) {
  List<String> out = new ArrayList();
  Map<WebNode,Integer> index = new HashMap();
  for (int i = 0; i < l(web.nodes); i++) {
    out.add("Node " + (i+1) + ": " + web.nodes.get(i));
    index.put(web.nodes.get(i), i+1);
  }
  
  for (Pair<WebNode, WebNode> p : web_relations(web))
    out.add(index.get(p.a) + " -> " + index.get(p.b) + " = " + web.getRelation(p));
    
  return fromLines(out);
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(String s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
  if (o instanceof Collection) return empty((Collection) o);
  if (o instanceof String) return empty((String) o);
  if (o instanceof Map) return empty((Map) o);
  if (o instanceof Object[]) return empty((Object[]) o);
  if (o == null) return true;
  throw fail("unknown type for 'empty': " + getType(o));
}

static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static String div(Object contents, Object... params) {
  return htag("div", contents, params);
}

static BigInteger div(BigInteger a, BigInteger b) {
  return a.divide(b);
}

static BigInteger div(BigInteger a, int b) {
  return a.divide(bigint(b));
}
static long nowUnlessLoading() {
  return /*dynamicObjectIsLoading() ? 0 :*/ now();
}
static String find(String pattern, String text) {
  Matcher matcher = Pattern.compile(pattern).matcher(text);
  if (matcher.find())
    return matcher.group(1);
  return null;
}

static <A> A find(Collection<A> c, Object... data) {
  for (A x : c)
    if (checkFields(x, data))
      return x;
  return null;
}
static char charPlus(char a, int b) {
  return (char) (((int) a) + b);
}
// make a lisp form
static Lisp lisp(String head, Object... args) {
  Lisp l = new Lisp(head);
  for (Object o : args)
    l.add(o);
  return l;
}

static Lisp lisp(String head, Collection args) {
  return new Lisp(head, args);
}

static BigInteger plus(BigInteger a, BigInteger b) {
  return a.add(b);
}

static BigInteger plus(BigInteger a, long b) {
  return a.add(bigint(b));
}
static List collect(Collection c, String field) {
  return collectField(c, field);
}

static List collect(String field, Collection c) {
  return collectField(c, field);
}


static BigInteger mul(BigInteger a, BigInteger b) {
  return a.multiply(b);
}

static BigInteger mul(BigInteger a, long b) {
  return a.multiply(bigint(b));
}
static <A, B> Set<A> keys(Map<A, B> map) {
  return map == null ? new HashSet() : map.keySet();
}

static Set keys(Object map) {
  return keys((Map) map);
}




  static <A, B> Set<A> keys(MultiMap<A, B> mm) {
    return mm.keySet();
  }



static <A> void remove(List<A> l, int i) {
  if (l != null && i >= 0 && i < l(l))
    l.remove(i);
}

static <A> void remove(Collection<A> l, A a) {
  if (l != null) l.remove(a);
}
static List emptyList() {
  return new ArrayList();
  //ret Collections.emptyList();
}

static List emptyList(int capacity) {
  return new ArrayList(capacity);
}

// Try to match capacity
static List emptyList(Iterable l) {
  return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static int hashCode(Object a) {
  return a == null ? 0 : a.hashCode();
}
static <A, B> Map<A, B> putAll(Map<A, B> a, Map<? extends A,? extends B> b) {
  if (a != null) a.putAll(b);
  return a;
}
static BigInteger bigint(String s) {
  return new BigInteger(s);
}

static BigInteger bigint(long l) {
  return BigInteger.valueOf(l);
}
static <A> boolean setAdd(Collection<A> c, A a) {
  if (c == null || c.contains(a)) return false;
  c.add(a);
  return true;
}
static String unquote(String s) {
  if (s == null) return null;
  if (startsWith(s, '[')) {
    int i = 1;
    while (i < s.length() && s.charAt(i) == '=') ++i;
    if (i < s.length() && s.charAt(i) == '[') {
      String m = s.substring(1, i);
      if (s.endsWith("]" + m + "]"))
        return s.substring(i+1, s.length()-i-1);
    }
  }
  
  if (s.length() > 1) {
    char c = s.charAt(0);
    if (c == '\"' || c == '\'') {
      int l = endsWith(s, c) ? s.length()-1 : s.length();
      StringBuilder sb = new StringBuilder(l-1);
  
      for (int i = 1; i < l; i++) {
        char ch = s.charAt(i);
        if (ch == '\\') {
          char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
          // Octal escape?
          if (nextChar >= '0' && nextChar <= '7') {
              String code = "" + nextChar;
              i++;
              if ((i < l - 1) && s.charAt(i + 1) >= '0'
                      && s.charAt(i + 1) <= '7') {
                  code += s.charAt(i + 1);
                  i++;
                  if ((i < l - 1) && s.charAt(i + 1) >= '0'
                          && s.charAt(i + 1) <= '7') {
                      code += s.charAt(i + 1);
                      i++;
                  }
              }
              sb.append((char) Integer.parseInt(code, 8));
              continue;
          }
          switch (nextChar) {
          case '\"':
              ch = '\"';
              break;
          case '\\':
              ch = '\\';
              break;
          case 'b':
              ch = '\b';
              break;
          case 'f':
              ch = '\f';
              break;
          case 'n':
              ch = '\n';
              break;
          case 'r':
              ch = '\r';
              break;
          case 't':
              ch = '\t';
              break;
          case '\'':
              ch = '\'';
              break;
          // Hex Unicode: u????
          case 'u':
              if (i >= l - 5) {
                  ch = 'u';
                  break;
              }
              int code = Integer.parseInt(
                      "" + s.charAt(i + 2) + s.charAt(i + 3)
                         + s.charAt(i + 4) + s.charAt(i + 5), 16);
              sb.append(Character.toChars(code));
              i += 5;
              continue;
          default:
            ch = nextChar; // added by Stefan
          }
          i++;
        }
        sb.append(ch);
      }
      return sb.toString();
    }
  }
    
  return s; // not quoted - return original
}
static String clUnparse(Lisp l) {
  if (l == null) return "";
  return join(" ", (List) concatLists(ll(conceptQuote(l.head)), map("clUnparse_sub", l)));
}

static String clUnparse_sub(Lisp l) {
  return l.empty() ? clUnparse(l) : "(" + clUnparse(l) + ")";
}

static List<String> clUnparse(List<Lisp> l) {
  return map("clUnparse", l);
}

static String getString(Map map, Object key) {
  return map == null ? null : (String) map.get(key);
}

static String getString(List l, int idx) {
  return (String) get(l, idx);
}

static String getString(Object o, Object key) {
  if (o instanceof Map) return getString((Map) o, key);
  if (key instanceof String)
    return (String) getOpt(o, (String) key);
  throw fail("Not a string key: " + getClassName(key));
}
static boolean containsIgnoreCase(Collection<String> l, String s) {
  for (String x : l)
    if (eqic(x, s))
      return true;
  return false;
}

static boolean containsIgnoreCase(String[] l, String s) {
  for (String x : l)
    if (eqic(x, s))
      return true;
  return false;
}

static boolean containsIgnoreCase(String s, char c) {
  return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}

static boolean containsIgnoreCase(String a, String b) {
  return indexOfIgnoreCase(a, b) >= 0;
}
static <A, B> Pair<A, B> pair(A a, B b) {
  return new Pair(a, b);
}

static <A> Pair<A, A> pair(A a) {
  return new Pair(a, a);
}
static boolean structure_showTiming, structure_checkTokenCount;

static String structure(Object o) {
  return structure(o, new structure_Data());
}

static String structure(Object o, structure_Data d) {
  StringWriter sw = new StringWriter();
  d.out = new PrintWriter(sw);
  structure_go(o, d);
  String s = str(sw);
  if (structure_checkTokenCount) {
    print("token count=" + d.n);
    assertEquals("token count", l(javaTokC(s)), d.n);
  }
  return s;
}

static void structure_go(Object o, structure_Data d) {
  structure_1(o, d);
  while (nempty(d.stack))
    popLast(d.stack).run();
}

static void structureToPrintWriter(Object o, PrintWriter out) {
  structure_Data d = new structure_Data();
  d.out = out;
  structure_go(o, d);
}

// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;

static class structure_Data {
  PrintWriter out;
  int stringSizeLimit;
  int shareStringsLongerThan = 20;
  boolean noStringSharing;

  IdentityHashMap<Object,Integer> seen = new IdentityHashMap();
  //new BitSet refd;
  HashMap<String,Integer> strings = new HashMap();
  HashSet<String> concepts = new HashSet();
  HashMap<Class, List<Field>> fieldsByClass = new HashMap();
  int n; // token count
  List<Runnable> stack = new ArrayList();
  
  // append single token
  structure_Data append(String token) { out.print(token); ++n; return this; }
  structure_Data append(int i) { out.print(i); ++n; return this; }
  
  // append multiple tokens
  structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
  
  // extend last token
  structure_Data app(String token) { out.print(token); return this; }
  structure_Data app(int i) { out.print(i); return this; }
}

static void structure_1(final Object o, final structure_Data d) {
  if (o == null) { d.append("null"); return; }
  
  Class c = o.getClass();
  boolean concept = false;
  
  List<Field> lFields = d.fieldsByClass.get(c);
  
  if (lFields == null) {
    // these are never back-referenced (for readability)
    
    if (o instanceof Number) {
      PrintWriter out = d.out;
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
      if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
      if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; }
      if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; }
      if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; }
    }
  
    if (o instanceof Boolean) {
      d.append(((Boolean) o).booleanValue() ? "t" : "f"); return;
    }
      
    if (o instanceof Character) {
      d.append(quoteCharacter((Character) o)); return;
    }
      
    if (o instanceof File) {
      d.append("File ").append(quote(((File) o).getPath())); return;
    }
      
    // referencable objects follow
    
    Integer ref = d.seen.get(o);
    if (o instanceof String && ref == null) ref = d.strings.get((String) o);
    if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }

    if (!(o instanceof String))
      d.seen.put(o, d.n); // record token number
    else {
      String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
      if (!d.noStringSharing) {
        if (d.shareStringsLongerThan == Integer.MAX_VALUE)
          d.seen.put(o, d.n);
        if (l(s) >= d.shareStringsLongerThan)
          d.strings.put(s, d.n);
      }
      quoteToPrintWriter(s, d.out); d.n++; return;
    }
      
    if (o instanceof HashSet) {
      d.append("hashset ");
      structure_1(new ArrayList((Set) o), d);
      return;
    }
  
    if (o instanceof TreeSet) {
      d.append("treeset ");
      structure_1(new ArrayList((Set) o), d);
      return;
    }
    
    String name = c.getName();
    if (o instanceof Collection
      && !startsWith(name, "main$")
      /* && neq(name, "main$Concept$RefL") */) {
      d.append("[");
      final int l = d.n;
      final Iterator it = ((Collection) o).iterator();
      d.stack.add(new Runnable() { public void run() { try { 
        if (!it.hasNext())
          d.append("]");
        else {
          d.stack.add(this);
          if (d.n != l) d.append(", ");
          structure_1(it.next(), d);
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (!it.hasNext())\r\n          d.append(\"]\");\r\n        else {\r\n          d.sta..."; }});
      return;
    }
    
    if (o instanceof Map && !startsWith(name, "main$")) {
      if (o instanceof LinkedHashMap) d.append("lhm");
      else if (o instanceof HashMap) d.append("hm");
      d.append("{");
      final int l = d.n;
      final Iterator it = ((Map) o).entrySet().iterator();
      
      d.stack.add(new Runnable() {
        boolean v;
        Map.Entry e;
        
        public void run() {
          if (v) {
            d.append("=");
            v = false;
            d.stack.add(this);
            structure_1(e.getValue(), d);
          } else {
            if (!it.hasNext())
              d.append("}");
            else {
              e = (Map.Entry) it.next();
              v = true;
              d.stack.add(this);
              if (d.n != l) d.append(", ");
              structure_1(e.getKey(), d);
            }
          }
        }
      });
      return;
    }
    
    if (c.isArray()) {
      if (o instanceof byte[]) {
        d.append("ba ").append(quote(bytesToHex((byte[]) o))); return;
      }
  
      final int n = Array.getLength(o);
  
      if (o instanceof boolean[]) {
        String hex = boolArrayToHex((boolean[]) o);
        int i = l(hex);
        while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
        d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return;
      }
      
      String atype = "array", sep = ", ";
  
      if (o instanceof int[]) {
        //ret "intarray " + quote(intArrayToHex((int[]) o));
        atype = "intarray";
        sep = " ";
      }
      
      d.append(atype).append("{");
      d.stack.add(new Runnable() {
        int i;
        public void run() {
          if (i >= n)
            d.append("}");
          else {
            d.stack.add(this);
            if (i > 0) d.append(", ");
            structure_1(Array.get(o, i++), d);
          }
        }
      });
      return;
    }
  
    if (o instanceof Class) {
      d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return;
    }
      
    if (o instanceof Throwable) {
      d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return;
    }
      
    if (o instanceof BitSet) {
      BitSet bs = (BitSet) o;
      d.append("bitset{", 2);
      int l = d.n;
      for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
        if (d.n != l) d.append(", ");
        d.append(i);
      }
      d.append("}"); return;
    }
      
    // Need more cases? This should cover all library classes...
    if (name.startsWith("java.") || name.startsWith("javax.")) {
      d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able
    }
    
    
      if (o instanceof Lisp) {
        d.append("l(", 2);
        final Lisp lisp = (Lisp) ( o);
        structure_1(lisp.head, d);
        final Iterator it = lisp.args == null ? emptyIterator() : lisp.args.iterator();
        d.stack.add(new Runnable() { public void run() { try { 
          if (!it.hasNext())
            d.append(")");
          else {
            d.stack.add(this);
            d.append(", ");
            structure_1(it.next(), d);
          }
        
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (!it.hasNext())\r\n            d.append(\")\");\r\n          else {\r\n           ..."; }});
        return;
      }
    
      
    /*if (name.equals("main$Lisp")) {
      fail("lisp not supported right now");
    }*/
    
    String dynName = shortDynamicClassName(o);
    if (concept && !d.concepts.contains(dynName)) {
      d.concepts.add(dynName);
      d.append("c ");
    }
    
    // serialize an object with fields.
    // first, collect all fields and values in fv.
    
    TreeSet<Field> fields = new TreeSet<Field>(new Comparator<Field>() {
      public int compare(Field a, Field b) {
        return stdcompare(a.getName(), b.getName());
      }
    });
    
    Class cc = c;
    while (cc != Object.class) {
      for (Field field : getDeclaredFields_cached(cc)) {
        if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
          continue;
        String fieldName = field.getName();
        
        fields.add(field);
        
        // put special cases here...
      }
        
      cc = cc.getSuperclass();
    }
    
    lFields = asList(fields);
    
    // Render this$1 first because unstructure needs it for constructor call.
    
    for (int i = 0; i < l(lFields); i++) {
      Field f = lFields.get(i);
      if (f.getName().equals("this$1")) {
        lFields.remove(i);
        lFields.add(0, f);
        break;
      }
    }
  
    
    d.fieldsByClass.put(c, lFields);
  } // << if (lFields == null)
  else { // ref handling for lFields != null
    Integer ref = d.seen.get(o);
    if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
    d.seen.put(o, d.n); // record token number
  }

  LinkedHashMap<String,Object> fv = new LinkedHashMap();
  for (Field f : lFields) {
    Object value;
    try {
      value = f.get(o);
    } catch (Exception e) {
      value = "?";
    }
      
    if (value != null)
      fv.put(f.getName(), value);
    
  }
  
  String name = c.getName();
  String shortName = dropPrefix("main$", name);
    
  // Now we have fields & values. Process fieldValues if it's a DynamicObject.
  
  // omit field "className" if equal to class's name
  if (concept && eq(fv.get("className"), shortName))
    fv.remove("className");
          
  if (o instanceof DynamicObject) {
    fv.putAll((Map) fv.get("fieldValues"));
    fv.remove("fieldValues");
    shortName = shortDynamicClassName(o);
    fv.remove("className");
  }
  
  String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
  
  d.append(shortName);
  
  
  final int l = d.n;
  final Iterator it = fv.entrySet().iterator();
  
  d.stack.add(new Runnable() { public void run() { try { 
    if (!it.hasNext()) {
      if (d.n != l)
        d.append(")");
    } else {
      Map.Entry e = (Map.Entry) it.next();
      d.append(d.n == l ? "(" : ", ");
      d.append((String) e.getKey()).append("=");
      d.stack.add(this);
      structure_1(e.getValue(), d);
    }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (!it.hasNext()) {\r\n      if (d.n != l)\r\n        d.append(\")\");\r\n    } else..."; }});
}

static int charDiff(char a, char b) {
  return (int) a-(int) b;
}
static int hashCodeFor(Object a) {
  return a == null ? 0 : a.hashCode();
}


static String htag(String tag) {
  return htag(tag, "");
}

static String htag(String tag, Object contents, Object... params) {
  String openingTag = hopeningTag(tag, params);
  String s = str(contents);
  if (empty(s))
    return dropLast(openingTag) + "/>";
  return openingTag + s + "</" + tag + ">";
}
static String quote(Object o) {
  if (o == null) return "null";
  return quote(str(o));
}

static String quote(String s) {
  if (s == null) return "null";
  StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
  quote_impl(s, out);
  return out.toString();
}
  
static void quote_impl(String s, StringBuilder out) {
  out.append('"');
  int l = s.length();
  for (int i = 0; i < l; i++) {
    char c = s.charAt(i);
    if (c == '\\' || c == '"')
      out.append('\\').append(c);
    else if (c == '\r')
      out.append("\\r");
    else if (c == '\n')
      out.append("\\n");
    else
      out.append(c);
  }
  out.append('"');
}
static int shorten_default = 100;

static String shorten(String s) { return shorten(s, shorten_default); }

static String shorten(String s, int max) {
  return shorten(s, max, "...");
}

static String shorten(String s, int max, String shortener) {
  if (s == null) return "";
  if (max < 0) return s;
  return s.length() <= max ? s : substring(s, 0, min(s.length(), max-l(shortener))) + shortener;
}

static String shorten(int max, String s) { return shorten(s, max); }
static String quoteCharacter(char c) {
  if (c == '\'') return "'\\''";
  if (c == '\\') return "'\\\\'";
  if (c == '\r') return "'\\r'";
  if (c == '\n') return "'\\n'";
  if (c == '\t') return "'\\t'";
  return "'" + c + "'";
}

static <A> List<A> dropFirstAndLast(int n, List<A> l) {
  return new ArrayList(subList(l, n, l(l)-n));
}

static String dropFirstAndLast(String s) {
  return substring(s, 1, l(s)-1);
}
static String shortDynamicClassName(Object o) {
 if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
    return ((DynamicObject) o).className;
  return shortClassName(o);
}
static String dropPrefix(String prefix, String s) {
  return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static Map litmap(Object... x) {
  HashMap map = new HashMap();
  litmap_impl(map, x);
  return map;
}

static void litmap_impl(Map map, Object... x) {
  for (int i = 0; i < x.length-1; i += 2)
    if (x[i+1] != null)
      map.put(x[i], x[i+1]);
}
static String getType(Object o) {
  return getClassName(o);
}
static boolean endsWith(String a, String b) {
  return a != null && a.endsWith(b);
}

static boolean endsWith(String a, char c) {
  return nempty(a) && lastChar(a) == c;
}



static boolean isJavaIdentifier(String s) {
  if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
    return false;
  for (int i = 1; i < s.length(); i++)
    if (!Character.isJavaIdentifierPart(s.charAt(i)))
      return false;
  return true;
}
static int min(int a, int b) {
  return Math.min(a, b);
}

static long min(long a, long b) {
  return Math.min(a, b);
}

static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }

static double min(double a, double b) {
  return Math.min(a, b);
}

static double min(double[] c) {
  double x = Double.MAX_VALUE;
  for (double d : c) x = Math.min(x, d);
  return x;
}

static float min(float[] c) {
  float x = Float.MAX_VALUE;
  for (float d : c) x = Math.min(x, d);
  return x;
}

static byte min(byte[] c) {
  byte x = 127;
  for (byte d : c) if (d < x) x = d;
  return x;
}

static short min(short[] c) {
  short x = 0x7FFF;
  for (short d : c) if (d < x) x = d;
  return x;
}
static <A> ArrayList<A> litlist(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}
static List map(Iterable l, Object f) {
  return map(f, l);
}

static List map(Object f, Iterable l) {
  List x = emptyList(l);
  if (l != null) for (Object o : l)
    x.add(callF(f, o));
  return x;
}


  static List map(F1 f, Iterable l) {
    List x = emptyList(l);
    if (l != null) for (Object o : l)
      x.add(callF(f, o));
    return x;
  }


static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }

static List map(Object f, Map map) {
  return map(map, f);
}

// map: func(key, value) -> list element
static List map(Map map, Object f) {
  List x = new ArrayList();
  if (map != null) for (Object _e : map.entrySet()) {
    Map.Entry e = (Map.Entry) _e;
    x.add(callF(f, e.getKey(), e.getValue()));
  }
  return x;
}
static List collectField(Collection c, String field) {
  List l = new ArrayList();
  for (Object a : c)
    l.add(getOpt(a, field));
  return l;
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }

static int max(Collection<Integer> c) {
  int x = Integer.MIN_VALUE;
  for (int i : c) x = max(x, i);
  return x;
}

static double max(double[] c) {
  if (c.length == 0) return Double.MIN_VALUE;
  double x = c[0];
  for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
  return x;
}

static float max(float[] c) {
  if (c.length == 0) return Float.MAX_VALUE;
  float x = c[0];
  for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
  return x;
}

static byte max(byte[] c) {
  byte x = -128;
  for (byte d : c) if (d > x) x = d;
  return x;
}

static short max(short[] c) {
  short x = -0x8000;
  for (short d : c) if (d > x) x = d;
  return x;
}
static List<String> javaTokC(String s) {
  if (s == null) return null;
  int l = s.length();
  ArrayList<String> tok = new ArrayList();
  
  int i = 0;
  while (i < l) {
    int j = i;
    char c, d;
    
    // scan for whitespace
    while (j < l) {
      c = s.charAt(j);
      d = j+1 >= l ? '\0' : s.charAt(j+1);
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
        ++j;
      else if (c == '/' && d == '*') {
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
        j = Math.min(j+2, l);
      } else if (c == '/' && d == '/') {
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
      } else
        break;
    }
    
    i = j;
    if (i >= l) break;
    c = s.charAt(i);
    d = i+1 >= l ? '\0' : s.charAt(i+1);

    // scan for non-whitespace
    if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
          ++j;
          break;
        } else if (s.charAt(j) == '\\' && j+1 < l)
          j += 2;
        else
          ++j;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
    else if (Character.isDigit(c)) {
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
    } else if (c == '[' && d == '[') {
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
      j = Math.min(j+2, l);
    } else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
      do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
      j = Math.min(j+3, l);
    } else
      ++j;
      
    tok.add(javaTok_substringC(s, i, j));
    i = j;
  }
  
  return tok;
}
static <A> A assertEquals(Object x, A y) {
  return assertEquals(null, x, y);
}

static <A> A assertEquals(String msg, Object x, A y) {
  if (!(x == null ? y == null : x.equals(y)))
    throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
  return y;
}
static boolean aiUsing_enabled;
static Set<String> aiUsing_set = synchroTreeSet();

static String aiUsing(String s) {
  if (aiUsing_enabled)
    aiUsing_set.addAll(aggressivelyCollectPossibleGlobalIDs(s));
  return s;
}

static void aiUsing(Object o) {
  // TODO
}

static <A> List<A> aiUsing(List<A> l) {
  if (aiUsing_enabled)
    for (Object li : unnull(l)) aiUsing(li);
  return l;
}

static Lisp aiUsing(Lisp l) {
  if (aiUsing_enabled && l != null) {
    aiUsing(l.head);
    for (Lisp sub : l) aiUsing(sub);
  }
  return l;
}
static HashMap<Class, Field[]> getDeclaredFields_cache = new HashMap();

static Field[] getDeclaredFields_cached(Class c) {
  Field[] fields;
  synchronized(getDeclaredFields_cache) {
    fields = getDeclaredFields_cache.get(c);
    if (fields == null) {
      getDeclaredFields_cache.put(c, fields = c.getDeclaredFields());
      for (Field f : fields)
        f.setAccessible(true);
    }
  }
  return fields;
}
static Field getOpt_findField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}
// works on lists and strings and null

static int indexOfIgnoreCase(Object a, Object b) {
  if (a == null) return -1;
  if (a instanceof String) {
     Matcher m = Pattern.compile((String) b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher((String) a);
     if (m.find()) return m.start(); else return -1;
  }
  if (a instanceof List) {
    for (int i = 0; i < ((List) a).size(); i++) {
      Object o = ((List) a).get(i);
      if (o != null && ((String) o).equalsIgnoreCase((String) b))
        return i;
    }
    return -1;
  }
  throw fail("Unknown type: " + a);
}
static String boolArrayToHex(boolean[] a) {
  return bytesToHex(boolArrayToBytes(a));
}
static <A> List<A> ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}
static Iterator emptyIterator() {
  return Collections.emptyIterator();
}
  public static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

  public static String bytesToHex(byte[] bytes, int ofs, int len) {
    StringBuilder stringBuilder = new StringBuilder(len*2);
    for (int i = 0; i < len; i++) {
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
      stringBuilder.append(s.substring(s.length()-2, s.length()));
    }
    return stringBuilder.toString();
  }

static boolean isInteger(String s) {
  if (s == null) return false;
  int n = l(s);
  if (n == 0) return false;
  int i = 0;
  if (s.charAt(0) == '-')
    if (++i >= n) return false;
  while (i < n) {
    char c = s.charAt(i);
    if (c < '0' || c > '9') return false;
    ++i;
  }
  return true;
}
static Set<Pair<WebNode, WebNode>> web_relations(Web web) {
  
    
  LinkedHashSet < Pair < WebNode , WebNode > > l = new LinkedHashSet();
  for (WebNode n : web.nodes)
    if (n instanceof WebRelation)
      l.add(pair(((WebRelation) n).a, ((WebRelation) n).b));
  return l;
}
static String assertPossibleGlobalID(String s) {
  if (!possibleGlobalID(s))
    throw fail("Not an acceptable global ID: " + s);
  return s;
}
static void quoteToPrintWriter(String s, PrintWriter out) {
  if (s == null) { out.print("null"); return; }
  out.print('"');
  int l = s.length();
  for (int i = 0; i < l; i++) {
    char c = s.charAt(i);
    if (c == '\\' || c == '"') {
      out.print('\\'); out.print(c);
    } else if (c == '\r')
      out.print("\\r");
    else if (c == '\n')
      out.print("\\n");
    else
      out.print(c);
  }
  out.print('"');
}
static List<String> tok_groupRoundBrackets(String s) {
  List<String> tok = javaTok(s);
  while (true) {
    int i = tok.lastIndexOf("(");
    if (i < 0) return tok;
    int j = indexOf(tok, ")", i);
    if (j < 0) return tok;
    tok.set(i, join(subList(tok, i, j+1)));
    tok.subList(i+1, j+1).clear();
    assertTrue(odd(l(tok)));
  }
}
static <A> List<A> concatLists(Collection<A>... lists) {
  List<A> l = new ArrayList();
  for (Collection<A> list : lists)
    if (list != null)
      l.addAll(list);
  return l;
}

static <A> List<A> concatLists(Collection<List<A>> lists) {
  List<A> l = new ArrayList();
  for (List<A> list : lists)
    if (list != null)
      l.addAll(list);
  return l;
}

static Object callOpt(Object o) {
  if (o == null) return null;
  return callF(o);
}

static Object callOpt(Object o, String method, Object... args) {
  try {
    if (o == null) return null;
    if (o instanceof Class) {
      Method m = callOpt_findStaticMethod((Class) o, method, args, false);
      if (m == null) return null;
      m.setAccessible(true);
      return m.invoke(null, args);
    } else {
      Method m = callOpt_findMethod(o, method, args, false);
      if (m == null) return null;
      m.setAccessible(true);
      return m.invoke(o, args);
    }
  } catch (Exception e) {
    //fail(e.getMessage() + " | Method: " + method + ", receiver: " + className(o) + ", args: (" + join(", ", map(f className, args) + ")");
    throw new RuntimeException(e);
  }
}

static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
  Class _c = c;
  while (c != null) {
    for (Method m : c.getDeclaredMethods()) {
      if (debug)
        System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
      if (!m.getName().equals(method)) {
        if (debug) System.out.println("Method name mismatch: " + method);
        continue;
      }

      if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
        continue;

      return m;
    }
    c = c.getSuperclass();
  }
  return null;
}

static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
  Class c = o.getClass();
  while (c != null) {
    for (Method m : c.getDeclaredMethods()) {
      if (debug)
        System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
      if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
        return m;
    }
    c = c.getSuperclass();
  }
  return null;
}

private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
  Class<?>[] types = m.getParameterTypes();
  if (types.length != args.length) {
    if (debug)
      System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
    return false;
  }
  for (int i = 0; i < types.length; i++)
    if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
      if (debug)
        System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
      return false;
    }
  return true;
}


// usually L<S>
static String fromLines(Collection lines) {
  StringBuilder buf = new StringBuilder();
  if (lines != null)
    for (Object line : lines)
      buf.append(str(line)).append('\n');
  return buf.toString();
}

static String fromLines(String... lines) {
  return fromLines(asList(lines));
}
static long now_virtualTime;
static long now() {
  return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}

static boolean checkFields(Object x, Object... data) {
  for (int i = 0; i < l(data); i += 2)
    if (neq(getOpt(x, (String) data[i]), data[i+1]))
      return false;
  return true;
}
static String conceptQuote(String s) {
  if (isIdentifier(s) || isInteger(s) || isProperlyQuoted(s)) return s;
  return quote(s);
}
static boolean eqic(String a, String b) {
  if ((a == null) != (b == null)) return false;
  if (a == null) return true;
  return a.equalsIgnoreCase(b);
}
static int randomID_defaultLength = 12;

static String randomID(int length) {
  return makeRandomID(length);
}

static String randomID() {
  return randomID(randomID_defaultLength);
}
static Object getOpt(Object o, String field) {
  return getOpt_cached(o, field);
}

static Object getOpt_raw(Object o, String field) {
  try {
    Field f = getOpt_findField(o.getClass(), field);
    if (f == null) return null;
    f.setAccessible(true);
    return f.get(o);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

// access of static fields is not yet optimized
static Object getOpt(Class c, String field) {
  try {
    if (c == null) return null;
    Field f = getOpt_findStaticField(c, field);
    if (f == null) return null;
    f.setAccessible(true);
    return f.get(null);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

static Field getOpt_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}

static <A> A popLast(List<A> l) {
  return liftLast(l);
}
static int stdcompare(Number a, Number b) {
  return cmp(a, b);
}

static int stdcompare(String a, String b) {
  return cmp(a, b);
}

static int stdcompare(long a, long b) {
  return a < b ? -1 : a > b ? 1 : 0;
}

static int stdcompare(Object a, Object b) {
  return cmp(a, b);
}



static String javaTok_substringC(String s, int i, int j) {
  return s.substring(i, j);
}
static String[] dropLast(String[] a, int n) {
  n = Math.min(n, a.length);
  String[] b = new String[a.length-n];
  System.arraycopy(a, 0, b, 0, b.length);
  return b;
}

static <A> List<A> dropLast(List<A> l) {
  return subList(l, 0, l(l)-1);
}

static <A> List<A> dropLast(int n, List<A> l) {
  return subList(l, 0, l(l)-n);
}

static <A> List<A> dropLast(Iterable<A> l) {
  return dropLast(asList(l));
}

static String dropLast(String s) {
  return substring(s, 0, l(s)-1);
}

static String dropLast(String s, int n) {
  return substring(s, 0, l(s)-n);
}

static String dropLast(int n, String s) {
  return dropLast(s, n);
}

static byte[] boolArrayToBytes(boolean[] a) {
  byte[] b = new byte[(l(a)+7)/8];
  for (int i = 0; i < l(a); i++)
    if (a[i])
      b[i/8] |= 1 << (i & 7);
  return b;
}
static boolean isProperlyQuoted(String s) {
  return s.length() >= 2
    && s.startsWith("\"")
    && s.endsWith("\"")
    && (!s.endsWith("\\\"") || s.endsWith("\\\\\""));
}
static boolean odd(int i) {
  return (i & 1) != 0;
}

static boolean odd(long i) {
  return (i & 1) != 0;
}
static <A> Set<A> synchroTreeSet() {
  return Collections.synchronizedSet(new TreeSet<A>());
}

static <A> A liftLast(List<A> l) {
  if (l.isEmpty()) return null;
  int i = l(l)-1;
  A a = l.get(i);
  l.remove(i);
  return a;
}
static int cmp(Number a, Number b) {
  return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}

static int cmp(double a, double b) {
  return a < b ? -1 : a == b ? 0 : 1;
}

static int cmp(String a, String b) {
  return a == null ? b == null ? 0 : -1 : a.compareTo(b);
}

static int cmp(Object a, Object b) {
  if (a == null) return b == null ? 0 : -1;
  if (b == null) return 1;
  return ((Comparable) a).compareTo(b);
}
static String unnull(String s) {
  return s == null ? "" : s;
}

static <A> List<A> unnull(List<A> l) {
  return l == null ? emptyList() : l;
}

static <A, B> Map<A, B> unnull(Map<A, B> l) {
  return l == null ? emptyMap() : l;
}

static <A> Iterable<A> unnull(Iterable<A> i) {
  return i == null ? emptyList() : i;
}

static <A> A[] unnull(A[] a) {
  return a == null ? (A[]) new Object[0] : a;
}

static BitSet unnull(BitSet b) {
  return b == null ? new BitSet() : b;
}


// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings

static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;

static List<String> javaTok(String s) {
  return javaTok(s, null);
}

static List<String> javaTok(String s, List<String> existing) {
  ++javaTok_n;
  int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
  ArrayList<String> tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
  int l = s.length();
  
  int i = 0, n = 0;
  while (i < l) {
    int j = i;
    char c, d;
    
    // scan for whitespace
    while (j < l) {
      c = s.charAt(j);
      d = j+1 >= l ? '\0' : s.charAt(j+1);
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
        ++j;
      else if (c == '/' && d == '*') {
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
        j = Math.min(j+2, l);
      } else if (c == '/' && d == '/') {
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
      } else
        break;
    }
    
    if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(javaTok_substringN(s, i, j));
    ++n;
    i = j;
    if (i >= l) break;
    c = s.charAt(i);
    d = i+1 >= l ? '\0' : s.charAt(i+1);

    // scan for non-whitespace
    
    // Special JavaX syntax: 'identifier
    if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
      j += 2;
      while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
        ++j;
    } else if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
          ++j;
          break;
        } else if (s.charAt(j) == '\\' && j+1 < l)
          j += 2;
        else
          ++j;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
    else if (Character.isDigit(c)) {
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
    } else if (c == '[' && d == '[') {
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
      j = Math.min(j+2, l);
    } else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
      do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
      j = Math.min(j+3, l);
    } else
      ++j;
      
    if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(javaTok_substringC(s, i, j));
    ++n;
    i = j;
  }
  
  if ((tok.size() % 2) == 0) tok.add("");
  javaTok_elements += tok.size();
  return tok;
}

static List<String> javaTok(List<String> tok) {
  return javaTok(join(tok), tok);
}

static boolean javaTok_isCopyable(String t, String s, int i, int j) {
  return t.length() == j-i
    && s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static String hopeningTag(String tag, Object... params) {
  StringBuilder buf = new StringBuilder();
  buf.append("<" + tag);
  for (int i = 0; i < l(params); i += 2) {
    String name = (String) get(params, i);
    Object val = get(params, i+1);
    if (nempty(name) && val != null) {
      String s = str(val);
      if (!empty(s))
        buf.append(" " + name + "=" + htmlQuote(s));
    }
  }
  buf.append(">");
  return str(buf);
}
static boolean isIdentifier(String s) {
  return isJavaIdentifier(s);
}
static <A> int indexOf(List<A> l, A a, int startIndex) {
  if (l == null) return -1;
  for (int i = startIndex; i < l(l); i++)
    if (eq(l.get(i), a))
      return i;
  return -1;
}

static <A> int indexOf(List<A> l, int startIndex, A a) {
  return indexOf(l, a, startIndex);
}

static <A> int indexOf(List<A> l, A a) {
  if (l == null) return -1;
  return l.indexOf(a);
}

static int indexOf(String a, String b) {
  return a == null || b == null ? -1 : a.indexOf(b);
}

static int indexOf(String a, String b, int i) {
  return a == null || b == null ? -1 : a.indexOf(b, i);
}

static int indexOf(String a, char b) {
  return a == null ? -1 : a.indexOf(b);
}

static int indexOf(String a, char b, int i) {
  return a == null ? -1 : a.indexOf(b, i);
}

static int indexOf(String a, int i, String b) {
  return a == null || b == null ? -1 : a.indexOf(b, i);
}

static <A> int indexOf(A[] x, A a) {
  if (x == null) return -1;
  for (int i = 0; i < l(x); i++)
    if (eq(x[i], a))
      return i;
  return -1;
}
static Set<String> aggressivelyCollectPossibleGlobalIDs(String s) {
  LinkedHashSet<String> ids = new LinkedHashSet();
  if (s == null) return ids;
  for (int i = 0; i < l(s); i++) {
    int j = i;
    while (j < l(s) && Character.isLowerCase(s.charAt(j))) ++j;
    if (j-i == 16)
      ids.add(substring(s, i, j));
    i = j;
  }
  return ids;
}
//static final Map<Class, HashMap<S, Field>> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);

static class getOpt_Map extends WeakHashMap {
  getOpt_Map() {
    if (getOpt_special == null) getOpt_special = new HashMap();
    clear();
  }
  
  public void clear() {
    super.clear();
    //print("getOpt clear");
    put(Class.class, getOpt_special);
    put(String.class, getOpt_special);
  }
}

static final Map<Class, HashMap<String, Field>> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
//static final Map<Class, HashMap<S, Field>> getOpt_cache = _registerWeakMap(synchroMap(new getOpt_Map));
static HashMap getOpt_special; // just a marker

/*static void getOpt_special_init(Map map) {
  map.put(Class.class, getOpt_special);
  map.put(S.class, getOpt_special);
}*/

static Object getOpt_cached(Object o, String field) { try {
  if (o == null) return null;

  Class c = o.getClass();
  HashMap<String, Field> map;
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  
  if (map == getOpt_special) {
    if (o instanceof Class)
      return getOpt((Class) o, field);
    /*if (o instanceof S)
      ret getOpt(getBot((S) o), field);*/
    if (o instanceof Map)
      return ((Map) o).get(field);
  }
    
  Field f = map.get(field);
  if (f != null) return f.get(o);
  
    if (o instanceof DynamicObject)
      return ((DynamicObject) o).fieldValues.get(field);
  
  return null;
} catch (Exception __e) { throw rethrow(__e); } }

// used internally - we are in synchronized block
static HashMap<String, Field> getOpt_makeCache(Class c) {
  HashMap<String, Field> map;
  if (isSubtypeOf(c, Map.class))
    map = getOpt_special;
  else {
    map = new HashMap();
    Class _c = c;
    do {
      for (Field f : _c.getDeclaredFields()) {
        f.setAccessible(true);
        String name = f.getName();
        if (!map.containsKey(name))
          map.put(name, f);
      }
      _c = _c.getSuperclass();
    } while (_c != null);
  }
  getOpt_cache.put(c, map);
  return map;
}
static String shortClassName(Object o) {
  if (o == null) return null;
  Class c = o instanceof Class ? (Class) o : o.getClass();
  String name = c.getName();
  return shortenClassName(name);
}
static boolean possibleGlobalID(String s) {
  return l(s) == 16 && allLowerCaseCharacters(s);
}
static String makeRandomID(int length) {
  Random random = new Random();
  char[] id = new char[length];
  for (int i = 0; i < id.length; i++)
    id[i] = (char) ((int) 'a' + random.nextInt(26));
  return new String(id);
}
static char lastChar(String s) {
  return empty(s) ? '\0' : s.charAt(l(s)-1);
}


static String javaTok_substringN(String s, int i, int j) {
  if (i == j) return "";
  if (j == i+1 && s.charAt(i) == ' ') return " ";
  return s.substring(i, j);
}
static String shortenClassName(String name) {
  if (name == null) return null;
  int i = lastIndexOf(name, "$");
  if (i < 0) i = lastIndexOf(name, ".");
  return i < 0 ? name : substring(name, i+1);
}
static boolean isSubtypeOf(Class a, Class b) {
  return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static List<Pair> _registerDangerousWeakMap_preList;

static <A> A _registerDangerousWeakMap(A map) {
  return _registerDangerousWeakMap(map, null);
}

static <A> A _registerDangerousWeakMap(A map, Object init) {
  callF(init, map);
  
  if (init instanceof String) {
    final String f = (String) ( init);
    init = new Object() { void get(Map map) { try {  callMC(f, map) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "callMC(f, map)"; }};
  }
    
  if (javax() == null) {
    // We're in class init
    if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList();
    _registerDangerousWeakMap_preList.add(pair(map, init));
    return map;
  }
  
  try {
    call(javax(), "_registerDangerousWeakMap", map, init);
  } catch (Throwable e) { printException(e);
    upgradeJavaXAndRestart();
  }
  return map;
}

static void _onLoad_registerDangerousWeakMap() {
  assertNotNull(javax());
  if (_registerDangerousWeakMap_preList == null) return;
  for (Pair p : _registerDangerousWeakMap_preList)
    _registerDangerousWeakMap(p.a, p.b);
  _registerDangerousWeakMap_preList = null;
}
static String htmlQuote(String s) {
  return "\"" + htmlencode(s) + "\"";
}
static Map emptyMap() {
  return new HashMap();
}
static void clear(Collection c) {
  if (c != null) c.clear();
}
static boolean allLowerCaseCharacters(String s) {
  for (int i = 0; i < l(s); i++)
    if (Character.getType(s.charAt(i)) != Character.LOWERCASE_LETTER) return false;
  return true;
}


static void upgradeJavaXAndRestart() {
  run("#1001639");
  restart();
  sleep();
}
// automagically encode a whole map (keys+values)
static Map htmlencode(Map o) {
  HashMap bla = new HashMap();
  for (Object key : keys(o)) {
    Object value = o.get(key);
    bla.put(htmlencode(key), htmlencode(value));
  }
  return bla;
}

static String htmlencode(Object o) {
  return htmlencode(string(o));
}

static String htmlencode(String s) {
  if (s == null) return "";
  StringBuilder out = new StringBuilder(Math.max(16, s.length()));
  for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      /*if (c >= 0x100)
        out.append("&#x").append(charToHex(c)).append(';');
      else*/ if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
          out.append("&#");
          out.append((int) c);
          out.append(';');
      } else
          out.append(c);
  }
  return out.toString();
}
static int lastIndexOf(String a, String b) {
  return a == null || b == null ? -1 : a.lastIndexOf(b);
}


static volatile boolean sleep_noSleep;

static void sleep(long ms) {
  ping();
  if (ms < 0) return;
  // allow spin locks
  if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread");
  try {
    Thread.sleep(ms);
  } catch (Exception e) { throw new RuntimeException(e); }
}

static void sleep() { try {
  if (sleep_noSleep) throw fail("nosleep");
  print("Sleeping.");
  sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
static void restart() {
  Object j = getJavaX();
  call(j, "cleanRestart", get(j, "fullArgs"));
}
static Class run(String progID, String... args) {
  Class main = hotwire(progID);
  callMain(main, args);
  return main;
}
static String string(Object o) {
  return String.valueOf(o);
}


static <A> A callMain(A c, String... args) {
  callOpt(c, "main", new Object[] {args});
  return c;
}

static void callMain() {
  callMain(mc());
}
static Object sleepQuietly_monitor = new Object();

static void sleepQuietly() { try {
  assertFalse(isAWTThread());
  synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }
static Class<?> hotwire(String src) {
  assertFalse(_inCore());
  Class j = getJavaX();
  if (isAndroid()) {
    synchronized(j) { // hopefully this goes well...
      List<File> libraries = new ArrayList<File>();
      File srcDir = (File) call(j, "transpileMain", src, libraries);
      if (srcDir == null)
        throw fail("transpileMain returned null (src=" + quote(src) + ")");
    
      Object androidContext = get(j, "androidContext");
      return (Class) call(j, "loadx2android", srcDir, src);
    }
  } else {
    // ret hotwire_overInternalBot(src);
    Class c = (Class) ( call(j, "hotwire", src));
    hotwire_copyOver(c);
    return c;
  }
}


static boolean _inCore() {
  return false;
}
static void hotwire_copyOver(Class c) {
  synchronized(StringBuffer.class) {
    for (String field : litlist("print_log", "print_silent", "androidContext")) {
      Object o = getOpt(mc(), field);
      if (o != null)
        setOpt(c, field, o);
    }
      
    Object mainBot = getMainBot();
    if (mainBot != null)
      setOpt(c, "mainBot", mainBot);

    setOpt(c, "creator_class", new WeakReference(mc()));
  }
}
static void assertFalse(Object o) {
  if (!(eq(o, false) || isFalse(pcallF(o))))
    throw fail(str(o));
}
  
static boolean assertFalse(boolean b) {
  if (b) throw fail("oops");
  return b;
}

static boolean assertFalse(String msg, boolean b) {
  if (b) throw fail(msg);
  return b;
}



static Object mainBot;

static Object getMainBot() {
  return mainBot;
}
static Field setOpt_findField(Class c, String field) {
  HashMap<String, Field> map;
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  return map.get(field);
}

static void setOpt(Object o, String field, Object value) { try {
  if (o == null) return;
  
  
    if (o instanceof _SetField) { ((_SetField) o)._setField(field, value); return; }
  
  
  Class c = o.getClass();
  HashMap<String, Field> map;
  
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  
  if (map == getOpt_special) {
    if (o instanceof Class) {
      setOpt((Class) o, field, value);
      return;
    }
    
    // It's probably a subclass of Map. Use raw method
    setOpt_raw(o, field, value);
    return;
  }
  
  Field f = map.get(field);
  if (f != null)
    smartSet(f, o, value); // possible improvement: skip setAccessible
} catch (Exception __e) { throw rethrow(__e); } }

static void setOpt(Class c, String field, Object value) {
  if (c == null) return;
  try {
    Field f = setOpt_findStaticField(c, field);
    if (f != null)
      smartSet(f, null, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
  
static Field setOpt_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}


static void setOpt_raw(Object o, String field, Object value) { try {
  if (o == null) return;
  if (o instanceof Class) setOpt_raw((Class) o, field, value);
  else {
    Field f = setOpt_raw_findField(o.getClass(), field);
    if (f != null)
      smartSet(f, o, value);
  }
} catch (Exception __e) { throw rethrow(__e); } }

static void setOpt_raw(Class c, String field, Object value) { try {
  if (c == null) return;
  Field f = setOpt_raw_findStaticField(c, field);
  if (f != null)
    smartSet(f, null, value);
} catch (Exception __e) { throw rethrow(__e); } }
  
static Field setOpt_raw_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}

static Field setOpt_raw_findField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}
static void smartSet(Field f, Object o, Object value) throws Exception {
  f.setAccessible(true);
  
  // take care of common case (long to int)
  if (f.getType() == int.class && value instanceof Long)
    value = ((Long) value).intValue();
    
  try {
    f.set(o, value);
  } catch (Exception e) {
    
    throw e;
  }
}


static ThreadLocal<Boolean> DynamicObject_loading = new ThreadLocal();

static class DynamicObject {
  String className; // just the name, without the "main$"
  LinkedHashMap<String,Object> fieldValues = new LinkedHashMap();
  
  DynamicObject() {}
  // className = just the name, without the "main$"
  DynamicObject(String className) {
  this.className = className;}
}
}