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.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.tablePopupMenuFirst;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import static loadableUtils.utils.rethrow;
import static loadableUtils.utils.concepts_internStringsLongerThan;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.structure_ClassInfo;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.GlobalID;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import java.text.NumberFormat;

class main {

  static public class AModule extends DynPrintLog {

    public void start() {
      try {
        super.start();
        startThread("Start", new Runnable() {

          public void run() {
            try {
              AutoCloseable __9 = enter();
              try {
                try {
                  test_LineCompCompressor();
                  print("OK");
                } catch (Throwable __e) {
                  _handleException(__e);
                }
              } finally {
                _close(__9);
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "AutoCloseable __9 = enter(); try { try {\r\n    test_LineCompCompressor();\r\n   ...";
          }
        });
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }
  }

  static public boolean _moduleClass_AModule = true;

  static public String programID;

  static public void _onLoad_initUtils() {
    utils.__javax = javax();
  }

  static public void _onLoad_defaultClassFinder() {
    setDefaultClassFinder(new F1<String, Class>() {

      public Class get(String name) {
        Class c = findClass_fullName(name);
        if (c != null)
          return c;
        if (name.startsWith("main$"))
          return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
        return null;
      }
    });
  }

  static public Thread startThread(Object runnable) {
    return startThread(defaultThreadName(), runnable);
  }

  static public Thread startThread(String name, Object runnable) {
    runnable = wrapAsActivity(runnable);
    return startThread(newThread(toRunnable(runnable), name));
  }

  static public Thread startThread(Thread t) {
    _registerThread(t);
    t.start();
    return t;
  }

  static public void test_LineCompCompressor() {
    Random random = predictableRandomizer();
    List<String> lines = repF(10, () -> makeRandomID(10, random));
    Map<String, String> data = new LinkedHashMap();
    for (int i = 0; i < 100; i++) data.put("v" + (i + 1), lines(repF(10, () -> random(lines))));
    pnlStruct(data);
    LineCompCompressor lcc = new LineCompCompressor(data);
    lcc.verify = lcc.verbose = true;
    lcc.run();
  }

  static volatile public StringBuffer local_log = new StringBuffer();

  static volatile public Appendable print_log = local_log;

  static volatile public int print_log_max = 1024 * 1024;

  static volatile public int local_log_max = 100 * 1024;

  static public boolean print_silent = false;

  static public Object print_byThread_lock = new Object();

  static volatile public ThreadLocal<Object> print_byThread;

  static volatile public Object print_allThreads;

  static volatile public Object print_preprocess;

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

  static public <A> A print(String s, A o) {
    print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
    return o;
  }

  static public <A> A print(A o) {
    ping_okInCleanUp();
    if (print_silent)
      return o;
    String s = String.valueOf(o) + "\n";
    print_noNewLine(s);
    return o;
  }

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

  static public void print_raw(String s) {
    if (print_preprocess != null)
      s = (String) callF(print_preprocess, s);
    s = fixNewLines(s);
    Appendable loc = local_log;
    Appendable 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 public void print_autoRotate() {
  }

  static volatile public PersistableThrowable _handleException_lastException;

  static public List _handleException_onException = synchroList(ll("printStackTrace2"));

  static public void _handleException(Throwable e) {
    _handleException_lastException = persistableThrowable(e);
    Throwable e2 = innerException(e);
    if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
      return;
    for (Object f : cloneList(_handleException_onException)) try {
      callF(f, e);
    } catch (Throwable e3) {
      printStackTrace2(e3);
    }
  }

  static public void _close(AutoCloseable c) {
    if (c != null)
      try {
        c.close();
      } catch (Throwable e) {
        if (c instanceof javax.imageio.stream.ImageOutputStream)
          return;
        else
          throw rethrow(e);
      }
  }

  static public Class javax() {
    return getJavaX();
  }

  static public void setDefaultClassFinder(Object cf) {
    _defaultClassFinder_value = cf;
  }

  static public HashMap<String, Class> findClass_fullName_cache = new HashMap();

  static public Class findClass_fullName(String name) {
    synchronized (findClass_fullName_cache) {
      if (findClass_fullName_cache.containsKey(name))
        return findClass_fullName_cache.get(name);
      Class c;
      try {
        c = Class.forName(name);
      } catch (ClassNotFoundException e) {
        c = null;
      }
      findClass_fullName_cache.put(name, c);
      return c;
    }
  }

  static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1<String, Boolean> f) {
    return print_byThread().get() == null ? tempInterceptPrint(f) : null;
  }

  static public Throwable printStackTrace2(Throwable e) {
    print(getStackTrace2(e));
    return e;
  }

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

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

  static public Object _defaultClassFinder_value = defaultDefaultClassFinder();

  static public Object _defaultClassFinder() {
    return _defaultClassFinder_value;
  }

  static public String defaultThreadName_name;

  static public String defaultThreadName() {
    if (defaultThreadName_name == null)
      defaultThreadName_name = "A thread by " + programID();
    return defaultThreadName_name;
  }

  static public Runnable wrapAsActivity(Object r) {
    return toRunnable(r);
  }

  static public Thread newThread(Object runnable) {
    return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
  }

  static public Thread newThread(Object runnable, String name) {
    if (name == null)
      name = defaultThreadName();
    return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
  }

  static public Thread newThread(String name, Object runnable) {
    return newThread(runnable, name);
  }

  static public Runnable toRunnable(final Object o) {
    if (o instanceof Runnable)
      return (Runnable) o;
    return new Runnable() {

      public void run() {
        try {
          callF(o);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(o)";
      }
    };
  }

  static public Map<Thread, Boolean> _registerThread_threads;

  static public Object _onRegisterThread;

  static public Thread _registerThread(Thread t) {
    if (_registerThread_threads == null)
      _registerThread_threads = newWeakHashMap();
    _registerThread_threads.put(t, true);
    vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
    callF(_onRegisterThread, t);
    return t;
  }

  static public void _registerThread() {
    _registerThread(Thread.currentThread());
  }

  static public Random predictableRandomizer() {
    return predictableRandom();
  }

  static public List repF(int n, Object f, Object... args) {
    List l = new ArrayList();
    for (int i = 0; i < n; i++) l.add(callF(f, args));
    return l;
  }

  static public List repF(Object f, int n) {
    return repF(n, f);
  }

  static public <A> List<A> repF(int n, IF0<A> f) {
    return repF(f, n);
  }

  static public String makeRandomID(int length) {
    return makeRandomID(length, defaultRandomGenerator());
  }

  static public String makeRandomID(int length, Random 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 public String makeRandomID(Random r, int length) {
    return makeRandomID(length, r);
  }

  static public String lines(Iterable lines) {
    return fromLines(lines);
  }

  static public String lines(Object[] lines) {
    return fromLines(asList(lines));
  }

  static public List<String> lines(String s) {
    return toLines(s);
  }

  static public Random random_random = new Random();

  static public int random(int n) {
    return random(random_random, n);
  }

  static public int random(Random r, int n) {
    return n <= 0 ? 0 : r.nextInt(n);
  }

  static public double random(double max) {
    return random() * max;
  }

  static public double random() {
    return random_random.nextInt(100001) / 100000.0;
  }

  static public double random(double min, double max) {
    return min + random() * (max - min);
  }

  static public int random(int min, int max) {
    return min + random(max - min);
  }

  static public int random(Random r, int min, int max) {
    return min + random(r, max - min);
  }

  static public <A> A random(List<A> l) {
    return oneOf(l);
  }

  static public <A> A random(Collection<A> c) {
    if (c instanceof List)
      return random((List<A>) c);
    int i = random(l(c));
    return collectionGet(c, i);
  }

  static public void pnlStruct(Object o) {
    if (o instanceof Collection)
      pnlStruct(((Collection) o));
    else if (o instanceof Map)
      pnlStruct(((Map) o));
    else if (o != null)
      pnlStruct(ll(o));
  }

  static public <A, B extends Collection<A>> B pnlStruct(B l) {
    pnlStruct((Iterable<A>) l);
    return l;
  }

  static public <A> Iterable<A> pnlStruct(Iterable<A> l) {
    return pnlStruct("", l);
  }

  static public <A> Iterable<A> pnlStruct(String prefix, Iterable<A> l) {
    int i = 0;
    if (l != null)
      for (A a : l) print(prefix + (++i) + ". " + struct_noStringSharing(a));
    return l;
  }

  static public <A> A[] pnlStruct(A[] l) {
    pnlStruct(asList(l));
    return l;
  }

  static public <A, B> Map<A, B> pnlStruct(Map<A, B> map) {
    pnl(map(map, new F2<A, B, Object>() {

      public Object get(A a, B b) {
        try {
          return sfu(a) + " = " + sfu(b);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "sfu(a) + \" = \" + sfu(b)";
      }
    }));
    return map;
  }

  static public boolean endsWithLetterOrDigit(String s) {
    return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
  }

  static public void ping_okInCleanUp() {
    if (ping_pauseAll || ping_anyActions)
      ping_impl(true);
  }

  static public Object getThreadLocal(Object o, String name) {
    ThreadLocal t = (ThreadLocal) (getOpt(o, name));
    return t != null ? t.get() : null;
  }

  static public <A> A getThreadLocal(ThreadLocal<A> tl) {
    return tl == null ? null : tl.get();
  }

  static public <A> A getThreadLocal(ThreadLocal<A> tl, A defaultValue) {
    return or(getThreadLocal(tl), defaultValue);
  }

  static public ThreadLocal<Object> print_byThread_dontCreate() {
    return print_byThread;
  }

  static public boolean isFalse(Object o) {
    return eq(false, o);
  }

  static public Object callF(Object f, Object... args) {
    try {
      if (f instanceof String)
        return callMC((String) f, args);
      return x30_util.callF(f, args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A callF(F0<A> f) {
    return f == null ? null : f.get();
  }

  static public <A> A callF(IF0<A> f) {
    return f == null ? null : f.get();
  }

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

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

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

  static public <A> void callF(VF1<A> f, A a) {
    if (f != null)
      f.get(a);
  }

  static public Object callMC(String method, Object... args) {
    return call(mc(), method, args);
  }

  static public Object call(Object o) {
    return callF(o);
  }

  static public Object call(Object o, String method, Object... args) {
    return call_withVarargs(o, method, args);
  }

  static public String fixNewLines(String s) {
    int i = indexOf(s, '\r');
    if (i < 0)
      return s;
    int l = s.length();
    StringBuilder out = new StringBuilder(l);
    out.append(s, 0, i);
    for (; i < l; i++) {
      char c = s.charAt(i);
      if (c != '\r')
        out.append(c);
      else {
        out.append('\n');
        if (i + 1 < l && s.charAt(i + 1) == '\n')
          ++i;
      }
    }
    return out.toString();
  }

  static public void print_append(Appendable buf, String s, int max) {
    try {
      synchronized (buf) {
        buf.append(s);
        if (buf instanceof StringBuffer)
          rotateStringBuffer(((StringBuffer) buf), max);
        else if (buf instanceof StringBuilder)
          rotateStringBuilder(((StringBuilder) buf), max);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> List<A> synchroList() {
    return Collections.synchronizedList(new ArrayList<A>());
  }

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

  static public <A> List<A> ll(A... a) {
    ArrayList l = new ArrayList(a.length);
    if (a != null)
      for (A x : a) l.add(x);
    return l;
  }

  static public PersistableThrowable persistableThrowable(Throwable e) {
    return e == null ? null : new PersistableThrowable(e);
  }

  static public Throwable innerException(Throwable e) {
    return getInnerException(e);
  }

  static public boolean eq(Object a, Object b) {
    return a == b || (a == null ? b == null : b != null && a.equals(b));
  }

  static public <A> ArrayList<A> cloneList(Iterable<A> l) {
    return l instanceof Collection ? cloneList((Collection) l) : asList(l);
  }

  static public <A> ArrayList<A> cloneList(Collection<A> l) {
    if (l == null)
      return new ArrayList();
    synchronized (collectionMutex(l)) {
      return new ArrayList<A>(l);
    }
  }

  static public Class __javax;

  static public Class getJavaX() {
    try {
      return __javax;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ThreadLocal<Object> print_byThread() {
    synchronized (print_byThread_lock) {
      if (print_byThread == null)
        print_byThread = new ThreadLocal();
    }
    return print_byThread;
  }

  static public AutoCloseable tempInterceptPrint(F1<String, Boolean> f) {
    return tempSetThreadLocal(print_byThread(), f);
  }

  static public String getStackTrace2(Throwable e) {
    return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
  }

  static public Object defaultDefaultClassFinder() {
    return new F1<String, Class>() {

      public Class get(String name) {
        Class c = findClass_fullName(name);
        if (c != null)
          return c;
        if (name.startsWith("loadableUtils.utils$"))
          return findClass_fullName("main" + name.substring(19));
        return null;
      }
    };
  }

  static public String programID() {
    return getProgramID();
  }

  static public String programID(Object o) {
    return getProgramID(o);
  }

  static public Runnable _topLevelErrorHandling(final Runnable runnable) {
    final Object info = _threadInfo();
    return new Runnable() {

      public void run() {
        try {
          try {
            _threadInheritInfo(info);
            runnable.run();
          } catch (Throwable __e) {
            _handleException(__e);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcall {\r\n      _threadInheritInfo(info);\r\n      runnable.run();\r\n    }";
      }
    };
  }

  static public <A> WeakReference<A> weakRef(A a) {
    return newWeakReference(a);
  }

  static public Class mc() {
    return main.class;
  }

  static public Random predictableRandom() {
    return new Random(0);
  }

  static public Random defaultRandomGenerator() {
    return ThreadLocalRandom.current();
  }

  static public String fromLines(Iterable lines) {
    StringBuilder buf = new StringBuilder();
    if (lines != null)
      for (Object line : lines) buf.append(str(line)).append('\n');
    return buf.toString();
  }

  static public String fromLines(String... lines) {
    return fromLines(asList(lines));
  }

  static public <A> ArrayList<A> asList(A[] a) {
    return a == null ? new ArrayList<A>() : new ArrayList<A>(Arrays.asList(a));
  }

  static public ArrayList<Integer> asList(int[] a) {
    if (a == null)
      return null;
    ArrayList<Integer> l = emptyList(a.length);
    for (int i : a) l.add(i);
    return l;
  }

  static public ArrayList<Float> asList(float[] a) {
    if (a == null)
      return null;
    ArrayList<Float> l = emptyList(a.length);
    for (float i : a) l.add(i);
    return l;
  }

  static public ArrayList<Double> asList(double[] a) {
    if (a == null)
      return null;
    ArrayList<Double> l = emptyList(a.length);
    for (double i : a) l.add(i);
    return l;
  }

  static public <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 public <A> ArrayList<A> asList(Producer<A> p) {
    ArrayList l = new ArrayList();
    A a;
    if (p != null)
      while ((a = p.next()) != null) l.add(a);
    return l;
  }

  static public <A> ArrayList<A> asList(Enumeration<A> e) {
    ArrayList l = new ArrayList();
    if (e != null)
      while (e.hasMoreElements()) l.add(e.nextElement());
    return l;
  }

  static public IterableIterator<String> toLines(File f) {
    return linesFromFile(f);
  }

  static public List<String> toLines(String s) {
    List<String> lines = new ArrayList<String>();
    if (s == null)
      return lines;
    int start = 0;
    while (true) {
      int i = toLines_nextLineBreak(s, start);
      if (i < 0) {
        if (s.length() > start)
          lines.add(s.substring(start));
        break;
      }
      lines.add(s.substring(start, i));
      if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
        i += 2;
      else
        ++i;
      start = i;
    }
    return lines;
  }

  static public int toLines_nextLineBreak(String s, int start) {
    for (int i = start; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c == '\r' || c == '\n')
        return i;
    }
    return -1;
  }

  static public <A> A oneOf(List<A> l) {
    return empty(l) ? null : l.get(new Random().nextInt(l.size()));
  }

  static public char oneOf(String s) {
    return empty(s) ? '?' : s.charAt(random(l(s)));
  }

  static public String oneOf(String... l) {
    return oneOf(asList(l));
  }

  static public <A> A collectionGet(Collection<A> c, int idx) {
    if (c == null || idx < 0 || idx >= l(c))
      return null;
    if (c instanceof List)
      return listGet((List<A>) c, idx);
    Iterator<A> it = c.iterator();
    for (int i = 0; i < idx; i++) if (it.hasNext())
      it.next();
    else
      return null;
    return it.hasNext() ? it.next() : null;
  }

  static public String struct_noStringSharing(Object o) {
    structure_Data d = new structure_Data();
    d.noStringSharing = true;
    return structure(o, d);
  }

  static public <A extends Iterable> A pnl(String prefix, A l) {
    printNumberedLines(prefix, l);
    return l;
  }

  static public <A extends Iterable> A pnl(A l) {
    printNumberedLines(l);
    return l;
  }

  static public <A extends Map> A pnl(A map) {
    printNumberedLines(map);
    return map;
  }

  static public <A extends Map> A pnl(String prefix, A map) {
    printNumberedLines(prefix, map);
    return map;
  }

  static public <A> A[] pnl(A[] a) {
    printNumberedLines(a);
    return a;
  }

  static public String pnl(String s) {
    printNumberedLines(lines(s));
    return s;
  }

  static public List map(Iterable l, Object f) {
    return map(f, l);
  }

  static public 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 public <A, B> List<B> map(Iterable<A> l, F1<A, B> f) {
    return map(f, l);
  }

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

  static public <A, B> List<B> map(IF1<A, B> f, Iterable<A> l) {
    return map(l, f);
  }

  static public <A, B> List<B> map(Iterable<A> l, IF1<A, B> f) {
    List x = emptyList(l);
    if (l != null)
      for (A o : l) x.add(f.get(o));
    return x;
  }

  static public <A, B> List<B> map(IF1<A, B> f, A[] l) {
    return map(l, f);
  }

  static public <A, B> List<B> map(A[] l, IF1<A, B> f) {
    List x = emptyList(l);
    if (l != null)
      for (A o : l) x.add(f.get(o));
    return x;
  }

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

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

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

  static public 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 public <A, B, C> List<C> map(Map<A, B> map, IF2<A, B, C> f) {
    return map(map, (Object) f);
  }

  static public String sfu(Object o) {
    return structureForUser(o);
  }

  static volatile public boolean ping_pauseAll = false;

  static public int ping_sleep = 100;

  static volatile public boolean ping_anyActions = false;

  static public Map<Thread, Object> ping_actions = newWeakHashMap();

  static public ThreadLocal<Boolean> ping_isCleanUpThread = new ThreadLocal();

  static public boolean ping() {
    if (ping_pauseAll || ping_anyActions)
      ping_impl(true);
    return true;
  }

  static public boolean ping_impl(boolean okInCleanUp) {
    try {
      if (ping_pauseAll && !isAWTThread()) {
        do Thread.sleep(ping_sleep); while (ping_pauseAll);
        return true;
      }
      if (ping_anyActions) {
        if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
          failIfUnlicensed();
        Object action = null;
        synchronized (ping_actions) {
          if (!ping_actions.isEmpty()) {
            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 public <A> A or(A a, A b) {
    return a != null ? a : b;
  }

  static public Object call_withVarargs(Object o, String method, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        Class c = (Class) o;
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findStaticMethod(method, args);
        if (me != null)
          return invokeMethod(me, null, args);
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          methodSearch: for (Method m : methods) {
            {
              if (!(m.isVarArgs()))
                continue;
            }
            {
              if (!(isStaticMethod(m)))
                continue;
            }
            Object[] newArgs = massageArgsForVarArgsCall(m, args);
            if (newArgs != null)
              return invokeMethod(m, null, newArgs);
          }
        throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
      } else {
        Class c = o.getClass();
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(method, args);
        if (me != null)
          return invokeMethod(me, o, args);
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          methodSearch: for (Method m : methods) {
            {
              if (!(m.isVarArgs()))
                continue;
            }
            Object[] newArgs = massageArgsForVarArgsCall(m, args);
            if (newArgs != null)
              return invokeMethod(m, o, newArgs);
          }
        throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void rotateStringBuffer(StringBuffer buf, int max) {
    try {
      if (buf == null)
        return;
      synchronized (buf) {
        if (buf.length() <= max)
          return;
        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);
        }
        buf.trimToSize();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void rotateStringBuilder(StringBuilder buf, int max) {
    try {
      if (buf == null)
        return;
      synchronized (buf) {
        if (buf.length() <= max)
          return;
        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);
        }
        buf.trimToSize();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Throwable getInnerException(Throwable e) {
    if (e == null)
      return null;
    while (e.getCause() != null) e = e.getCause();
    return e;
  }

  static public Throwable getInnerException(Runnable r) {
    return getInnerException(getException(r));
  }

  static public String str(Object o) {
    return o == null ? "null" : o.toString();
  }

  static public String str(char[] c) {
    return new String(c);
  }

  static public Object collectionMutex(List l) {
    return l;
  }

  static public Object collectionMutex(Object o) {
    if (o instanceof List)
      return o;
    String c = className(o);
    if (eq(c, "java.util.TreeMap$KeySet"))
      c = className(o = getOpt(o, "m"));
    else if (eq(c, "java.util.HashMap$KeySet"))
      c = className(o = get_raw(o, "this$0"));
    if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
      c = className(o = get_raw(o, "m"));
    return o;
  }

  static public <A> AutoCloseable tempSetThreadLocal(final ThreadLocal<A> tl, A a) {
    if (tl == null)
      return null;
    final A prev = setThreadLocal(tl, a);
    return new AutoCloseable() {

      public String toString() {
        return "tl.set(prev);";
      }

      public void close() throws Exception {
        tl.set(prev);
      }
    };
  }

  static public String hideCredentials(URL url) {
    return url == null ? null : hideCredentials(str(url));
  }

  static public String hideCredentials(String url) {
    try {
      if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
        return url;
    } catch (Throwable e) {
      print("HideCredentials", e);
    }
    return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=<hidden>");
  }

  static public String hideCredentials(Object o) {
    return hideCredentials(str(o));
  }

  static public String getStackTrace(Throwable throwable) {
    lastException(throwable);
    return getStackTrace_noRecord(throwable);
  }

  static public String getStackTrace_noRecord(Throwable throwable) {
    StringWriter writer = new StringWriter();
    throwable.printStackTrace(new PrintWriter(writer));
    return hideCredentials(writer.toString());
  }

  static public String getStackTrace() {
    return getStackTrace_noRecord(new Throwable());
  }

  static public Throwable unwrapTrivialExceptionWraps(Throwable e) {
    if (e == null)
      return e;
    while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
    return e;
  }

  static public String replacePrefix(String prefix, String replacement, String s) {
    if (!startsWith(s, prefix))
      return s;
    return replacement + substring(s, l(prefix));
  }

  static public Throwable innerException2(Throwable e) {
    if (e == null)
      return null;
    while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
    return e;
  }

  static public String getProgramID() {
    return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
  }

  static public String getProgramID(Class c) {
    String id = (String) getOpt(c, "programID");
    if (nempty(id))
      return formatSnippetID(id);
    return "?";
  }

  static public String getProgramID(Object o) {
    return getProgramID(getMainClass(o));
  }

  static public <A> WeakReference<A> newWeakReference(A a) {
    return a == null ? null : new WeakReference(a);
  }

  static public ArrayList emptyList() {
    return new ArrayList();
  }

  static public ArrayList emptyList(int capacity) {
    return new ArrayList(max(0, capacity));
  }

  static public ArrayList emptyList(Iterable l) {
    return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
  }

  static public ArrayList emptyList(Object[] l) {
    return emptyList(l(l));
  }

  static public <A> ArrayList<A> emptyList(Class<A> c) {
    return new ArrayList();
  }

  static public CloseableIterableIterator<String> linesFromFile(File f) {
    try {
      if (!f.exists())
        return emptyCloseableIterableIterator();
      if (ewic(f.getName(), ".gz"))
        return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
      return linesFromReader(utf8bufferedReader(f));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public CloseableIterableIterator<String> linesFromFile(String path) {
    return linesFromFile(newFile(path));
  }

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

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

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

  static public boolean empty(Object[] o) {
    return o == null || o.length == 0;
  }

  static public 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 instanceof byte[])
      return empty((byte[]) o);
    if (o == null)
      return true;
    throw fail("unknown type for 'empty': " + getType(o));
  }

  static public boolean empty(Iterator i) {
    return i == null || !i.hasNext();
  }

  static public boolean empty(double[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(float[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(int[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(long[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(byte[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(short[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(MultiSet ms) {
    return ms == null || ms.isEmpty();
  }

  static public boolean empty(File f) {
    return getFileSize(f) == 0;
  }

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

  static public void printNumberedLines(Map map) {
    printNumberedLines(mapToLines(map));
  }

  static public void printNumberedLines(String prefix, Map map) {
    printNumberedLines(prefix, mapToLines(map));
  }

  static public <A extends Iterable> A printNumberedLines(A l) {
    int i = 0;
    if (l != null)
      for (Object a : l) print((++i) + ". " + str(a));
    return l;
  }

  static public <A extends Iterable> A printNumberedLines(String prefix, A l) {
    int i = 0;
    if (l != null)
      for (Object a : l) print(prefix + (++i) + ". " + str(a));
    return l;
  }

  static public void printNumberedLines(Object[] l) {
    printNumberedLines(asList(l));
  }

  static public void printNumberedLines(Object o) {
    printNumberedLines(lines(str(o)));
  }

  static public String structureForUser(Object o) {
    return beautifyStructure(struct_noStringSharing(o));
  }

  static public boolean isAWTThread() {
    if (isAndroid())
      return false;
    if (isHeadless())
      return false;
    return isAWTThread_awt();
  }

  static public boolean isAWTThread_awt() {
    return SwingUtilities.isEventDispatchThread();
  }

  static public void failIfUnlicensed() {
    assertTrue("license off", licensed());
  }

  static public Thread currentThread() {
    return Thread.currentThread();
  }

  static final public Map<Class, _MethodCache> callOpt_cache = newDangerousWeakHashMap();

  static public Object callOpt_cached(Object o, String methodName, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        Class c = (Class) o;
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(methodName, args);
        if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
          return null;
        return invokeMethod(me, null, args);
      } else {
        Class c = o.getClass();
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(methodName, args);
        if (me == null)
          return null;
        return invokeMethod(me, o, args);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public _MethodCache callOpt_getCache(Class c) {
    synchronized (callOpt_cache) {
      _MethodCache cache = callOpt_cache.get(c);
      if (cache == null)
        callOpt_cache.put(c, cache = new _MethodCache(c));
      return cache;
    }
  }

  static public Object invokeMethod(Method m, Object o, Object... args) {
    try {
      try {
        return m.invoke(o, args);
      } catch (InvocationTargetException e) {
        throw rethrow(getExceptionCause(e));
      } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isStaticMethod(Method m) {
    return methodIsStatic(m);
  }

  static public Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
    Class<?>[] types = m.getParameterTypes();
    int n = types.length - 1, nArgs = args.length;
    if (nArgs < n)
      return null;
    for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
      return null;
    Class varArgType = types[n].getComponentType();
    for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
      return null;
    Object[] newArgs = new Object[n + 1];
    arraycopy(args, 0, newArgs, 0, n);
    Object[] varArgs = arrayOfType(varArgType, nArgs - n);
    arraycopy(args, n, varArgs, 0, nArgs - n);
    newArgs[n] = varArgs;
    return newArgs;
  }

  static public <A> String joinWithComma(Collection<A> c) {
    return join(", ", c);
  }

  static public String joinWithComma(String... c) {
    return join(", ", c);
  }

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

  static public List<String> classNames(Collection l) {
    return getClassNames(l);
  }

  static public List<String> classNames(Object[] l) {
    return getClassNames(Arrays.asList(l));
  }

  static public Throwable getException(Runnable r) {
    try {
      callF(r);
      return null;
    } catch (Throwable e) {
      return e;
    }
  }

  static public String className(Object o) {
    return getClassName(o);
  }

  static public boolean eqOneOf(Object o, Object... l) {
    for (Object x : l) if (eq(o, x))
      return true;
    return false;
  }

  static public <A> A setThreadLocal(ThreadLocal<A> tl, A value) {
    if (tl == null)
      return null;
    A old = tl.get();
    tl.set(value);
    return old;
  }

  static public boolean startsWithOneOf(String s, String... l) {
    for (String x : l) if (startsWith(s, x))
      return true;
    return false;
  }

  static public boolean startsWithOneOf(String s, Matches m, String... l) {
    for (String x : l) if (startsWith(s, x, m))
      return true;
    return false;
  }

  static public boolean isAGIBlueDomain(String domain) {
    return domainIsUnder(domain, theAGIBlueDomain());
  }

  static public String hostNameFromURL(String url) {
    try {
      return new URL(url).getHost();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static volatile public PersistableThrowable lastException_lastException;

  static public PersistableThrowable lastException() {
    return lastException_lastException;
  }

  static public void lastException(Throwable e) {
    lastException_lastException = persistableThrowable(e);
  }

  static public boolean startsWith(String a, String b) {
    return a != null && a.startsWith(b);
  }

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

  static public boolean startsWith(String a, String b, Matches m) {
    if (!startsWith(a, b))
      return false;
    m.m = new String[] { substring(a, strL(b)) };
    return true;
  }

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

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

  static public 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 public String substring(String s, CharSequence l) {
    return substring(s, l(l));
  }

  static public boolean nempty(Collection c) {
    return !empty(c);
  }

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

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

  static public boolean nempty(byte[] o) {
    return !empty(o);
  }

  static public boolean nempty(int[] o) {
    return !empty(o);
  }

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

  static public boolean nempty(Iterator i) {
    return i != null && i.hasNext();
  }

  static public boolean nempty(Object o) {
    return !empty(o);
  }

  static public String formatSnippetIDOpt(String s) {
    return isSnippetID(s) ? formatSnippetID(s) : s;
  }

  static public String formatSnippetID(String id) {
    return "#" + parseSnippetID(id);
  }

  static public String formatSnippetID(long id) {
    return "#" + id;
  }

  static public Class getMainClass() {
    return mc();
  }

  static public Class getMainClass(Object o) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class && eq(((Class) o).getName(), "x30"))
        return (Class) o;
      return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public int max(int a, int b) {
    return Math.max(a, b);
  }

  static public int max(int a, int b, int c) {
    return max(max(a, b), c);
  }

  static public long max(int a, long b) {
    return Math.max((long) a, b);
  }

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

  static public double max(int a, double b) {
    return Math.max((double) a, b);
  }

  static public float max(float a, float b) {
    return Math.max(a, b);
  }

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

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

  static public 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 public 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 public byte max(byte[] c) {
    byte x = -128;
    for (byte d : c) if (d > x)
      x = d;
    return x;
  }

  static public short max(short[] c) {
    short x = -0x8000;
    for (short d : c) if (d > x)
      x = d;
    return x;
  }

  static public int max(int[] c) {
    int x = Integer.MIN_VALUE;
    for (int d : c) if (d > x)
      x = d;
    return x;
  }

  static public CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {

    public Object next() {
      throw fail();
    }

    public boolean hasNext() {
      return false;
    }
  };

  static public <A> CloseableIterableIterator<A> emptyCloseableIterableIterator() {
    return emptyCloseableIterableIterator_instance;
  }

  static public boolean ewic(String a, String b) {
    return endsWithIgnoreCase(a, b);
  }

  static public boolean ewic(String a, String b, Matches m) {
    return endsWithIgnoreCase(a, b, m);
  }

  static public CloseableIterableIterator<String> linesFromReader(Reader r) {
    final BufferedReader br = bufferedReader(r);
    return iteratorFromFunction_f0_autoCloseable(new F0<String>() {

      public String get() {
        try {
          return readLineFromReaderWithClose(br);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret readLineFromReaderWithClose(br);";
      }
    }, _wrapIOCloseable(r));
  }

  static public BufferedReader utf8bufferedReader(InputStream in) {
    try {
      return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedReader utf8bufferedReader(File f) {
    try {
      return utf8bufferedReader(newFileInputStream(f));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public GZIPInputStream newGZIPInputStream(File f) {
    return gzInputStream(f);
  }

  static public GZIPInputStream newGZIPInputStream(InputStream in) {
    return gzInputStream(in);
  }

  static public File newFile(File base, String... names) {
    for (String name : names) base = new File(base, name);
    return base;
  }

  static public File newFile(String name) {
    return name == null ? null : new File(name);
  }

  static public File newFile(String base, String... names) {
    return newFile(newFile(base), names);
  }

  static public String getType(Object o) {
    return getClassName(o);
  }

  static public long getFileSize(String path) {
    return path == null ? 0 : new File(path).length();
  }

  static public long getFileSize(File f) {
    return f == null ? 0 : f.length();
  }

  static public List<String> mapToLines(Map map) {
    List<String> l = new ArrayList();
    for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
    return l;
  }

  static public String mapToLines(Map map, Object f) {
    return lines(map(map, f));
  }

  static public String mapToLines(Object f, Map map) {
    return lines(map(map, f));
  }

  static public String mapToLines(Object f, Iterable l) {
    return lines(map(f, l));
  }

  static public <A> String mapToLines(Iterable<A> l, IF1<A, String> f) {
    return mapToLines((Object) f, l);
  }

  static public <A> String mapToLines(IF1<A, String> f, Iterable<A> l) {
    return mapToLines((Object) f, l);
  }

  static public <A, B> String mapToLines(Map<A, B> map, IF2<A, B, String> f) {
    return lines(map(map, f));
  }

  static public String beautifyStructure(String s) {
    List<String> tok = javaTokForStructure(s);
    structure_addTokenMarkers(tok);
    jreplace(tok, "lhm", "");
    return join(tok);
  }

  static volatile public boolean licensed_yes = true;

  static public boolean licensed() {
    if (!licensed_yes)
      return false;
    ping_okInCleanUp();
    return true;
  }

  static public void licensed_off() {
    licensed_yes = false;
  }

  static public Throwable getExceptionCause(Throwable e) {
    Throwable c = e.getCause();
    return c != null ? c : e;
  }

  static public String joinWithSpace(Iterable c) {
    return join(" ", c);
  }

  static public String joinWithSpace(String... c) {
    return join(" ", c);
  }

  static public boolean methodIsStatic(Method m) {
    return (m.getModifiers() & Modifier.STATIC) != 0;
  }

  static public boolean argumentCompatibleWithType(Object arg, Class type) {
    return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
  }

  static public void arraycopy(Object[] a, Object[] b) {
    if (a != null && b != null)
      arraycopy(a, 0, b, 0, min(a.length, b.length));
  }

  static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
    if (n != 0)
      System.arraycopy(src, srcPos, dest, destPos, n);
  }

  static public <A> A[] arrayOfType(Class<A> type, int n) {
    return makeArray(type, n);
  }

  static public <A> A[] arrayOfType(int n, Class<A> type) {
    return arrayOfType(type, n);
  }

  public static <A> String join(String glue, Iterable<A> strings) {
    if (strings == null)
      return "";
    if (strings instanceof Collection) {
      if (((Collection) strings).size() == 1)
        return str(first(((Collection) strings)));
    }
    StringBuilder buf = new StringBuilder();
    Iterator<A> 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 public <A> String join(Iterable<A> strings) {
    return join("", strings);
  }

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

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

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

  static public 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 public String getClassName(Object o) {
    return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
  }

  static public boolean domainIsUnder(String domain, String mainDomain) {
    return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
  }

  static public String theAGIBlueDomain() {
    return "agi.blue";
  }

  static public boolean nemptyString(String s) {
    return s != null && s.length() > 0;
  }

  static public int strL(String s) {
    return s == null ? 0 : s.length();
  }

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

  static public boolean neq(Object a, Object b) {
    return !eq(a, b);
  }

  public static boolean isSnippetID(String s) {
    try {
      parseSnippetID(s);
      return true;
    } catch (RuntimeException e) {
      return false;
    }
  }

  public static long parseSnippetID(String snippetID) {
    long id = Long.parseLong(shortenSnippetID(snippetID));
    if (id == 0)
      throw fail("0 is not a snippet ID");
    return id;
  }

  static public boolean endsWithIgnoreCase(String a, String b) {
    int la = l(a), lb = l(b);
    return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
  }

  static public boolean endsWithIgnoreCase(String a, String b, Matches m) {
    if (!endsWithIgnoreCase(a, b))
      return false;
    m.m = new String[] { substring(a, 0, l(a) - l(b)) };
    return true;
  }

  static public BufferedReader bufferedReader(Reader r) {
    return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
  }

  static public <A> CloseableIterableIterator<A> iteratorFromFunction_f0_autoCloseable(final F0<A> f, final AutoCloseable closeable) {
    class IFF2 extends CloseableIterableIterator<A> {

      public A a;

      public boolean done = false;

      public boolean hasNext() {
        getNext();
        return !done;
      }

      public A next() {
        getNext();
        if (done)
          throw fail();
        A _a = a;
        a = null;
        return _a;
      }

      public void getNext() {
        if (done || a != null)
          return;
        a = f.get();
        done = a == null;
      }

      public void close() throws Exception {
        if (closeable != null)
          closeable.close();
      }
    }
    ;
    return new IFF2();
  }

  static public String readLineFromReaderWithClose(BufferedReader r) {
    try {
      String s = r.readLine();
      if (s == null)
        r.close();
      return s;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
    return c == null ? null : new AutoCloseable() {

      public String toString() {
        return "c.close();\r\n    _registerIO(c, null, false);";
      }

      public void close() throws Exception {
        c.close();
        _registerIO(c, null, false);
      }
    };
  }

  static public <A> A _registerIOWrap(A wrapper, Object wrapped) {
    return wrapper;
  }

  static public FileInputStream newFileInputStream(File path) throws IOException {
    return newFileInputStream(path.getPath());
  }

  static public FileInputStream newFileInputStream(String path) throws IOException {
    FileInputStream f = new FileInputStream(path);
    _registerIO(f, path, true);
    return f;
  }

  static public int gzInputStream_defaultBufferSize = 65536;

  static public GZIPInputStream gzInputStream(File f) {
    try {
      return gzInputStream(new FileInputStream(f));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public GZIPInputStream gzInputStream(File f, int bufferSize) {
    try {
      return gzInputStream(new FileInputStream(f), bufferSize);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public GZIPInputStream gzInputStream(InputStream in) {
    return gzInputStream(in, gzInputStream_defaultBufferSize);
  }

  static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
    try {
      return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A, B> Set<A> keys(Map<A, B> map) {
    return map == null ? new HashSet() : map.keySet();
  }

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

  static public <A> Set<A> keys(MultiSet<A> ms) {
    return ms.keySet();
  }

  static public List<String> javaTokForStructure(String s) {
    return javaTok_noMLS(s);
  }

  static public String structure_addTokenMarkers(String s) {
    return join(structure_addTokenMarkers(javaTokForStructure(s)));
  }

  static public List<String> structure_addTokenMarkers(List<String> tok) {
    TreeSet<Integer> refs = new TreeSet();
    for (int i = 1; i < l(tok); i += 2) {
      String t = tok.get(i);
      if (t.startsWith("t") && isInteger(t.substring(1)))
        refs.add(parseInt(t.substring(1)));
    }
    if (empty(refs))
      return tok;
    for (int i : refs) {
      int idx = i * 2 + 1;
      if (idx >= l(tok))
        continue;
      String t = "";
      if (endsWithLetterOrDigit(tok.get(idx - 1)))
        t = " ";
      tok.set(idx, t + "m" + i + " " + tok.get(idx));
    }
    return tok;
  }

  static public String jreplace(String s, String in, String out) {
    return jreplace(s, in, out, null);
  }

  static public String jreplace(String s, String in, String out, Object condition) {
    List<String> tok = javaTok(s);
    return jreplace(tok, in, out, condition) ? join(tok) : s;
  }

  static public boolean jreplace(List<String> tok, String in, String out) {
    return jreplace(tok, in, out, false, true, null);
  }

  static public boolean jreplace(List<String> tok, String in, String out, Object condition) {
    return jreplace(tok, in, out, false, true, condition);
  }

  static public boolean jreplace(List<String> tok, String in, String out, IF2<List<String>, Integer, Boolean> condition) {
    return jreplace(tok, in, out, (Object) condition);
  }

  static public boolean jreplace(List<String> tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) {
    String[] toks = javaTokForJFind_array(in);
    int lTokin = toks.length * 2 + 1;
    boolean anyChange = false;
    int i = -1;
    for (int n = 0; n < 10000; n++) {
      i = findCodeTokens(tok, i + 1, ignoreCase, toks, condition);
      if (i < 0)
        return anyChange;
      List<String> subList = tok.subList(i - 1, i + lTokin - 1);
      String expansion = jreplaceExpandRefs(out, subList);
      int end = i + lTokin - 2;
      clearAllTokens(tok, i, end);
      tok.set(i, expansion);
      if (reTok)
        reTok(tok, i, end);
      i = end;
      anyChange = true;
    }
    throw fail("woot? 10000! " + quote(in) + " => " + quote(out));
  }

  static public boolean jreplace_debug = false;

  static public 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 public int min(int a, int b) {
    return Math.min(a, b);
  }

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

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

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

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

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

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

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

  static public short min(short[] c) {
    short x = 0x7FFF;
    for (short d : c) if (d < x)
      x = d;
    return x;
  }

  static public int min(int[] c) {
    int x = Integer.MAX_VALUE;
    for (int d : c) if (d < x)
      x = d;
    return x;
  }

  static public <A> A[] makeArray(Class<A> type, int n) {
    return (A[]) Array.newInstance(type, n);
  }

  static public Object first(Object list) {
    return first((Iterable) list);
  }

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

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

  static public <A> A first(IterableIterator<A> i) {
    return first((Iterator<A>) i);
  }

  static public <A> A first(Iterator<A> i) {
    return i == null || !i.hasNext() ? null : i.next();
  }

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

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

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

  static public Byte first(byte[] l) {
    return empty(l) ? null : l[0];
  }

  static public boolean eqic(String a, String b) {
    if ((a == null) != (b == null))
      return false;
    if (a == null)
      return true;
    return a.equalsIgnoreCase(b);
  }

  static public boolean eqic(char a, char b) {
    if (a == b)
      return true;
    char u1 = Character.toUpperCase(a);
    char u2 = Character.toUpperCase(b);
    if (u1 == u2)
      return true;
    return Character.toLowerCase(u1) == Character.toLowerCase(u2);
  }

  static public String shortenSnippetID(String snippetID) {
    if (snippetID.startsWith("#"))
      snippetID = snippetID.substring(1);
    String httpBlaBla = "http://tinybrain.de/";
    if (snippetID.startsWith(httpBlaBla))
      snippetID = snippetID.substring(httpBlaBla.length());
    return "" + parseLong(snippetID);
  }

  static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
    return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
  }

  static public void _registerIO(Object object, String path, boolean opened) {
  }

  static public List<String> javaTok_noMLS(String s) {
    ArrayList<String> tok = new ArrayList();
    int l = s == null ? 0 : s.length();
    int i = 0, n = 0;
    while (i < l) {
      int j = i;
      char c, d;
      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;
      }
      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);
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          int c2 = s.charAt(j);
          if (c2 == opener || c2 == '\n' && opener == '\'') {
            ++j;
            break;
          } else if (c2 == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else
        ++j;
      tok.add(javaTok_substringC(s, i, j));
      ++n;
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    return tok;
  }

  static public boolean isInteger(String s) {
    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 public int parseInt(String s) {
    return emptyString(s) ? 0 : Integer.parseInt(s);
  }

  static public int parseInt(char c) {
    return Integer.parseInt(str(c));
  }

  static public int javaTok_n, javaTok_elements;

  static public boolean javaTok_opt = false;

  static public List<String> javaTok(String s) {
    ++javaTok_n;
    ArrayList<String> tok = new ArrayList();
    int l = s == null ? 0 : s.length();
    int i = 0, n = 0;
    while (i < l) {
      int j = i;
      char c, d;
      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;
      }
      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);
      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) {
          int c2 = s.charAt(j);
          if (c2 == opener || c2 == '\n' && opener == '\'') {
            ++j;
            break;
          } else if (c2 == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } 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));
      ++n;
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    javaTok_elements += tok.size();
    return tok;
  }

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

  static public Map<String, String[]> javaTokForJFind_array_cache = synchronizedMRUCache(1000);

  static public String[] javaTokForJFind_array(String s) {
    String[] tok = javaTokForJFind_array_cache.get(s);
    if (tok == null)
      javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s))));
    return tok;
  }

  static public int findCodeTokens(List<String> tok, String... tokens) {
    return findCodeTokens(tok, 1, false, tokens);
  }

  static public int findCodeTokens(List<String> tok, boolean ignoreCase, String... tokens) {
    return findCodeTokens(tok, 1, ignoreCase, tokens);
  }

  static public int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String... tokens) {
    return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
  }

  static public HashSet<String> findCodeTokens_specials = lithashset("*", "<quoted>", "<id>", "<int>", "\\*");

  static public int findCodeTokens_bails, findCodeTokens_nonbails;

  static public interface findCodeTokens_Matcher {

    public boolean get(String token);
  }

  static public int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
    int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length;
    int i = startIdx | 1;
    String firstToken = tokens[0];
    if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) {
      while (i < end && !firstToken.equals(tok.get(i))) i += 2;
    }
    findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens];
    for (int j = 0; j < nTokens; j++) {
      String p = tokens[j];
      findCodeTokens_Matcher matcher;
      if (p.equals("*"))
        matcher = t -> true;
      else if (p.equals("<quoted>"))
        matcher = t -> isQuoted(t);
      else if (p.equals("<id>"))
        matcher = t -> isIdentifier(t);
      else if (p.equals("<int>"))
        matcher = t -> isInteger(t);
      else if (p.equals("\\*"))
        matcher = t -> t.equals("*");
      else if (ignoreCase)
        matcher = t -> eqic(p, t);
      else
        matcher = t -> t.equals(p);
      matchers[j] = matcher;
    }
    outer: for (; i < end; i += 2) {
      for (int j = 0; j < nTokens; j++) if (!matchers[j].get(tok.get(i + j * 2)))
        continue outer;
      if (condition == null || checkTokCondition(condition, tok, i - 1))
        return i;
    }
    return -1;
  }

  static public String jreplaceExpandRefs(String s, List<String> tokref) {
    if (!contains(s, '$'))
      return s;
    List<String> tok = javaTok(s);
    for (int i = 1; i < l(tok); i += 2) {
      String t = tok.get(i);
      if (t.startsWith("$") && isInteger(t.substring(1))) {
        String x = tokref.get(-1 + parseInt(t.substring(1)) * 2);
        tok.set(i, x);
      } else if (t.equals("\\")) {
        tok.set(i, "");
        i += 2;
      }
    }
    return join(tok);
  }

  static public void clearAllTokens(List<String> tok) {
    for (int i = 0; i < tok.size(); i++) tok.set(i, "");
  }

  static public void clearAllTokens(List<String> tok, int i, int j) {
    for (; i < j; i++) tok.set(i, "");
  }

  static public List<String> reTok(List<String> tok) {
    replaceCollection(tok, javaTok(tok));
    return tok;
  }

  static public List<String> reTok(List<String> tok, int i) {
    return reTok(tok, i, i + 1);
  }

  static public List<String> reTok(List<String> tok, int i, int j) {
    i = max(i & ~1, 0);
    j = min(l(tok), j | 1);
    if (i >= j)
      return tok;
    List<String> t = javaTok(joinSubList(tok, i, j));
    replaceListPart(tok, i, j, t);
    return tok;
  }

  static public String quote(Object o) {
    if (o == null)
      return "null";
    return quote(str(o));
  }

  static public 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 public 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 if (c == '\0')
        out.append("\\0");
      else
        out.append(c);
    }
    out.append('"');
  }

  static public String asString(Object o) {
    return o == null ? null : o.toString();
  }

  static public long parseLong(String s) {
    if (empty(s))
      return 0;
    return Long.parseLong(dropSuffix("L", s));
  }

  static public long parseLong(Object s) {
    return Long.parseLong((String) s);
  }

  static public 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 public String javaTok_substringC(String s, int i, int j) {
    return s.substring(i, j);
  }

  static public boolean emptyString(String s) {
    return s == null || s.length() == 0;
  }

  static public List<String> javaTokWithExisting(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;
      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 && javaTokWithExisting_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);
      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) {
            ++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));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } 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 && javaTokWithExisting_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 public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
    return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
  }

  static public <A, B> Map<A, B> synchronizedMRUCache(int maxSize) {
    return synchroMap(new MRUCache(maxSize));
  }

  static public String[] codeTokensAsStringArray(List<String> tok) {
    int n = max(0, (l(tok) - 1) / 2);
    String[] out = new String[n];
    for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1);
    return out;
  }

  static public int jfind(String s, String in) {
    return jfind(javaTok(s), in);
  }

  static public int jfind(List<String> tok, String in) {
    return jfind(tok, 1, in);
  }

  static public int jfind(List<String> tok, int startIdx, String in) {
    return jfind(tok, startIdx, in, null);
  }

  static public int jfind(List<String> tok, String in, Object condition) {
    return jfind(tok, 1, in, condition);
  }

  static public int jfind(List<String> tok, int startIdx, String in, Object condition) {
    return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
  }

  static public int jfind(List<String> tok, List<String> tokin) {
    return jfind(tok, 1, tokin);
  }

  static public int jfind(List<String> tok, int startIdx, List<String> tokin) {
    return jfind(tok, startIdx, tokin, null);
  }

  static public int jfind(List<String> tok, int startIdx, String[] tokinC, Object condition) {
    return findCodeTokens(tok, startIdx, false, tokinC, condition);
  }

  static public int jfind(List<String> tok, int startIdx, List<String> tokin, Object condition) {
    return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
  }

  static public List<String> jfind_preprocess(List<String> tok) {
    for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
    replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
    return tok;
  }

  static public <A> HashSet<A> lithashset(A... items) {
    HashSet<A> set = new HashSet();
    for (A a : items) set.add(a);
    return set;
  }

  static public boolean isQuoted(String s) {
    if (isNormalQuoted(s))
      return true;
    return isMultilineQuoted(s);
  }

  static public boolean isIdentifier(String s) {
    return isJavaIdentifier(s);
  }

  static public boolean checkTokCondition(Object condition, List<String> tok, int i) {
    if (condition instanceof TokCondition)
      return ((TokCondition) condition).get(tok, i);
    return checkCondition(condition, tok, i);
  }

  static public boolean contains(Collection c, Object o) {
    return c != null && c.contains(o);
  }

  static public boolean contains(Object[] x, Object o) {
    if (x != null)
      for (Object a : x) if (eq(a, o))
        return true;
    return false;
  }

  static public boolean contains(String s, char c) {
    return s != null && s.indexOf(c) >= 0;
  }

  static public boolean contains(String s, String b) {
    return s != null && s.indexOf(b) >= 0;
  }

  static public boolean contains(BitSet bs, int i) {
    return bs != null && bs.get(i);
  }

  static public <A> boolean contains(Producer<A> p, A a) {
    if (p != null && a != null)
      while (true) {
        A x = p.next();
        if (x == null)
          break;
        if (eq(x, a))
          return true;
      }
    return false;
  }

  static public <A> void replaceCollection(Collection<A> dest, Collection<A> src) {
    if (dest == src)
      return;
    dest.clear();
    dest.addAll(src);
  }

  static public String joinSubList(List<String> l, int i, int j) {
    return join(subList(l, i, j));
  }

  static public String joinSubList(List<String> l, int i) {
    return join(subList(l, i));
  }

  static public void replaceListPart(List l, int i, int j, List l2) {
    replaceSublist(l, i, j, l2);
  }

  static public String dropSuffix(String suffix, String s) {
    return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

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

  static public <A, B> Map<A, B> synchroMap(Map<A, B> map) {
    return Collections.synchronizedMap(map);
  }

  static public <A> ArrayList<A> litlist(A... a) {
    ArrayList l = new ArrayList(a.length);
    for (A x : a) l.add(x);
    return l;
  }

  static public <A> List<A> replaceSublist(List<A> l, List<A> x, List<A> y) {
    if (x == null)
      return l;
    int i = 0;
    while (true) {
      i = indexOfSubList(l, x, i);
      if (i < 0)
        break;
      replaceSublist(l, i, i + l(x), y);
      i += l(y);
    }
    return l;
  }

  static public <A> List<A> replaceSublist(List<A> l, int fromIndex, int toIndex, List<A> y) {
    int n = y.size(), toIndex_new = fromIndex + n;
    if (toIndex_new < toIndex) {
      removeSubList(l, toIndex_new, toIndex);
      copyListPart(y, 0, l, fromIndex, n);
    } else {
      copyListPart(y, 0, l, fromIndex, toIndex - fromIndex);
      if (toIndex_new > toIndex)
        l.addAll(toIndex, subList(y, toIndex - fromIndex));
    }
    return l;
  }

  static public boolean isNormalQuoted(String s) {
    int l = l(s);
    if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"'))
      return false;
    int j = 1;
    while (j < l) if (s.charAt(j) == '"')
      return j == l - 1;
    else if (s.charAt(j) == '\\' && j + 1 < l)
      j += 2;
    else
      ++j;
    return false;
  }

  static public boolean isMultilineQuoted(String s) {
    if (!startsWith(s, "["))
      return false;
    int i = 1;
    while (i < s.length() && s.charAt(i) == '=') ++i;
    return i < s.length() && s.charAt(i) == '[';
  }

  static public 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 public boolean checkCondition(Object condition, Object... args) {
    return isTrue(callF(condition, args));
  }

  static public <A> boolean checkCondition(IF1<A, Boolean> condition, A arg) {
    return isTrue(callF(condition, arg));
  }

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

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

  static public <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
    if (l == null)
      return null;
    int n = l(l);
    startIndex = Math.max(0, startIndex);
    endIndex = Math.min(n, endIndex);
    if (startIndex >= endIndex)
      return ll();
    if (startIndex == 0 && endIndex == n)
      return l;
    return l.subList(startIndex, endIndex);
  }

  static public Map synchroHashMap() {
    return Collections.synchronizedMap(new HashMap());
  }

  static public <A> int indexOfSubList(List<A> x, List<A> y) {
    return indexOfSubList(x, y, 0);
  }

  static public <A> int indexOfSubList(List<A> x, List<A> y, int i) {
    outer: for (; i + l(y) <= l(x); i++) {
      for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y.get(j)))
        continue outer;
      return i;
    }
    return -1;
  }

  static public <A> int indexOfSubList(List<A> x, A[] y, int i) {
    outer: for (; i + l(y) <= l(x); i++) {
      for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y[j]))
        continue outer;
      return i;
    }
    return -1;
  }

  static public void removeSubList(List l, int from, int to) {
    if (l != null)
      subList(l, from, to).clear();
  }

  static public void removeSubList(List l, int from) {
    if (l != null)
      subList(l, from).clear();
  }

  static public <A, B extends A> void copyListPart(List<B> a, int i1, List<A> b, int i2, int n) {
    if (a == null || b == null)
      return;
    for (int i = 0; i < n; i++) b.set(i2 + i, a.get(i1 + i));
  }

  static public char lastChar(String s) {
    return empty(s) ? '\0' : s.charAt(l(s) - 1);
  }

  final static public class _MethodCache {

    final public Class c;

    final public HashMap<String, List<Method>> cache = new HashMap();

    public _MethodCache(Class c) {
      this.c = c;
      _init();
    }

    public void _init() {
      Class _c = c;
      while (_c != null) {
        for (Method m : _c.getDeclaredMethods()) if (!reflection_isForbiddenMethod(m))
          multiMapPut(cache, m.getName(), makeAccessible(m));
        _c = _c.getSuperclass();
      }
      for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
        multiMapPut(cache, m.getName(), makeAccessible(m));
    }

    public Method findMethod(String method, Object[] args) {
      try {
        List<Method> m = cache.get(method);
        if (m == null)
          return null;
        int n = m.size();
        for (int i = 0; i < n; i++) {
          Method me = m.get(i);
          if (call_checkArgs(me, args, false))
            return me;
        }
        return null;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public Method findStaticMethod(String method, Object[] args) {
      try {
        List<Method> m = cache.get(method);
        if (m == null)
          return null;
        int n = m.size();
        for (int i = 0; i < n; i++) {
          Method me = m.get(i);
          if (isStaticMethod(me) && call_checkArgs(me, args, false))
            return me;
        }
        return null;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }
  }

  static public class MRUCache<A, B> extends LinkedHashMap<A, B> {

    public int maxSize = 10;

    public MRUCache() {
    }

    public MRUCache(int maxSize) {
      this.maxSize = maxSize;
    }

    public boolean removeEldestEntry(Map.Entry eldest) {
      return size() > maxSize;
    }

    public Object _serialize() {
      return ll(maxSize, cloneLinkedHashMap(this));
    }

    static public MRUCache _deserialize(List l) {
      MRUCache m = new MRUCache();
      m.maxSize = (int) first(l);
      m.putAll((LinkedHashMap) second(l));
      return m;
    }
  }

  static public interface IF0<A> {

    public A get();
  }

  static abstract public class CloseableIterableIterator<A> extends IterableIterator<A> implements AutoCloseable {

    public void close() throws Exception {
    }
  }

  static public interface IF2<A, B, C> {

    public C get(A a, B b);
  }

  static abstract public class TokCondition {

    abstract public boolean get(List<String> tok, int i);
  }

  static public class LineCompCompressor {

    abstract static public class Chunk {

      abstract public String text(List<Chunk> chunks);
    }

    static public class CPair extends Chunk implements IFieldsToList {

      public int i1;

      public int i2;

      public CPair() {
      }

      public CPair(int i1, int i2) {
        this.i2 = i2;
        this.i1 = i1;
      }

      public String toString() {
        return shortClassName(this) + "(" + i1 + ", " + i2 + ")";
      }

      public boolean equals(Object o) {
        if (!(o instanceof CPair))
          return false;
        CPair x = (CPair) o;
        return eq(i1, x.i1) && eq(i2, x.i2);
      }

      public int hashCode() {
        int h = 64355773;
        h = boostHashCombine(h, _hashCode(i1));
        h = boostHashCombine(h, _hashCode(i2));
        return h;
      }

      public Object[] _fieldsToList() {
        return new Object[] { i1, i2 };
      }

      public CPair(IntPair p) {
        i1 = p.a;
        i2 = p.b;
      }

      public String text(List<Chunk> chunks) {
        return linesLL_rtrim(chunks.get(i1).text(chunks), chunks.get(i2).text(chunks));
      }
    }

    static public class CPrim extends Chunk implements IFieldsToList {

      public String s;

      public CPrim() {
      }

      public CPrim(String s) {
        this.s = s;
      }

      public String toString() {
        return shortClassName(this) + "(" + s + ")";
      }

      public boolean equals(Object o) {
        if (!(o instanceof CPrim))
          return false;
        CPrim x = (CPrim) o;
        return eq(s, x.s);
      }

      public int hashCode() {
        int h = 64372105;
        h = boostHashCombine(h, _hashCode(s));
        return h;
      }

      public Object[] _fieldsToList() {
        return new Object[] { s };
      }

      public String text(List<Chunk> chunks) {
        return s;
      }
    }

    public boolean verbose = false;

    public boolean sortLines = true;

    public boolean verify = true;

    public Map<String, List<String>> textIDToLines;

    public List<String> allUniqueLines;

    public List<Chunk> chunks = new ArrayList();

    public int primChunks;

    public Map<String, Integer> lineIndex;

    public Map<Pair<String, String>, Integer> linePairIndex = new HashMap();

    public Map<String, List<Integer>> finalEncodings;

    public LineCompCompressor(Map<String, String> texts) {
      textIDToLines = mapValuesToLinkedHashMap(__38 -> lines(__38), texts);
    }

    public void run() {
      allUniqueLines = uniquify(concatLists(values(textIDToLines)));
      if (sortLines)
        sortInPlace(allUniqueLines);
      for (String line : allUniqueLines) chunks.add(new CPrim(line));
      primChunks = l(chunks);
      lineIndex = listIndex(collect("s", chunks));
      Map<String, List<Integer>> simpleEncodings = mapValues(textIDToLines, (IF1<List<String>, List<Integer>>) (lines -> map(lines, line -> lineIndex.get(line))));
      finalEncodings = repeatUntilSame(__39 -> compressPairs(__39), simpleEncodings);
      if (verbose || verify)
        printAndCheckEncodings(finalEncodings);
    }

    public void saveAsTextFile(File f) {
      String out = exportEncoding(finalEncodings);
      saveTextFile(f, out);
      if (verify)
        checkDecompression(f, textIDToLines);
    }

    public void checkDecompression(File file, Map<String, List<String>> textIDToLines) {
      BufferedReader reader = bufferedUtf8Reader(file);
      try {
        LineCompReader lcr = new LineCompReader(reader);
        assertEquals(keysList(textIDToLines), asList(lcr.versions()));
        for (String version : keys(textIDToLines)) assertEquals(lcr.textForVersion(version), lines_rtrim(textIDToLines.get(version)));
        if (verbose)
          print("Decompression OK for " + nVersions(textIDToLines));
      } finally {
        _close(reader);
      }
    }

    public String exportEncoding(Map<String, List<Integer>> encodings) {
      List<String> buf = new ArrayList();
      buf.add("LINECOMP " + primChunks);
      for (Chunk c : chunks) {
        if (c instanceof CPair)
          buf.add(((CPair) c).i1 + " " + ((CPair) c).i2);
        else
          buf.add(((CPrim) c).s);
      }
      for (String id : keys(encodings)) {
        List<Integer> l = encodings.get(id);
        buf.add(id + "=" + joinWithSpace(l));
      }
      return lines_rtrim(buf);
    }

    public Map<String, List<Integer>> compressPairs(Map<String, List<Integer>> encodings) {
      MultiSet<IntPair> pairCounts = new MultiSet();
      for (List<Integer> l : values(encodings)) {
        IntPair lastPair = null;
        for (IntPair pair : overlappingIntPairs(l)) {
          if (neq(pair, lastPair)) {
            lastPair = pair;
            pairCounts.add(pair);
          }
        }
      }
      IntPair toCompress = msMostPopularDuplicate(pairCounts);
      if (toCompress == null)
        return encodings;
      int idx = makeCPair(toCompress);
      print("Made pair: " + toCompress + " -> " + idx + ", " + (msNumberOfDuplicates(pairCounts) - 1) + " remaining");
      return mapValues(encodings, (IF1<List<Integer>, List<Integer>>) encoded -> replaceSublist(encoded, ll(toCompress.a, toCompress.b), ll(idx)));
    }

    public int makeCPair(IntPair p) {
      int idx = addAndReturnIndex(chunks, new CPair(p));
      return idx;
    }

    public void printAndCheckEncodings(Map<String, List<Integer>> encodings) {
      for (String id : keys(encodings)) {
        List<Integer> encoded = encodings.get(id);
        if (verbose)
          print(id + ": " + joinWithSpace(encoded));
        assertEquals(lines(textIDToLines.get(id)), decode(encoded));
      }
    }

    public String decode(List<Integer> encoded) {
      return lines(lambdaMap(__40 -> chunkText(__40), encoded));
    }

    public String chunkText(int idx) {
      return chunks.get(idx).text(chunks);
    }
  }

  static abstract public class IterableIterator<A> implements Iterator<A>, Iterable<A> {

    public Iterator<A> iterator() {
      return this;
    }

    public void remove() {
      unsupportedOperation();
    }
  }

  static abstract public class F2<A, B, C> {

    abstract public C get(A a, B b);
  }

  static public interface IFieldsToList {

    public Object[] _fieldsToList();
  }

  static public class LineCompReader {

    public List<String> literals = new ArrayList();

    public List<Pair<Integer, Integer>> pairs = new ArrayList();

    public LinkedHashMap<String, List<Integer>> versions = new LinkedHashMap();

    public LineCompReader(File f) {
      BufferedReader reader = utf8Reader(f);
      try {
        load(reader);
      } finally {
        _close(reader);
      }
    }

    public LineCompReader(BufferedReader reader) {
      load(reader);
    }

    public void load(BufferedReader reader) {
      try {
        String s = reader.readLine();
        Matches m = new Matches();
        if (!startsWith(s, "LINECOMP ", m))
          throw fail("Not a LINECOMP file");
        int nLiterals = parseInt(m.rest());
        for (int i = 0; i < nLiterals; i++) literals.add(assertNotNull(reader.readLine()));
        while (licensed()) {
          s = reader.readLine();
          if (s == null || contains(s, "="))
            break;
          pairs.add(assertNotNull(listToPair(parseInts(splitAtSpace(s)))));
        }
        while (contains(s, "=")) {
          int i = indexOf(s, '=');
          versions.put(takeFirst(s, i), parseInts(splitAtSpace(substring(s, i + 1))));
          s = reader.readLine();
        }
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public Set<String> versions() {
      return keys(versions);
    }

    public String getText(String version) {
      return textForVersion(version);
    }

    public String textForVersion(String version) {
      List<Integer> encoded = versions.get(version);
      if (encoded == null)
        return null;
      List<String> buf = new ArrayList();
      for (int idx : encoded) decode(idx, buf);
      return lines_rtrim(buf);
    }

    public void decode(int idx, List<String> buf) {
      if (idx < l(literals))
        buf.add(literals.get(idx));
      else {
        Pair<Integer, Integer> p = pairs.get(idx - l(literals));
        decode(p.a, buf);
        decode(p.b, buf);
      }
    }
  }

  static public class IntPair implements IFieldsToList {

    public int a;

    public int b;

    public IntPair() {
    }

    public IntPair(int a, int b) {
      this.b = b;
      this.a = a;
    }

    public String toString() {
      return shortClassName(this) + "(" + a + ", " + b + ")";
    }

    public Object[] _fieldsToList() {
      return new Object[] { a, b };
    }

    public boolean equals(Object o) {
      if (!(o instanceof IntPair))
        return false;
      IntPair x = (IntPair) o;
      return a == x.a && b == x.b;
    }

    public int hashCode() {
      int h = -672893111;
      h = boostHashCombine(h, _hashCode(a));
      h = boostHashCombine(h, _hashCode(b));
      return h;
    }
  }

  static public class Pair<A, B> implements Comparable<Pair<A, B>> {

    public A a;

    public B b;

    public Pair() {
    }

    public 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 + ">";
    }

    public int compareTo(Pair<A, B> p) {
      if (p == null)
        return 1;
      int i = ((Comparable<A>) a).compareTo(p.a);
      if (i != 0)
        return i;
      return ((Comparable<B>) b).compareTo(p.b);
    }
  }

  static public boolean reflection_isForbiddenMethod(Method m) {
    return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
  }

  static public <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 public Field makeAccessible(Field f) {
    try {
      f.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, f);
    }
    return f;
  }

  static public Method makeAccessible(Method m) {
    try {
      m.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, m);
    }
    return m;
  }

  static public Constructor makeAccessible(Constructor c) {
    try {
      c.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, c);
    }
    return c;
  }

  static public Set<Class> allInterfacesImplementedBy(Class c) {
    if (c == null)
      return null;
    HashSet<Class> set = new HashSet();
    allInterfacesImplementedBy_find(c, set);
    return set;
  }

  static public void allInterfacesImplementedBy_find(Class c, Set<Class> set) {
    if (c.isInterface() && !set.add(c))
      return;
    do {
      for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
    } while ((c = c.getSuperclass()) != null);
  }

  static public Method findMethod(Object o, String method, Object... args) {
    return findMethod_cached(o, method, args);
  }

  static public boolean findMethod_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 public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length) {
      if (debug)
        print("Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++) {
      Object arg = args[i];
      if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
        if (debug)
          print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
        return false;
      }
    }
    return true;
  }

  static public Method findStaticMethod(Class c, String method, Object... args) {
    Class _c = c;
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (!m.getName().equals(method))
          continue;
        if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
          continue;
        return m;
      }
      c = c.getSuperclass();
    }
    return null;
  }

  static public boolean findStaticMethod_checkArgs(Method m, Object[] args) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length)
      return false;
    for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
      return false;
    return true;
  }

  static public <A, B> LinkedHashMap<A, B> cloneLinkedHashMap(Map<A, B> map) {
    return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
  }

  static public <A> A second(List<A> l) {
    return get(l, 1);
  }

  static public <A> A second(Iterable<A> l) {
    if (l == null)
      return null;
    Iterator<A> it = iterator(l);
    if (!it.hasNext())
      return null;
    it.next();
    return it.hasNext() ? it.next() : null;
  }

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

  static public <A, B> B second(Pair<A, B> p) {
    return p == null ? null : p.b;
  }

  static public <A> A second(Producer<A> p) {
    if (p == null)
      return null;
    if (p.next() == null)
      return null;
    return p.next();
  }

  static public char second(String s) {
    return charAt(s, 1);
  }

  static public 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 public int boostHashCombine(int a, int b) {
    return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
  }

  static public int _hashCode(Object a) {
    return a == null ? 0 : a.hashCode();
  }

  static public String linesLL_rtrim(Object... x) {
    return lines_rtrim(ll(x));
  }

  static public LinkedHashMap mapValuesToLinkedHashMap(Object func, Map map) {
    LinkedHashMap m = new LinkedHashMap();
    for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
    return m;
  }

  static public <A, B, C> LinkedHashMap<A, C> mapValuesToLinkedHashMap(Map<A, B> map, IF1<B, C> f) {
    return mapValuesToLinkedHashMap(f, map);
  }

  static public <A, B, C> LinkedHashMap<A, C> mapValuesToLinkedHashMap(IF1<B, C> f, Map<A, B> map) {
    return mapValuesToLinkedHashMap((Object) f, map);
  }

  static public LinkedHashMap mapValuesToLinkedHashMap(Map map, Object func) {
    return mapValuesToLinkedHashMap(func, map);
  }

  static public <A> List<A> uniquify(Collection<A> l) {
    return uniquifyList(l);
  }

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

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

  static public <A, B> Collection<B> values(Map<A, B> map) {
    return map == null ? emptyList() : map.values();
  }

  static public Collection values(Object map) {
    return values((Map) map);
  }

  static public <A> List<A> sortInPlace(List<A> l, final Object comparator) {
    return sortedInPlace(l, comparator);
  }

  static public <A> List<A> sortInPlace(List<A> l) {
    return sortedInPlace(l);
  }

  static public Map<String, Integer> listIndex(List<String> l) {
    Map<String, Integer> map = new HashMap();
    for (int i = 0; i < l(l); i++) map.put(l.get(i), i);
    return map;
  }

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

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

  static public Map mapValues(Object func, Map map) {
    Map m = similarEmptyMap(map);
    for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
    return m;
  }

  static public <A, B, C> Map<A, C> mapValues(Map<A, B> map, IF1<B, C> f) {
    return mapValues(f, map);
  }

  static public <A, B, C> Map<A, C> mapValues(IF1<B, C> f, Map<A, B> map) {
    return mapValues((Object) f, map);
  }

  static public Map mapValues(Map map, Object func) {
    return mapValues(func, map);
  }

  static public <A> A repeatUntilSame(IF1<A, A> f, A o) {
    return applyUntilSame(f, o);
  }

  static public File saveTextFile(String fileName, String contents) throws IOException {
    CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
    try {
      File file = new File(fileName);
      mkdirsForFile(file);
      String tempFileName = fileName + "_temp";
      File tempFile = new File(tempFileName);
      if (contents != null) {
        if (tempFile.exists())
          try {
            String saveName = tempFileName + ".saved." + now();
            copyFile(tempFile, new File(saveName));
          } catch (Throwable e) {
            printStackTrace(e);
          }
        FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
        PrintWriter printWriter = new PrintWriter(outputStreamWriter);
        printWriter.print(contents);
        printWriter.close();
      }
      if (file.exists() && !file.delete())
        throw new IOException("Can't delete " + fileName);
      if (contents != null)
        if (!tempFile.renameTo(file))
          throw new IOException("Can't rename " + tempFile + " to " + file);
      vmBus_send("wroteFile", file);
      return file;
    } finally {
      action.done();
    }
  }

  static public File saveTextFile(File fileName, String contents) {
    try {
      saveTextFile(fileName.getPath(), contents);
      return fileName;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedReader bufferedUtf8Reader(InputStream in) {
    return utf8BufferedReader(in);
  }

  static public BufferedReader bufferedUtf8Reader(File f) {
    return utf8BufferedReader(f);
  }

  static public <A> A assertEquals(Object x, A y) {
    return assertEquals(null, x, y);
  }

  static public <A> A assertEquals(String msg, Object x, A y) {
    if (assertVerbose())
      return assertEqualsVerbose(msg, x, y);
    if (!(x == null ? y == null : x.equals(y)))
      throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
    return y;
  }

  static public <A, B> List<A> keysList(Map<A, B> map) {
    return cloneListSynchronizingOn(keys(map), map);
  }

  static public <A> List<A> keysList(MultiSet<A> ms) {
    return ms == null ? null : keysList(ms.map);
  }

  static public String lines_rtrim(Collection lines) {
    return rtrim_fromLines(lines);
  }

  static public String nVersions(long n) {
    return n2(n, "version");
  }

  static public String nVersions(Collection l) {
    return nVersions(l(l));
  }

  static public String nVersions(Map map) {
    return nVersions(l(map));
  }

  static public List<IntPair> overlappingIntPairs(List<Integer> l) {
    List<IntPair> out = new ArrayList();
    Iterator<Integer> it = iterator(l);
    if (!it.hasNext())
      return out;
    int a = it.next();
    while (it.hasNext()) {
      int b = it.next();
      out.add(new IntPair(a, b));
      a = b;
    }
    return out;
  }

  static public <A> A msMostPopularDuplicate(MultiSet<A> ms) {
    A a = msMostPopularEntry(ms);
    return a != null && ms.get(a) > 1 ? a : null;
  }

  static public <A> int msNumberOfDuplicates(MultiSet<A> ms) {
    if (ms == null)
      return 0;
    return countPred(keys(ms), a -> ms.get(a) > 1);
  }

  static public <A> int addAndReturnIndex(List<A> l, A a) {
    if (l == null)
      return -1;
    int idx = l.size();
    l.add(a);
    return idx;
  }

  static public <A, B> List<B> lambdaMap(IF1<A, B> f, Iterable<A> l) {
    return map(l, f);
  }

  static public <A> Iterator<A> iterator(Iterable<A> c) {
    return c == null ? emptyIterator() : c.iterator();
  }

  static public UnsupportedOperationException unsupportedOperation() {
    throw new UnsupportedOperationException();
  }

  static public BufferedReader utf8Reader(InputStream in) {
    return utf8BufferedReader(in);
  }

  static public BufferedReader utf8Reader(File f) {
    return utf8BufferedReader(f);
  }

  static public Object load(String varName) {
    readLocally(varName);
    return get(mc(), varName);
  }

  static public Object load(String progID, String varName) {
    readLocally(progID, varName);
    return get(mc(), varName);
  }

  static public <A> A assertNotNull(A a) {
    assertTrue(a != null);
    return a;
  }

  static public <A> A assertNotNull(String msg, A a) {
    assertTrue(msg, a != null);
    return a;
  }

  static public <A> Pair<A, A> listToPair(List<A> l) {
    return l(l) != 2 ? null : pair(first(l), second(l));
  }

  static public List<Integer> parseInts(Iterable<String> l) {
    return lambdaMap(__41 -> parseInt(__41), l);
  }

  static public List<String> splitAtSpace(String s) {
    return empty(s) ? emptyList() : asList(s.split("\\s+"));
  }

  static public <A> List<A> takeFirst(List<A> l, int n) {
    return l(l) <= n ? l : newSubListOrSame(l, 0, n);
  }

  static public <A> List<A> takeFirst(int n, List<A> l) {
    return takeFirst(l, n);
  }

  static public String takeFirst(int n, String s) {
    return substring(s, 0, n);
  }

  static public String takeFirst(String s, int n) {
    return substring(s, 0, n);
  }

  static public <A> List<A> takeFirst(int n, Iterable<A> i) {
    if (i == null)
      return null;
    List l = new ArrayList();
    Iterator<A> it = i.iterator();
    for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
      if (it.hasNext())
        l.add(it.next());
      else
        break;
    }
    return l;
  }

  static public int hashCodeFor(Object a) {
    return a == null ? 0 : a.hashCode();
  }

  static public void vmBus_send(String msg, Object... args) {
    Object arg = vmBus_wrapArgs(args);
    pcallFAll(vm_busListeners_live(), msg, arg);
    pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
  }

  static public void vmBus_send(String msg) {
    vmBus_send(msg, (Object) null);
  }

  static public Method findMethod_cached(Object o, String method, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        _MethodCache cache = callOpt_getCache(((Class) o));
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
            return m;
        return null;
      } else {
        _MethodCache cache = callOpt_getCache(o.getClass());
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          for (Method m : methods) if (findMethod_checkArgs(m, args, false))
            return m;
        return null;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public char charAt(String s, int i) {
    return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
  }

  static public 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 public <A> List<A> uniquifyList(Collection<A> l) {
    if (l == null)
      return null;
    if (l(l) < 2)
      return asList(l);
    HashSet<A> set = new HashSet();
    List<A> out = new ArrayList();
    for (A a : l) if (set.add(a))
      out.add(a);
    return out;
  }

  static public <A> List<A> sortedInPlace(List<A> l, final Object comparator) {
    sort(l, makeComparator(comparator));
    return l;
  }

  static public <A> List<A> sortedInPlace(List<A> l) {
    sort(l);
    return l;
  }

  static public List collectField(Iterable c, String field) {
    List l = new ArrayList();
    if (c != null)
      for (Object a : c) l.add(getOpt(a, field));
    return l;
  }

  static public List collectField(String field, Iterable c) {
    return collectField(c, field);
  }

  static public Map similarEmptyMap(Map m) {
    if (m instanceof TreeMap)
      return new TreeMap(((TreeMap) m).comparator());
    if (m instanceof LinkedHashMap)
      return new LinkedHashMap();
    return new HashMap();
  }

  static public <A> A applyUntilSame(IF1<A, A> f, A o) {
    while (licensed()) {
      A o2 = f.get(o);
      if (o == o2)
        break;
      o = o2;
    }
    return o;
  }

  static public List<CriticalAction> beginCriticalAction_inFlight = synchroList();

  static public class CriticalAction {

    public String description;

    public CriticalAction() {
    }

    public CriticalAction(String description) {
      this.description = description;
    }

    public void done() {
      beginCriticalAction_inFlight.remove(this);
    }
  }

  static public CriticalAction beginCriticalAction(String description) {
    ping();
    CriticalAction c = new CriticalAction(description);
    beginCriticalAction_inFlight.add(c);
    return c;
  }

  static public void cleanMeUp_beginCriticalAction() {
    int n = 0;
    while (nempty(beginCriticalAction_inFlight)) {
      int m = l(beginCriticalAction_inFlight);
      if (m != n) {
        n = m;
        try {
          print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
      sleepInCleanUp(10);
    }
  }

  public static File mkdirsForFile(File file) {
    File dir = file.getParentFile();
    if (dir != null) {
      dir.mkdirs();
      if (!dir.isDirectory())
        if (dir.isFile())
          throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
        else
          throw fail("Unknown IO exception during mkdirs of " + f2s(file));
    }
    return file;
  }

  public static String mkdirsForFile(String path) {
    mkdirsForFile(new File(path));
    return path;
  }

  static public long now_virtualTime;

  static public long now() {
    return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
  }

  static public File copyFile(File src, File dest) {
    try {
      FileInputStream inputStream = new FileInputStream(src.getPath());
      FileOutputStream outputStream = newFileOutputStream(dest.getPath());
      try {
        copyStream(inputStream, outputStream);
        inputStream.close();
      } finally {
        outputStream.close();
      }
      return dest;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A extends Throwable> A printStackTrace(A e) {
    print(getStackTrace(e));
    return e;
  }

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

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

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

  static public FileOutputStream newFileOutputStream(File path) throws IOException {
    return newFileOutputStream(path.getPath());
  }

  static public FileOutputStream newFileOutputStream(String path) throws IOException {
    return newFileOutputStream(path, false);
  }

  static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
    return newFileOutputStream(path.getPath(), append);
  }

  static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
    mkdirsForFile(path);
    FileOutputStream f = new FileOutputStream(path, append);
    _registerIO(f, path, true);
    return f;
  }

  static public BufferedReader utf8BufferedReader(InputStream in) {
    return utf8bufferedReader(in);
  }

  static public BufferedReader utf8BufferedReader(File f) {
    return utf8bufferedReader(f);
  }

  static public ThreadLocal<Boolean> assertVerbose_value = new ThreadLocal();

  static public void assertVerbose(boolean b) {
    assertVerbose_value.set(b);
  }

  static public boolean assertVerbose() {
    return isTrue(assertVerbose_value.get());
  }

  static public <A> A assertEqualsVerbose(Object x, A y) {
    assertEqualsVerbose((String) null, x, y);
    return y;
  }

  static public <A> A assertEqualsVerbose(String msg, Object x, A y) {
    if (!eq(x, y)) {
      throw fail((msg != null ? msg + ": " : "") + "expected: " + x + ", got: " + y);
    } else
      print("OK: " + (x));
    return y;
  }

  static public <A> ArrayList<A> cloneListSynchronizingOn(Collection<A> l, Object mutex) {
    if (l == null)
      return new ArrayList();
    synchronized (mutex) {
      return new ArrayList<A>(l);
    }
  }

  static public String rtrim_fromLines(Collection lines) {
    StringBuilder buf = new StringBuilder();
    if (lines != null) {
      boolean first = true;
      for (Object line : lines) {
        if (first)
          first = false;
        else
          buf.append('\n');
        buf.append(str(line));
      }
    }
    return buf.toString();
  }

  static public String n2(long l) {
    return formatWithThousands(l);
  }

  static public String n2(Collection l) {
    return n2(l(l));
  }

  static public String n2(Map map) {
    return n2(l(map));
  }

  static public String n2(double l, String singular) {
    return n2(l, singular, singular + "s");
  }

  static public String n2(double l, String singular, String plural) {
    if (fraction(l) == 0)
      return n2((long) l, singular, plural);
    else
      return l + " " + plural;
  }

  static public String n2(long l, String singular, String plural) {
    return n_fancy2(l, singular, plural);
  }

  static public String n2(long l, String singular) {
    return n_fancy2(l, singular, singular + "s");
  }

  static public String n2(Collection l, String singular) {
    return n2(l(l), singular);
  }

  static public String n2(Collection l, String singular, String plural) {
    return n_fancy2(l, singular, plural);
  }

  static public String n2(Map m, String singular, String plural) {
    return n_fancy2(m, singular, plural);
  }

  static public String n2(Map m, String singular) {
    return n2(l(m), singular);
  }

  static public String n2(Object[] a, String singular) {
    return n2(l(a), singular);
  }

  static public String n2(Object[] a, String singular, String plural) {
    return n_fancy2(a, singular, plural);
  }

  static public String n2(MultiSet ms, String singular, String plural) {
    return n_fancy2(ms, singular, plural);
  }

  static public <A> A msMostPopularEntry(MultiSet<A> ms) {
    return ms == null ? null : ms.getMostPopularEntry();
  }

  static public int countPred(Iterable c, Object pred) {
    return nfilter(c, pred);
  }

  static public int countPred(Object pred, Iterable c) {
    return nfilter(pred, c);
  }

  static public <A> int countPred(Iterable<A> c, IF1<A, Boolean> pred) {
    return nfilter(c, pred);
  }

  static public Iterator emptyIterator() {
    return Collections.emptyIterator();
  }

  static public void readLocally(String progID, String varNames) {
    readLocally2(mc(), progID, varNames);
  }

  static public void readLocally(String varNames) {
    readLocally2(mc(), programID(), varNames);
  }

  static public void readLocally2(Object obj, String varNames) {
    readLocally2(obj, programID(), varNames);
  }

  static public int readLocally_stringLength;

  static public ThreadLocal<Boolean> readLocally2_allDynamic = new ThreadLocal();

  static public ThreadLocal readLocally2_classFinder = new ThreadLocal();

  static public void readLocally2(Object obj, String progID, String varNames) {
    try {
      boolean allDynamic = isTrue(getAndClearThreadLocal(readLocally2_allDynamic));
      for (String variableName : javaTokC(varNames)) {
        File textFile = new File(programDir(progID), variableName + ".text");
        String value = loadTextFile(textFile);
        if (value != null)
          set(main.class, variableName, value);
        else {
          File structureFile = new File(programDir(progID), variableName + ".structure");
          value = loadTextFile(structureFile);
          if (value == null) {
            File structureGZFile = new File(programDir(progID), variableName + ".structure.gz");
            if (!structureGZFile.isFile())
              return;
            InputStream fis = new FileInputStream(structureGZFile);
            try {
              GZIPInputStream gis = newGZIPInputStream(fis);
              InputStreamReader reader = new InputStreamReader(gis, "UTF-8");
              BufferedReader bufferedReader = new BufferedReader(reader);
              Object o = unstructure_tok(javaTokC_noMLS_onReader(bufferedReader), allDynamic, readLocally2_classFinder.get());
              readLocally_set(obj, variableName, o);
              return;
            } finally {
              _close(fis);
            }
          }
          readLocally_stringLength = l(value);
          if (nempty(value))
            readLocally_set(obj, variableName, unstructure(value, allDynamic, readLocally2_classFinder.get()));
        }
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void readLocally_set(Object c, String varName, Object value) {
    Object oldValue = get(c, varName);
    if (oldValue instanceof List && !(oldValue instanceof ArrayList) && value != null) {
      value = synchroList((List) value);
    }
    set(c, varName, value);
  }

  static public <A, B> Pair<A, B> pair(A a, B b) {
    return new Pair(a, b);
  }

  static public <A> Pair<A, A> pair(A a) {
    return new Pair(a, a);
  }

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

  static public <A> List<A> newSubListOrSame(List<A> l, int startIndex, int endIndex) {
    if (l == null)
      return null;
    int n = l(l);
    startIndex = max(0, startIndex);
    endIndex = min(n, endIndex);
    if (startIndex >= endIndex)
      return ll();
    if (startIndex == 0 && endIndex == n)
      return l;
    return cloneList(l.subList(startIndex, endIndex));
  }

  static public Object vmBus_wrapArgs(Object... args) {
    return empty(args) ? null : l(args) == 1 ? args[0] : args;
  }

  static public void pcallFAll(Collection l, Object... args) {
    if (l != null)
      for (Object f : cloneList(l)) pcallF(f, args);
  }

  static public void pcallFAll(Iterator it, Object... args) {
    while (it.hasNext()) pcallF(it.next(), args);
  }

  static public Set vm_busListeners_live_cache;

  static public Set vm_busListeners_live() {
    if (vm_busListeners_live_cache == null)
      vm_busListeners_live_cache = vm_busListeners_live_load();
    return vm_busListeners_live_cache;
  }

  static public Set vm_busListeners_live_load() {
    return vm_generalIdentityHashSet("busListeners");
  }

  static public Map<String, Set> vm_busListenersByMessage_live_cache;

  static public Map<String, Set> vm_busListenersByMessage_live() {
    if (vm_busListenersByMessage_live_cache == null)
      vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
    return vm_busListenersByMessage_live_cache;
  }

  static public Map<String, Set> vm_busListenersByMessage_live_load() {
    return vm_generalHashMap("busListenersByMessage");
  }

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

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

  static public <A> int lastIndexOf(List<A> l, int i, A a) {
    if (l == null)
      return -1;
    for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a))
      return i;
    return -1;
  }

  static public <T> void sort(T[] a, Comparator<? super T> c) {
    Arrays.sort(a, c);
  }

  static public <T> void sort(T[] a) {
    Arrays.sort(a);
  }

  static public void sort(int[] a) {
    if (a != null)
      Arrays.sort(a);
  }

  static public <T> void sort(List<T> a, Comparator<? super T> c) {
    Collections.sort(a, c);
  }

  static public void sort(List a) {
    Collections.sort(a);
  }

  static public Comparator makeComparator(final Object f) {
    if (f instanceof Comparator)
      return (Comparator) f;
    return new Comparator() {

      public int compare(Object a, Object b) {
        return (Integer) callF(f, a, b);
      }
    };
  }

  static public void sleepInCleanUp(long ms) {
    try {
      if (ms < 0)
        return;
      Thread.sleep(ms);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String f2s(File f) {
    return f == null ? null : f.getAbsolutePath();
  }

  static public String f2s(String s) {
    return f2s(newFile(s));
  }

  static public String f2s(java.nio.file.Path p) {
    return p == null ? null : f2s(p.toFile());
  }

  static public void copyStream(InputStream in, OutputStream out) {
    try {
      byte[] buf = new byte[65536];
      while (true) {
        int n = in.read(buf);
        if (n <= 0)
          return;
        out.write(buf, 0, n);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String formatWithThousands(long l) {
    return formatWithThousandsSeparator(l);
  }

  static public double fraction(double d) {
    return d % 1;
  }

  static public String n_fancy2(long l, String singular, String plural) {
    return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
  }

  static public String n_fancy2(Collection l, String singular, String plural) {
    return n_fancy2(l(l), singular, plural);
  }

  static public String n_fancy2(Map m, String singular, String plural) {
    return n_fancy2(l(m), singular, plural);
  }

  static public String n_fancy2(Object[] a, String singular, String plural) {
    return n_fancy2(l(a), singular, plural);
  }

  static public String n_fancy2(MultiSet ms, String singular, String plural) {
    return n_fancy2(l(ms), singular, plural);
  }

  static public <A> int nfilter(Iterable<A> c, IF1<A, Boolean> pred) {
    return nfilter(pred, c);
  }

  static public <A> int nfilter(IF1<A, Boolean> pred, Iterable<A> c) {
    int n = 0;
    if (c != null)
      for (A o : c) if (pred.get(o))
        ++n;
    return n;
  }

  static public int nfilter(Iterable c, Object pred) {
    int n = 0;
    if (c != null)
      for (Object o : c) if (isTrue(callF(pred, o)))
        ++n;
    return n;
  }

  static public int nfilter(Object pred, Iterable c) {
    return nfilter(c, pred);
  }

  static public <A> A getAndClearThreadLocal(ThreadLocal<A> tl) {
    A a = tl.get();
    tl.set(null);
    return a;
  }

  static public 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;
      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);
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          if (s.charAt(j) == opener || s.charAt(j) == '\n') {
            ++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));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } 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 public File programDir_mine;

  static public File programDir() {
    return programDir(getProgramID());
  }

  static public File programDir(String snippetID) {
    boolean me = sameSnippetID(snippetID, programID());
    if (programDir_mine != null && me)
      return programDir_mine;
    File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
    if (me) {
      String c = caseID();
      if (nempty(c))
        dir = newFile(dir, c);
    }
    return dir;
  }

  static public File programDir(String snippetID, String subPath) {
    return new File(programDir(snippetID), subPath);
  }

  static public String loadTextFile(String fileName) {
    return loadTextFile(fileName, null);
  }

  static public String loadTextFile(File f, String defaultContents) {
    try {
      checkFileNotTooBigToRead(f);
      if (f == null || !f.exists())
        return defaultContents;
      FileInputStream fileInputStream = new FileInputStream(f);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
      return loadTextFile(inputStreamReader);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String loadTextFile(File fileName) {
    return loadTextFile(fileName, null);
  }

  static public String loadTextFile(String fileName, String defaultContents) {
    return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
  }

  static public String loadTextFile(Reader reader) throws IOException {
    StringBuilder builder = new StringBuilder();
    try {
      char[] buffer = new char[1024];
      int n;
      while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
    } finally {
      reader.close();
    }
    return str(builder);
  }

  static public <A> A set(A o, String field, Object value) {
    if (o == null)
      return null;
    if (o instanceof Class)
      set((Class) o, field, value);
    else
      try {
        Field f = set_findField(o.getClass(), field);
        makeAccessible(f);
        smartSet(f, o, value);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    return o;
  }

  static public void set(Class c, String field, Object value) {
    if (c == null)
      return;
    try {
      Field f = set_findStaticField(c, field);
      makeAccessible(f);
      smartSet(f, null, value);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  static public Field set_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 public Field set_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 public Object unstructure(String text) {
    return unstructure(text, false);
  }

  static public Object unstructure(String text, final boolean allDynamic) {
    return unstructure(text, allDynamic, null);
  }

  static public int structure_internStringsLongerThan = 50;

  static public int unstructure_unquoteBufSize = 100;

  static public int unstructure_tokrefs;

  abstract static public class unstructure_Receiver {

    abstract public void set(Object o);
  }

  static public Object unstructure(String text, boolean allDynamic, Object classFinder) {
    if (text == null)
      return null;
    return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
  }

  static public Object unstructure_reader(BufferedReader reader) {
    return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
  }

  static public Object unstructure_tok(final Producer<String> tok, final boolean allDynamic, final Object _classFinder) {
    final boolean debug = unstructure_debug;
    final class X {

      public int i = -1;

      final public Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();

      public HashMap<Integer, Object> refs = new HashMap();

      public HashMap<Integer, Object> tokrefs = new HashMap();

      public HashSet<String> concepts = new HashSet();

      public HashMap<String, Class> classesMap = new HashMap();

      public List<Runnable> stack = new ArrayList();

      public String curT;

      public char[] unquoteBuf = new char[unstructure_unquoteBufSize];

      public Class findAClass(String fullClassName) {
        return classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
      }

      public String unquote(String s) {
        return unquoteUsingCharArray(s, unquoteBuf);
      }

      public String t() {
        return curT;
      }

      public String tpp() {
        String t = curT;
        consume();
        return t;
      }

      public void parse(final unstructure_Receiver out) {
        String t = t();
        int refID = 0;
        if (structure_isMarker(t, 0, l(t))) {
          refID = parseInt(t.substring(1));
          consume();
        }
        final int _refID = refID;
        final int tokIndex = i;
        parse_inner(refID, tokIndex, new unstructure_Receiver() {

          public void set(Object o) {
            if (_refID != 0)
              refs.put(_refID, o);
            if (o != null)
              tokrefs.put(tokIndex, o);
            out.set(o);
          }
        });
      }

      public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
        String t = t();
        Class c = classesMap.get(t);
        if (c == null) {
          if (t.startsWith("\"")) {
            String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
            out.set(s);
            return;
          }
          if (t.startsWith("'")) {
            out.set(unquoteCharacter(tpp()));
            return;
          }
          if (t.equals("bigint")) {
            out.set(parseBigInt());
            return;
          }
          if (t.equals("d")) {
            out.set(parseDouble());
            return;
          }
          if (t.equals("fl")) {
            out.set(parseFloat());
            return;
          }
          if (t.equals("sh")) {
            consume();
            t = tpp();
            if (t.equals("-")) {
              t = tpp();
              out.set((short) (-parseInt(t)));
              return;
            }
            out.set((short) parseInt(t));
            return;
          }
          if (t.equals("-")) {
            consume();
            t = tpp();
            out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
            return;
          }
          if (isInteger(t) || isLongConstant(t)) {
            consume();
            if (isLongConstant(t)) {
              out.set(parseLong(t));
              return;
            }
            long l = parseLong(t);
            boolean isInt = l == (int) l;
            out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
            return;
          }
          if (t.equals("false") || t.equals("f")) {
            consume();
            out.set(false);
            return;
          }
          if (t.equals("true") || t.equals("t")) {
            consume();
            out.set(true);
            return;
          }
          if (t.equals("-")) {
            consume();
            t = tpp();
            out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
            return;
          }
          if (isInteger(t) || isLongConstant(t)) {
            consume();
            if (isLongConstant(t)) {
              out.set(parseLong(t));
              return;
            }
            long l = parseLong(t);
            boolean isInt = l == (int) l;
            out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
            return;
          }
          if (t.equals("File")) {
            consume();
            File f = new File(unquote(tpp()));
            out.set(f);
            return;
          }
          if (t.startsWith("r") && isInteger(t.substring(1))) {
            consume();
            int ref = Integer.parseInt(t.substring(1));
            Object o = refs.get(ref);
            if (o == null)
              throw fail("unsatisfied back reference " + ref);
            out.set(o);
            return;
          }
          if (t.startsWith("t") && isInteger(t.substring(1))) {
            consume();
            int ref = Integer.parseInt(t.substring(1));
            Object o = tokrefs.get(ref);
            if (o == null)
              throw fail("unsatisfied token reference " + ref + " at " + tokIndex);
            out.set(o);
            return;
          }
          if (t.equals("hashset")) {
            parseHashSet(out);
            return;
          }
          if (t.equals("lhs")) {
            parseLinkedHashSet(out);
            return;
          }
          if (t.equals("treeset")) {
            parseTreeSet(out);
            return;
          }
          if (t.equals("ciset")) {
            parseCISet(out);
            return;
          }
          if (eqOneOf(t, "hashmap", "hm")) {
            consume();
            parseMap(new HashMap(), out);
            return;
          }
          if (t.equals("lhm")) {
            consume();
            parseMap(new LinkedHashMap(), out);
            return;
          }
          if (t.equals("tm")) {
            consume();
            parseMap(new TreeMap(), out);
            return;
          }
          if (t.equals("cimap")) {
            consume();
            parseMap(ciMap(), out);
            return;
          }
          if (t.equals("ll")) {
            consume();
            {
              parseList(new LinkedList(), out);
              return;
            }
          }
          if (t.equals("syncLL")) {
            consume();
            {
              parseList(synchroLinkedList(), out);
              return;
            }
          }
          if (t.equals("sync")) {
            consume();
            {
              parse(new unstructure_Receiver() {

                public void set(Object value) {
                  if (value instanceof Map) {
                    if (value instanceof NavigableMap) {
                      out.set(Collections.synchronizedNavigableMap((NavigableMap) value));
                      return;
                    }
                    if (value instanceof SortedMap) {
                      out.set(Collections.synchronizedSortedMap((SortedMap) value));
                      return;
                    }
                    {
                      out.set(Collections.synchronizedMap((Map) value));
                      return;
                    }
                  } else {
                    out.set(Collections.synchronizedList((List) value));
                    return;
                  }
                }
              });
              return;
            }
          }
          if (t.equals("{")) {
            parseMap(out);
            return;
          }
          if (t.equals("[")) {
            this.parseList(new ArrayList(), out);
            return;
          }
          if (t.equals("bitset")) {
            parseBitSet(out);
            return;
          }
          if (t.equals("array") || t.equals("intarray") || t.equals("dblarray")) {
            parseArray(out);
            return;
          }
          if (t.equals("ba")) {
            consume();
            String hex = unquote(tpp());
            out.set(hexToBytes(hex));
            return;
          }
          if (t.equals("boolarray")) {
            consume();
            int n = parseInt(tpp());
            String hex = unquote(tpp());
            out.set(boolArrayFromBytes(hexToBytes(hex), n));
            return;
          }
          if (t.equals("class")) {
            out.set(parseClass());
            return;
          }
          if (t.equals("l")) {
            parseLisp(out);
            return;
          }
          if (t.equals("null")) {
            consume();
            out.set(null);
            return;
          }
          if (eq(t, "c")) {
            consume();
            t = t();
            assertTrue(isJavaIdentifier(t));
            concepts.add(t);
          }
          if (eq(t, "cu")) {
            consume();
            t = tpp();
            assertTrue(isJavaIdentifier(t));
            String fullClassName = "main$" + t;
            Class _c = findAClass(fullClassName);
            if (_c == null)
              throw fail("Class not found: " + fullClassName);
            parse(new unstructure_Receiver() {

              public void set(Object value) {
                out.set(call(_c, "_deserialize", value));
              }
            });
            return;
          }
        }
        if (eq(t, "j")) {
          consume("j");
          out.set(parseJava());
          return;
        }
        if (c == null && !isJavaIdentifier(t))
          throw new RuntimeException("Unknown token " + (i + 1) + ": " + quote(t));
        consume();
        String className, fullClassName;
        if (eq(t(), ".")) {
          consume();
          className = fullClassName = t + "." + assertIdentifier(tpp());
        } else {
          className = t;
          fullClassName = "main$" + t;
        }
        if (c == null) {
          if (allDynamic)
            c = null;
          else
            c = findAClass(fullClassName);
          if (c != null)
            classesMap.put(className, c);
        }
        boolean hasBracket = eq(t(), "(");
        if (hasBracket)
          consume();
        boolean hasOuter = hasBracket && eq(t(), "this$1");
        DynamicObject dO = null;
        Object o = null;
        final String thingName = t;
        if (c != null) {
          o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c);
          if (o instanceof DynamicObject)
            dO = (DynamicObject) o;
        } else {
          if (concepts.contains(t) && (c = findAClass("main$Concept")) != null)
            o = dO = (DynamicObject) nuEmptyObject(c);
          else
            dO = new DynamicObject();
          dO.className = className;
        }
        if (refID != 0)
          refs.put(refID, o != null ? o : dO);
        tokrefs.put(tokIndex, o != null ? o : dO);
        final LinkedHashMap<String, Object> fields = new LinkedHashMap();
        final Object _o = o;
        final DynamicObject _dO = dO;
        if (hasBracket) {
          stack.add(new Runnable() {

            public void run() {
              try {
                if (eq(t(), ","))
                  consume();
                if (eq(t(), ")")) {
                  consume(")");
                  objRead(_o, _dO, fields, hasOuter);
                  out.set(_o != null ? _o : _dO);
                } else {
                  final String key = unquote(tpp());
                  String t = tpp();
                  if (!eq(t, "="))
                    throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName);
                  stack.add(this);
                  parse(new unstructure_Receiver() {

                    public void set(Object value) {
                      fields.put(key, value);
                    }
                  });
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "ifdef unstructure_debug\r\n            print(\"in object values, token: \" + t())...";
            }
          });
        } else {
          objRead(o, dO, fields, hasOuter);
          out.set(o != null ? o : dO);
        }
      }

      public void objRead(Object o, DynamicObject dO, Map<String, Object> fields, boolean hasOuter) {
        if (o != null) {
          if (dO != null) {
            setOptAllDyn(dO, fields);
          } else {
            setOptAll_pcall(o, fields);
          }
          if (hasOuter)
            fixOuterRefs(o);
        } else
          for (Map.Entry<String, Object> e : fields.entrySet()) setDynObjectValue(dO, intern(e.getKey()), e.getValue());
        if (o != null)
          pcallOpt_noArgs(o, "_doneLoading");
      }

      public void parseSet(final Set set, final unstructure_Receiver out) {
        this.parseList(new ArrayList(), new unstructure_Receiver() {

          public void set(Object o) {
            set.addAll((List) o);
            out.set(set);
          }
        });
      }

      public void parseLisp(final unstructure_Receiver out) {
        throw fail("class Lisp not included");
      }

      public void parseBitSet(final unstructure_Receiver out) {
        consume("bitset");
        consume("{");
        final BitSet bs = new BitSet();
        stack.add(new Runnable() {

          public void run() {
            try {
              if (eq(t(), "}")) {
                consume("}");
                out.set(bs);
              } else {
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    bs.set((Integer) o);
                    if (eq(t(), ","))
                      consume();
                  }
                });
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(bs);\r\n       ...";
          }
        });
      }

      public void parseList(final List list, final unstructure_Receiver out) {
        tokrefs.put(i, list);
        consume("[");
        stack.add(new Runnable() {

          public void run() {
            try {
              if (eq(t(), "]")) {
                consume();
                out.set(list);
              } else {
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    list.add(o);
                    if (eq(t(), ","))
                      consume();
                  }
                });
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (eq(t(), \"]\")) {\r\n          consume();\r\n          ifdef unstructure_debug\r...";
          }
        });
      }

      public void parseArray(final unstructure_Receiver out) {
        final String type = tpp();
        consume("{");
        final List list = new ArrayList();
        stack.add(new Runnable() {

          public void run() {
            try {
              if (eq(t(), "}")) {
                consume("}");
                out.set(type.equals("intarray") ? toIntArray(list) : type.equals("dblarray") ? toDoubleArray(list) : list.toArray());
              } else {
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    list.add(o);
                    if (eq(t(), ","))
                      consume();
                  }
                });
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(\r\n           ...";
          }
        });
      }

      public Object parseClass() {
        consume("class");
        consume("(");
        String name = unquote(tpp());
        consume(")");
        Class c = allDynamic ? null : findAClass(name);
        if (c != null)
          return c;
        DynamicObject dO = new DynamicObject();
        dO.className = "java.lang.Class";
        name = dropPrefix("main$", name);
        dO.fieldValues.put("name", name);
        return dO;
      }

      public Object parseBigInt() {
        consume("bigint");
        consume("(");
        String val = tpp();
        if (eq(val, "-"))
          val = "-" + tpp();
        consume(")");
        return new BigInteger(val);
      }

      public Object parseDouble() {
        consume("d");
        consume("(");
        String val = unquote(tpp());
        consume(")");
        return Double.parseDouble(val);
      }

      public Object parseFloat() {
        consume("fl");
        String val;
        if (eq(t(), "(")) {
          consume("(");
          val = unquote(tpp());
          consume(")");
        } else {
          val = unquote(tpp());
        }
        return Float.parseFloat(val);
      }

      public void parseHashSet(unstructure_Receiver out) {
        consume("hashset");
        parseSet(new HashSet(), out);
      }

      public void parseLinkedHashSet(unstructure_Receiver out) {
        consume("lhs");
        parseSet(new LinkedHashSet(), out);
      }

      public void parseTreeSet(unstructure_Receiver out) {
        consume("treeset");
        parseSet(new TreeSet(), out);
      }

      public void parseCISet(unstructure_Receiver out) {
        consume("ciset");
        parseSet(ciSet(), out);
      }

      public void parseMap(unstructure_Receiver out) {
        parseMap(new TreeMap(), out);
      }

      public Object parseJava() {
        String j = unquote(tpp());
        Matches m = new Matches();
        if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
          return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
        else {
          warn("Unknown Java object: " + j);
          return null;
        }
      }

      public void parseMap(final Map map, final unstructure_Receiver out) {
        consume("{");
        stack.add(new Runnable() {

          public boolean v = false;

          public Object key;

          public void run() {
            if (v) {
              v = false;
              stack.add(this);
              if (!eq(tpp(), "="))
                throw fail("= expected, got " + t() + " in map of size " + l(map));
              parse(new unstructure_Receiver() {

                public void set(Object value) {
                  map.put(key, value);
                  if (eq(t(), ","))
                    consume();
                }
              });
            } else {
              if (eq(t(), "}")) {
                consume("}");
                out.set(map);
              } else {
                v = true;
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    key = o;
                  }
                });
              }
            }
          }
        });
      }

      public void consume() {
        curT = tok.next();
        ++i;
      }

      public void consume(String s) {
        if (!eq(t(), s)) {
          throw fail(quote(s) + " expected, got " + quote(t()));
        }
        consume();
      }

      public void parse_initial(unstructure_Receiver out) {
        consume();
        parse(out);
        while (nempty(stack)) popLast(stack).run();
      }
    }
    Boolean b = DynamicObject_loading.get();
    DynamicObject_loading.set(true);
    try {
      final Var v = new Var();
      X x = new X();
      x.parse_initial(new unstructure_Receiver() {

        public void set(Object o) {
          v.set(o);
        }
      });
      unstructure_tokrefs = x.tokrefs.size();
      return v.get();
    } finally {
      DynamicObject_loading.set(b);
    }
  }

  static public boolean unstructure_debug = false;

  static public Producer<String> javaTokC_noMLS_onReader(final BufferedReader r) {
    final class X implements Producer<String> {

      public StringBuilder buf = new StringBuilder();

      public char c, d, e = 'x';

      public X() {
        nc();
        nc();
        nc();
      }

      public void nc() {
        try {
          c = d;
          d = e;
          if (e == '\0')
            return;
          int i = r.read();
          e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public void ncSave() {
        if (c != '\0') {
          buf.append(c);
          nc();
        }
      }

      public String next() {
        while (c != '\0') {
          if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
            nc();
          else if (c == '/' && d == '*') {
            do nc(); while (c != '\0' && !(c == '*' && d == '/'));
            nc();
            nc();
          } else if (c == '/' && d == '/') {
            do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
          } else
            break;
        }
        if (c == '\0')
          return null;
        if (c == '\'' || c == '"') {
          char opener = c;
          ncSave();
          while (c != '\0') {
            if (c == opener || c == '\n') {
              ncSave();
              break;
            } else if (c == '\\') {
              ncSave();
              ncSave();
            } else
              ncSave();
          }
        } else if (Character.isJavaIdentifierStart(c))
          do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\'');
        else if (Character.isDigit(c)) {
          do ncSave(); while (Character.isDigit(c));
          if (c == 'L')
            ncSave();
        } else
          ncSave();
        String t = buf.toString();
        buf.setLength(0);
        return t;
      }
    }
    return new X();
  }

  static public Object pcallF(Object f, Object... args) {
    return pcallFunction(f, args);
  }

  static public <A> A pcallF(F0<A> f) {
    try {
      return f == null ? null : f.get();
    } catch (Throwable __e) {
      return null;
    }
  }

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

  static public <A> void pcallF(VF1<A> f, A a) {
    try {
      if (f != null)
        f.get(a);
    } catch (Throwable __e) {
      _handleException(__e);
    }
  }

  static public String formatWithThousandsSeparator(long l) {
    return NumberFormat.getInstance(new Locale("en_US")).format(l);
  }

  static public String trim(String s) {
    return s == null ? null : s.trim();
  }

  static public String trim(StringBuilder buf) {
    return buf.toString().trim();
  }

  static public String trim(StringBuffer buf) {
    return buf.toString().trim();
  }

  static public boolean sameSnippetID(String a, String b) {
    if (!isSnippetID(a) || !isSnippetID(b))
      return false;
    return parseSnippetID(a) == parseSnippetID(b);
  }

  static public File javaxDataDir_dir;

  static public File javaxDataDir() {
    return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
  }

  static public File javaxDataDir(String... subs) {
    return newFile(javaxDataDir(), subs);
  }

  static volatile public String caseID_caseID;

  static public String caseID() {
    return caseID_caseID;
  }

  static public void caseID(String id) {
    caseID_caseID = id;
  }

  static public ThreadLocal<VF1<File>> checkFileNotTooBigToRead_tl = new ThreadLocal();

  static public void checkFileNotTooBigToRead(File f) {
    callF(checkFileNotTooBigToRead_tl.get(), f);
  }

  static public void smartSet(Field f, Object o, Object value) throws Exception {
    try {
      f.set(o, value);
    } catch (Exception e) {
      Class type = f.getType();
      if (type == int.class && value instanceof Long)
        value = ((Long) value).intValue();
      if (type == LinkedHashMap.class && value instanceof Map) {
        f.set(o, asLinkedHashMap((Map) value));
        return;
      }
      try {
        if (f.getType() == Concept.Ref.class) {
          f.set(o, ((Concept) o).new Ref((Concept) value));
          return;
        }
        if (o instanceof Concept.Ref) {
          f.set(o, ((Concept.Ref) o).get());
          return;
        }
      } catch (Throwable _e) {
      }
      throw e;
    }
  }

  static public Producer<String> javaTokC_noMLS_iterator(final String s) {
    return javaTokC_noMLS_iterator(s, 0);
  }

  static public Producer<String> javaTokC_noMLS_iterator(final String s, final int startIndex) {
    return new Producer<String>() {

      final public int l = s.length();

      public int i = startIndex;

      public String next() {
        if (i >= l)
          return null;
        int j = i;
        char c, d;
        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)
          return null;
        c = s.charAt(i);
        d = i + 1 >= l ? '\0' : s.charAt(i + 1);
        if (c == '\'' || c == '"') {
          char opener = c;
          ++j;
          while (j < l) {
            if (s.charAt(j) == opener || s.charAt(j) == '\n') {
              ++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)));
        else if (Character.isDigit(c)) {
          do ++j; while (j < l && Character.isDigit(s.charAt(j)));
          if (j < l && s.charAt(j) == 'L')
            ++j;
        } else
          ++j;
        String t = quickSubstring(s, i, j);
        i = j;
        return t;
      }
    };
  }

  static public String unquoteUsingCharArray(String s, char[] buf) {
    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();
        if (l > buf.length)
          return unquote(s);
        int n = 0;
        for (int i = 1; i < l; i++) {
          char ch = s.charAt(i);
          if (ch == '\\') {
            char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
            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++;
                }
              }
              buf[n++] = (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;
              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);
                char[] x = Character.toChars(code);
                int lx = x.length;
                for (int j = 0; j < lx; j++) buf[n++] = x[j];
                i += 5;
                continue;
              default:
                ch = nextChar;
            }
            i++;
          }
          buf[n++] = ch;
        }
        return new String(buf, 0, n);
      }
    }
    return s;
  }

  static public boolean structure_isMarker(String s, int i, int j) {
    if (i >= j)
      return false;
    if (s.charAt(i) != 'm')
      return false;
    ++i;
    while (i < j) {
      char c = s.charAt(i);
      if (c < '0' || c > '9')
        return false;
      ++i;
    }
    return true;
  }

  static public String internIfLongerThan(String s, int l) {
    return s == null ? null : l(s) >= l ? intern(s) : s;
  }

  static public 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);
            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;
              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;
            }
            i++;
          }
          sb.append(ch);
        }
        return sb.toString();
      }
    }
    return s;
  }

  static public char unquoteCharacter(String s) {
    assertTrue(s.startsWith("'") && s.length() > 1);
    return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0);
  }

  static public BigInteger parseBigInt(String s) {
    return new BigInteger(s);
  }

  static public double parseDouble(String s) {
    return Double.parseDouble(s);
  }

  static public float parseFloat(String s) {
    return Float.parseFloat(s);
  }

  static public boolean isLongConstant(String s) {
    if (!s.endsWith("L"))
      return false;
    s = s.substring(0, l(s) - 1);
    return isInteger(s);
  }

  static public <A> TreeMap<String, A> ciMap() {
    return caseInsensitiveMap();
  }

  static public List parseList(String s) {
    return (List) safeUnstructure(s);
  }

  static public <A> List<A> synchroLinkedList() {
    return Collections.synchronizedList(new LinkedList<A>());
  }

  static public byte[] hexToBytes(String s) {
    if (odd(l(s)))
      throw fail("Hex string has odd length: " + quote(shorten(10, s)));
    int n = l(s) / 2;
    byte[] bytes = new byte[n];
    for (int i = 0; i < n; i++) {
      int a = parseHexChar(s.charAt(i * 2));
      int b = parseHexChar(s.charAt(i * 2 + 1));
      if (a < 0 || b < 0)
        throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s));
      bytes[i] = (byte) ((a << 4) | b);
    }
    return bytes;
  }

  static public boolean[] boolArrayFromBytes(byte[] a, int n) {
    boolean[] b = new boolean[n];
    int m = min(n, l(a) * 8);
    for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0;
    return b;
  }

  static public String assertIdentifier(String s) {
    return assertIsIdentifier(s);
  }

  static public String assertIdentifier(String msg, String s) {
    return assertIsIdentifier(msg, s);
  }

  static public <A> A nuStubInnerObject(Class<A> c) {
    return nuStubInnerObject(c, null);
  }

  static public <A> A nuStubInnerObject(Class<A> c, Object classFinder) {
    try {
      Class outerType = getOuterClass(c, classFinder);
      Constructor m = c.getDeclaredConstructor(outerType);
      makeAccessible(m);
      return (A) m.newInstance(new Object[] { null });
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Map<Class, Constructor> nuEmptyObject_cache = newDangerousWeakHashMap();

  static public <A> A nuEmptyObject(Class<A> c) {
    try {
      Constructor ctr;
      synchronized (nuEmptyObject_cache) {
        ctr = nuEmptyObject_cache.get(c);
        if (ctr == null) {
          nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
          makeAccessible(ctr);
        }
      }
      try {
        return (A) ctr.newInstance();
      } catch (InstantiationException e) {
        if (empty(e.getMessage()))
          if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
            throw fail("Can't instantiate abstract class " + className(c), e);
          else
            throw fail("Can't instantiate " + className(c), e);
        else
          throw rethrow(e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Constructor nuEmptyObject_findConstructor(Class c) {
    for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0)
      return m;
    throw fail("No default constructor declared in " + c.getName());
  }

  static public void setOptAllDyn(DynamicObject o, Map<String, Object> fields) {
    if (fields == null)
      return;
    HashMap<String, Field> fieldMap = instanceFieldsMap(o);
    for (Map.Entry<String, Object> e : fields.entrySet()) {
      String field = e.getKey();
      Object val = e.getValue();
      boolean has = fieldMap.containsKey(field);
      if (has)
        setOpt(o, field, val);
      else {
        o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, intern(field), val);
      }
    }
  }

  static public void setOptAll_pcall(Object o, Map<String, Object> fields) {
    if (fields == null)
      return;
    for (String field : keys(fields)) try {
      setOpt(o, field, fields.get(field));
    } catch (Throwable __e) {
      print(exceptionToStringShort(__e));
    }
  }

  static public void setOptAll_pcall(Object o, Object... values) {
    warnIfOddCount(values);
    for (int i = 0; i + 1 < l(values); i += 2) {
      String field = (String) values[i];
      Object value = values[i + 1];
      try {
        setOpt(o, field, value);
      } catch (Throwable __e) {
        print(exceptionToStringShort(__e));
      }
    }
  }

  static public void fixOuterRefs(Object o) {
    try {
      if (o == null)
        return;
      Field[] l = thisDollarOneFields(o.getClass());
      if (l.length <= 1)
        return;
      Object father = null;
      for (Field f : l) {
        father = f.get(o);
        if (father != null)
          break;
      }
      if (father == null)
        return;
      for (Field f : l) f.set(o, father);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void setDynObjectValue(DynamicObject o, String field, Object value) {
    o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, field, value);
  }

  static public String intern(String s) {
    return fastIntern(s);
  }

  static public void pcallOpt_noArgs(Object o, String method) {
    try {
      callOpt_noArgs(o, method);
    } catch (Throwable __e) {
      _handleException(__e);
    }
  }

  static public int[] toIntArray(Collection<Integer> l) {
    int[] a = new int[l(l)];
    int i = 0;
    if (a.length != 0)
      for (int x : l) a[i++] = x;
    return a;
  }

  static public double[] toDoubleArray(Collection<Double> l) {
    double[] a = new double[l(l)];
    int i = 0;
    if (a.length != 0)
      for (double x : l) a[i++] = x;
    return a;
  }

  static public String dropPrefix(String prefix, String s) {
    return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
  }

  static public TreeSet<String> ciSet() {
    return caseInsensitiveSet();
  }

  static public boolean jmatch(String pat, String s) {
    return jmatch(pat, s, null);
  }

  static public boolean jmatch(String pat, String s, Matches matches) {
    if (s == null)
      return false;
    return jmatch(pat, javaTok(s), matches);
  }

  static public boolean jmatch(String pat, List<String> toks) {
    return jmatch(pat, toks, null);
  }

  static public boolean jmatch(String pat, List<String> toks, Matches matches) {
    List<String> tokpat = javaTok(pat);
    String[] m = match2(tokpat, toks);
    if (m == null)
      return false;
    else {
      if (matches != null)
        matches.m = m;
      return true;
    }
  }

  static public Object nuObject(String className, Object... args) {
    try {
      return nuObject(classForName(className), args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A nuObject(Class<A> c, Object... args) {
    try {
      if (args.length == 0)
        return nuObjectWithoutArguments(c);
      Constructor m = nuObject_findConstructor(c, args);
      makeAccessible(m);
      return (A) m.newInstance(args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Constructor nuObject_findConstructor(Class c, Object... args) {
    for (Constructor m : c.getDeclaredConstructors()) {
      if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
        continue;
      return m;
    }
    throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
  }

  static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
    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 public boolean warn_on = true;

  static public ThreadLocal<List<String>> warn_warnings = new ThreadLocal();

  static public void warn(String s) {
    if (warn_on)
      print("Warning: " + s);
  }

  static public void warn(String s, List<String> warnings) {
    warn(s);
    if (warnings != null)
      warnings.add(s);
    addToCollection(warn_warnings.get(), s);
  }

  static public <A> A popLast(List<A> l) {
    return liftLast(l);
  }

  static public <A> List<A> popLast(int n, List<A> l) {
    return liftLast(n, l);
  }

  static public Object pcallFunction(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable __e) {
      _handleException(__e);
    }
    return null;
  }

  static public String _userHome;

  static public String userHome() {
    if (_userHome == null)
      return actualUserHome();
    return _userHome;
  }

  static public File userHome(String path) {
    return new File(userDir(), path);
  }

  static public <A, B> LinkedHashMap<A, B> asLinkedHashMap(Map<A, B> map) {
    if (map instanceof LinkedHashMap)
      return (LinkedHashMap) map;
    LinkedHashMap<A, B> m = new LinkedHashMap();
    if (map != null)
      synchronized (collectionMutex(map)) {
        m.putAll(map);
      }
    return m;
  }

  static public String quickSubstring(String s, int i, int j) {
    if (i == j)
      return "";
    return s.substring(i, j);
  }

  static public boolean endsWith(String a, String b) {
    return a != null && a.endsWith(b);
  }

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

  static public boolean endsWith(String a, String b, Matches m) {
    if (!endsWith(a, b))
      return false;
    m.m = new String[] { dropLast(l(b), a) };
    return true;
  }

  static public <A> TreeMap<String, A> caseInsensitiveMap() {
    return new TreeMap(caseInsensitiveComparator());
  }

  static public Object safeUnstructure(String s) {
    return unstructure(s, true);
  }

  static public boolean odd(int i) {
    return (i & 1) != 0;
  }

  static public boolean odd(long i) {
    return (i & 1) != 0;
  }

  static public boolean odd(BigInteger i) {
    return odd(toInt(i));
  }

  static public int shorten_default = 100;

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

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

  static public 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 public String shorten(int max, String s) {
    return shorten(s, max);
  }

  static public int parseHexChar(char c) {
    if (c >= '0' && c <= '9')
      return charDiff(c, '0');
    if (c >= 'a' && c <= 'f')
      return charDiff(c, 'a') + 10;
    if (c >= 'A' && c <= 'F')
      return charDiff(c, 'A') + 10;
    return -1;
  }

  static public String assertIsIdentifier(String s) {
    if (!isIdentifier(s))
      throw fail("Not an identifier: " + quote(s));
    return s;
  }

  static public String assertIsIdentifier(String msg, String s) {
    if (!isIdentifier(s))
      throw fail(msg + " - Not an identifier: " + quote(s));
    return s;
  }

  static public Class getOuterClass(Class c) {
    return getOuterClass(c, null);
  }

  static public Class getOuterClass(Class c, Object classFinder) {
    try {
      String s = c.getName();
      int i = s.lastIndexOf('$');
      String name = substring(s, 0, i);
      if (classFinder != null)
        return (Class) callF(classFinder, name);
      return Class.forName(name);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public HashMap<String, Field> instanceFieldsMap(Object o) {
    Class c = o.getClass();
    HashMap<String, Field> map;
    synchronized (getOpt_cache) {
      map = getOpt_cache.get(c);
      if (map == null)
        map = getOpt_makeCache(c);
    }
    return map;
  }

  static public <A, B> LinkedHashMap<A, B> syncMapPut2_createLinkedHashMap(LinkedHashMap<A, B> map, A key, B value) {
    if (key != null)
      if (value != null) {
        if (map == null)
          map = new LinkedHashMap();
        synchronized (collectionMutex(map)) {
          map.put(key, value);
        }
      } else if (map != null)
        synchronized (collectionMutex(map)) {
          map.remove(key);
        }
    return map;
  }

  static public String exceptionToStringShort(Throwable e) {
    lastException(e);
    e = getInnerException(e);
    String msg = hideCredentials(unnull(e.getMessage()));
    if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
      return baseClassName(e) + prependIfNempty(": ", msg);
    else
      return msg;
  }

  static public void warnIfOddCount(Object... list) {
    if (odd(l(list)))
      printStackTrace("Odd list size: " + list);
  }

  static public Map<Class, Field[]> thisDollarOneFields_cache = newDangerousWeakHashMap();

  static public Field[] thisDollarOneFields(Class c) {
    synchronized (thisDollarOneFields_cache) {
      Field[] l = thisDollarOneFields_cache.get(c);
      if (l == null)
        thisDollarOneFields_cache.put(c, l = thisDollarOneFields_uncached(c));
      return l;
    }
  }

  static public Field[] thisDollarOneFields_uncached(Class c) {
    List<Field> fields = new ArrayList();
    do {
      for (Field f : c.getDeclaredFields()) if (f.getName().equals("this$1"))
        fields.add(makeAccessible(f));
      c = c.getSuperclass();
    } while (c != null);
    return toArray(new Field[l(fields)], fields);
  }

  static public Method fastIntern_method;

  static public String fastIntern(String s) {
    try {
      if (s == null)
        return null;
      if (fastIntern_method == null) {
        fastIntern_method = findMethodNamed(javax(), "internPerProgram");
        if (fastIntern_method == null)
          upgradeJavaXAndRestart();
      }
      return (String) fastIntern_method.invoke(null, s);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Map<Class, HashMap<String, Method>> callOpt_noArgs_cache = newDangerousWeakHashMap();

  static public Object callOpt_noArgs(Object o, String method) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class)
        return callOpt(o, method);
      Class c = o.getClass();
      HashMap<String, Method> map;
      synchronized (callOpt_noArgs_cache) {
        map = callOpt_noArgs_cache.get(c);
        if (map == null)
          map = callOpt_noArgs_makeCache(c);
      }
      Method m = map.get(method);
      return m != null ? m.invoke(o) : null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public HashMap<String, Method> callOpt_noArgs_makeCache(Class c) {
    HashMap<String, Method> map = new HashMap();
    Class _c = c;
    do {
      for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0 && !reflection_isForbiddenMethod(m)) {
        makeAccessible(m);
        String name = m.getName();
        if (!map.containsKey(name))
          map.put(name, m);
      }
      _c = _c.getSuperclass();
    } while (_c != null);
    callOpt_noArgs_cache.put(c, map);
    return map;
  }

  static public TreeSet<String> caseInsensitiveSet() {
    return caseInsensitiveSet_treeSet();
  }

  static public TreeSet<String> caseInsensitiveSet(Collection<String> c) {
    return caseInsensitiveSet_treeSet(c);
  }

  static public String[] match2(List<String> pat, List<String> tok) {
    int i = pat.indexOf("...");
    if (i < 0)
      return match2_match(pat, tok);
    pat = new ArrayList<String>(pat);
    pat.set(i, "*");
    while (pat.size() < tok.size()) {
      pat.add(i, "*");
      pat.add(i + 1, "");
    }
    return match2_match(pat, tok);
  }

  static public String[] match2_match(List<String> pat, List<String> tok) {
    List<String> result = new ArrayList<String>();
    if (pat.size() != tok.size()) {
      return null;
    }
    for (int i = 1; i < pat.size(); i += 2) {
      String p = pat.get(i), t = tok.get(i);
      if (eq(p, "*"))
        result.add(t);
      else if (!equalsIgnoreCase(unquote(p), unquote(t)))
        return null;
    }
    return result.toArray(new String[result.size()]);
  }

  static public Map<String, Class> classForName_cache = synchroHashMap();

  static public Class classForName(String name) {
    try {
      if (classForName_cache == null)
        return Class.forName(name);
      Class c = classForName_cache.get(name);
      if (c == null)
        classForName_cache.put(name, c = Class.forName(name));
      return c;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Map<Class, Constructor> nuObjectWithoutArguments_cache = newDangerousWeakHashMap();

  static public Object nuObjectWithoutArguments(String className) {
    try {
      return nuObjectWithoutArguments(classForName(className));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A nuObjectWithoutArguments(Class<A> c) {
    try {
      if (nuObjectWithoutArguments_cache == null)
        return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
      Constructor m = nuObjectWithoutArguments_cache.get(c);
      if (m == null)
        nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
      return (A) m.newInstance();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Constructor nuObjectWithoutArguments_findConstructor(Class c) {
    for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
      makeAccessible(m);
      return m;
    }
    throw fail("No default constructor found in " + c.getName());
  }

  static public List<Class> getClasses(Object[] array) {
    List<Class> l = emptyList(l(array));
    for (Object o : array) l.add(_getClass(o));
    return l;
  }

  static public <A> boolean addToCollection(Collection<A> c, A a) {
    return c != null && c.add(a);
  }

  static public <A> A liftLast(List<A> l) {
    if (empty(l))
      return null;
    int i = l(l) - 1;
    A a = l.get(i);
    l.remove(i);
    return a;
  }

  static public <A> List<A> liftLast(int n, List<A> l) {
    int i = l(l) - n;
    List<A> part = cloneSubList(l, i);
    removeSubList(l, i);
    return part;
  }

  static public class getOpt_Map extends WeakHashMap {

    public getOpt_Map() {
      if (getOpt_special == null)
        getOpt_special = new HashMap();
      clear();
    }

    public void clear() {
      super.clear();
      put(Class.class, getOpt_special);
      put(String.class, getOpt_special);
    }
  }

  static final public Map<Class, HashMap<String, Field>> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));

  static public HashMap getOpt_special;

  static public 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 Map)
          return ((Map) o).get(field);
      }
      Field f = map.get(field);
      if (f != null)
        return f.get(o);
      if (o instanceof DynamicObject)
        return mapGet2(((DynamicObject) o).fieldValues, field);
      return null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public HashMap<String, Field> getOpt_makeCache(Class c) {
    HashMap<String, Field> map;
    if (isSubtypeOf(c, Map.class))
      map = getOpt_special;
    else {
      map = new HashMap();
      if (!reflection_classesNotToScan().contains(c.getName())) {
        Class _c = c;
        do {
          for (Field f : _c.getDeclaredFields()) {
            makeAccessible(f);
            String name = f.getName();
            if (!map.containsKey(name))
              map.put(name, f);
          }
          _c = _c.getSuperclass();
        } while (_c != null);
      }
    }
    if (getOpt_cache != null)
      getOpt_cache.put(c, map);
    return map;
  }

  static public Object callFunction(Object f, Object... args) {
    return callF(f, args);
  }

  static public String actualUserHome_value;

  static public String actualUserHome() {
    if (actualUserHome_value == null) {
      if (isAndroid())
        actualUserHome_value = "/storage/emulated/0/";
      else
        actualUserHome_value = System.getProperty("user.home");
    }
    return actualUserHome_value;
  }

  static public File actualUserHome(String sub) {
    return newFile(new File(actualUserHome()), sub);
  }

  static public File userDir() {
    return new File(userHome());
  }

  static public File userDir(String path) {
    return new File(userHome(), path);
  }

  static public 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 public <A> List<A> dropLast(List<A> l) {
    return subList(l, 0, l(l) - 1);
  }

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

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

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

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

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

  static public Comparator<String> caseInsensitiveComparator() {
    return betterCIComparator();
  }

  static public int toInt(Object o) {
    if (o == null)
      return 0;
    if (o instanceof Number)
      return ((Number) o).intValue();
    if (o instanceof String)
      return parseInt(((String) o));
    if (o instanceof Boolean)
      return boolToInt(((Boolean) o));
    throw fail("woot not int: " + getClassName(o));
  }

  static public int toInt(long l) {
    if (l != (int) l)
      throw fail("Too large for int: " + l);
    return (int) l;
  }

  static public int charDiff(char a, char b) {
    return (int) a - (int) b;
  }

  static public int charDiff(String a, char b) {
    return charDiff(stringToChar(a), b);
  }

  static public String unnull(String s) {
    return s == null ? "" : s;
  }

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

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

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

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

  static public <A> A[] unnull(A[] a) {
    return a == null ? (A[]) emptyObjectArray() : a;
  }

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

  static public Pt unnull(Pt p) {
    return p == null ? new Pt() : p;
  }

  static public <A, B> Pair<A, B> unnull(Pair<A, B> p) {
    return p != null ? p : new Pair(null, null);
  }

  static public String baseClassName(String className) {
    return substring(className, className.lastIndexOf('.') + 1);
  }

  static public String baseClassName(Object o) {
    return baseClassName(getClassName(o));
  }

  static public String prependIfNempty(String prefix, String s) {
    return empty(s) ? s : prefix + s;
  }

  static public Object[] toArray(Collection c) {
    return toObjectArray(c);
  }

  static public <A> A[] toArray(Iterable<A> c, Class<A> type) {
    A[] a = arrayOfType(l(c), type);
    if (a.length == 0)
      return a;
    asList(c).toArray(a);
    return a;
  }

  static public <A> A[] toArray(A[] array, Collection c) {
    if (array == null || c == null)
      return null;
    asList(c).toArray(array);
    return array;
  }

  static public Method findMethodNamed(Object obj, String method) {
    if (obj == null)
      return null;
    if (obj instanceof Class)
      return findMethodNamed((Class) obj, method);
    return findMethodNamed(obj.getClass(), method);
  }

  static public Method findMethodNamed(Class c, String method) {
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) {
        makeAccessible(m);
        return m;
      }
      c = c.getSuperclass();
    }
    return null;
  }

  static public void upgradeJavaXAndRestart() {
    run("#1001639");
    restart();
    sleep();
  }

  static public TreeSet<String> caseInsensitiveSet_treeSet() {
    return new TreeSet(caseInsensitiveComparator());
  }

  static public TreeSet<String> caseInsensitiveSet_treeSet(Collection<String> c) {
    return toCaseInsensitiveSet_treeSet(c);
  }

  static public boolean equalsIgnoreCase(String a, String b) {
    return eqic(a, b);
  }

  static public boolean equalsIgnoreCase(char a, char b) {
    return eqic(a, b);
  }

  static public Class<?> _getClass(String name) {
    try {
      return Class.forName(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public Class _getClass(Object o) {
    return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
  }

  static public Class _getClass(Object realm, String name) {
    try {
      return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public <A> List<A> cloneSubList(List<A> l, int startIndex, int endIndex) {
    return newSubList(l, startIndex, endIndex);
  }

  static public <A> List<A> cloneSubList(List<A> l, int startIndex) {
    return newSubList(l, startIndex);
  }

  static public void clear(Collection c) {
    if (c != null)
      c.clear();
  }

  static public void clear(Map map) {
    if (map != null)
      map.clear();
  }

  static public <A, B> void put(Map<A, B> map, A a, B b) {
    if (map != null)
      map.put(a, b);
  }

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

  static public List<Pair> _registerDangerousWeakMap_preList;

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

  static public <A> A _registerDangerousWeakMap(A map, Object init) {
    callF(init, map);
    if (init instanceof String) {
      final String f = (String) init;
      init = new VF1<Map>() {

        public void get(Map map) {
          try {
            callMC(f, map);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "callMC(f, map)";
        }
      };
    }
    if (javax() == null) {
      if (_registerDangerousWeakMap_preList == null)
        _registerDangerousWeakMap_preList = synchroList();
      _registerDangerousWeakMap_preList.add(pair(map, init));
      return map;
    }
    call(javax(), "_registerDangerousWeakMap", map, init);
    return map;
  }

  static public void _onLoad_registerDangerousWeakMap() {
    assertNotNull(javax());
    if (_registerDangerousWeakMap_preList == null)
      return;
    for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b);
    _registerDangerousWeakMap_preList = null;
  }

  static public <A, B> B mapGet2(Map<A, B> map, A a) {
    return map == null ? null : map.get(a);
  }

  static public <A, B> B mapGet2(A a, Map<A, B> map) {
    return map == null ? null : map.get(a);
  }

  static public boolean isSubtypeOf(Class a, Class b) {
    return b.isAssignableFrom(a);
  }

  static public Set<String> reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath");

  static public Set<String> reflection_classesNotToScan() {
    return reflection_classesNotToScan_value;
  }

  static public betterCIComparator_C betterCIComparator_instance;

  static public betterCIComparator_C betterCIComparator() {
    if (betterCIComparator_instance == null)
      betterCIComparator_instance = new betterCIComparator_C();
    return betterCIComparator_instance;
  }

  static public class betterCIComparator_C implements Comparator<String> {

    public int compare(String s1, String s2) {
      if (s1 == null)
        return s2 == null ? 0 : -1;
      if (s2 == null)
        return 1;
      int n1 = s1.length();
      int n2 = s2.length();
      int min = Math.min(n1, n2);
      for (int i = 0; i < min; i++) {
        char c1 = s1.charAt(i);
        char c2 = s2.charAt(i);
        if (c1 != c2) {
          c1 = Character.toUpperCase(c1);
          c2 = Character.toUpperCase(c2);
          if (c1 != c2) {
            c1 = Character.toLowerCase(c1);
            c2 = Character.toLowerCase(c2);
            if (c1 != c2) {
              return c1 - c2;
            }
          }
        }
      }
      return n1 - n2;
    }
  }

  static public int boolToInt(boolean b) {
    return b ? 1 : 0;
  }

  static public char stringToChar(String s) {
    if (l(s) != 1)
      throw fail("bad stringToChar: " + s);
    return firstChar(s);
  }

  static public Map emptyMap() {
    return new HashMap();
  }

  static public Object[] emptyObjectArray_a = new Object[0];

  static public Object[] emptyObjectArray() {
    return emptyObjectArray_a;
  }

  static public Object[] toObjectArray(Collection c) {
    List l = asList(c);
    return l.toArray(new Object[l.size()]);
  }

  static public Class run(String progID, String... args) {
    Class main = hotwire(progID);
    callMain(main, args);
    return main;
  }

  static public void restart() {
    Object j = getJavaX();
    call(j, "cleanRestart", get(j, "fullArgs"));
  }

  static volatile public boolean sleep_noSleep = false;

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

  static public void sleep() {
    try {
      if (sleep_noSleep)
        throw fail("nosleep");
      print("Sleeping.");
      sleepQuietly();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public TreeSet<String> toCaseInsensitiveSet_treeSet(Iterable<String> c) {
    if (isCISet(c))
      return (TreeSet) c;
    TreeSet<String> set = caseInsensitiveSet_treeSet();
    addAll(set, c);
    return set;
  }

  static public TreeSet<String> toCaseInsensitiveSet_treeSet(String... x) {
    TreeSet<String> set = caseInsensitiveSet_treeSet();
    addAll(set, x);
    return set;
  }

  static public Class<?> getClass(String name) {
    try {
      return Class.forName(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public Class getClass(Object o) {
    return o instanceof Class ? (Class) o : o.getClass();
  }

  static public Class getClass(Object realm, String name) {
    try {
      try {
        return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
      } catch (ClassNotFoundException e) {
        return null;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String classNameToVM(String name) {
    return name.replace(".", "$");
  }

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

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

  static public <A> HashSet<A> litset(A... items) {
    return lithashset(items);
  }

  static public char firstChar(String s) {
    return s.charAt(0);
  }

  static public Class<?> hotwire(String src) {
    assertFalse(_inCore());
    Class j = getJavaX();
    if (isAndroid()) {
      synchronized (j) {
        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 {
      Class c = (Class) (call(j, "hotwire", src));
      hotwire_copyOver(c);
      return c;
    }
  }

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

  static public void callMain() {
    callMain(mc());
  }

  static public Object sleepQuietly_monitor = new Object();

  static public void sleepQuietly() {
    try {
      assertFalse(isAWTThread());
      synchronized (sleepQuietly_monitor) {
        sleepQuietly_monitor.wait();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isCISet(Iterable<String> l) {
    return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
  }

  static public <A, B extends A> void addAll(Collection<A> c, Iterable<B> b) {
    if (c != null && b != null)
      for (A a : b) c.add(a);
  }

  static public <A, B extends A> boolean addAll(Collection<A> c, Collection<B> b) {
    return c != null && b != null && c.addAll(b);
  }

  static public <A, B extends A> boolean addAll(Collection<A> c, B... b) {
    return c != null && c.addAll(Arrays.asList(b));
  }

  static public <A, B> Map<A, B> addAll(Map<A, B> a, Map<? extends A, ? extends B> b) {
    if (a != null)
      a.putAll(b);
    return a;
  }

  static public void assertFalse(Object o) {
    if (!(eq(o, false)))
      throw fail(str(o));
  }

  static public boolean assertFalse(boolean b) {
    if (b)
      throw fail("oops");
    return b;
  }

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

  static public boolean _inCore() {
    return false;
  }

  static public List hotwire_copyOver_after = synchroList();

  static public void hotwire_copyOver(Class c) {
    for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field));
    setOptIfNotNull(c, "mainBot", getMainBot());
    setOpt(c, "creator_class", new WeakReference(mc()));
    pcallFAll(hotwire_copyOver_after, c);
  }

  static public void setOptIfNotNull(Object o, String field, Object value) {
    if (value != null)
      setOpt(o, field, value);
  }

  static public Object mainBot;

  static public Object getMainBot() {
    return mainBot;
  }

  static public interface Producer<A> {

    public A next();
  }

  static public class Var<A> implements IVar<A> {

    public Var() {
    }

    public Var(A v) {
      this.v = v;
    }

    public A v;

    public synchronized void set(A a) {
      if (v != a) {
        v = a;
        notifyAll();
      }
    }

    public synchronized A get() {
      return v;
    }

    public synchronized boolean has() {
      return v != null;
    }

    public synchronized void clear() {
      v = null;
    }

    public String toString() {
      return str(get());
    }
  }

  static public interface IVar<A> extends IF0<A> {

    public void set(A a);

    public A get();

    default public boolean has() {
      return get() != null;
    }

    default public void clear() {
      set(null);
    }
  }
}