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 static x30_pkg.x30_util.asList;
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.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 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.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.Rect;
import loadableUtils.utils.Pt;
import java.text.*;
import javax.swing.undo.UndoManager;
import java.util.TimeZone;
import java.awt.datatransfer.StringSelection;
import java.text.NumberFormat;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.nio.file.Files;
import java.nio.file.Path;

class main {

  static public class OSChat extends DynPrintLog {

    public String msg;

    public boolean sign = false;

    transient public StefansOS_ConnectToServer connector;

    public JComponent visualize() {
      JComponent log = super.visualize();
      enableWordWrap();
      return centerAndSouthWithMargins(log, centerAndEastWithMargin(withLabel("Talk to everyone:", onEnterAndCtrlEnter(jLiveValueTextField_bothWays(dm_fieldLiveValue("msg")), runnableThread(new Runnable() {

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

        public String toString() {
          return "sendMsg();";
        }
      }))), centerAndEastWithMargin(jLiveValueCheckBox("Sign", dm_fieldLiveValue("sign")), jbutton("Send", runnableThread(new Runnable() {

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

        public String toString() {
          return "sendMsg();";
        }
      })))));
    }

    public void sendMsg() {
      postMsg(trim(msg), sign);
      setField("msg", "");
    }

    public void postSigned(final String msg) {
      dm_q(new Runnable() {

        public void run() {
          try {
            postMsg(msg, true);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "postMsg(msg, true);";
        }
      });
    }

    public void postMsg(final String _msg, final boolean sign) {
      dm_q(new Runnable() {

        public void run() {
          try {
            String msg = _msg;
            if (empty(msg = trim(msg)))
              return;
            if (sign)
              msg = signWithComputerIDAndDate(msg);
            vmBus_send("sendingToChat", msg);
            logQuotedWithDate(javaxDataDir("OS Chat/sent.log"), msg);
            connector.sendLine("chat: " + quote(msg));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "String msg = _msg;\r\n    if (empty(msg = trim(msg))) return;\r\n    if (sign) ms...";
        }
      });
    }

    public void cleanMeUp() {
      cleanUp(connector);
    }

    public void start() {
      super.start();
      {
        startThread(new Runnable() {

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

          public String toString() {
            return "exportComputerPublicKeyToServerMechList();";
          }
        });
      }
      connector = new StefansOS_ConnectToServer();
      connector.onLine = new VF1<String>() {

        public void get(String line) {
          try {
            Matches m = new Matches();
            if (startsWith(line, "chat:", m)) {
              String msg = unquote(m.rest());
              infoBox(indent(">> ", msg));
              vmBus_send("gotFromChat", msg);
              logQuotedWithDate(stefansOS_chat_receivedLogFile(), msg);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "new Matches m;\r\n      if (startsWith(line, \"chat:\", m)) {\r\n        S msg = un...";
        }
      };
      connector.startWithSubs("chat");
    }
  }

  static public boolean _moduleClass_OSChat = true;

  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 void _onLoad_initUtils() {
    utils.__javax = javax();
  }

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

      public Class get(String name) {
        try {
          Class c = findClass_fullName(name);
          if (c != null)
            return c;
          if (startsWith(name, "main$"))
            return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + substring(name, 4));
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Class c = findClass_fullName(name);\r\n    if (c != null) ret c;\r\n    if (start...";
      }
    });
  }

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

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

  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 public AutoCloseable tempInterceptPrintIfNotIntercepted(F1<String, Boolean> f) {
    return print_byThread().get() == null ? tempInterceptPrint(f) : null;
  }

  static public JPanel centerAndSouthWithMargins(Component c, Component s) {
    return applyDefaultMargin(centerAndSouth(c, withTopMargin(s)));
  }

  static public JPanel centerAndEastWithMargin(Component c, Component e) {
    return centerAndEastWithMarginInbetween(c, e);
  }

  public static JComponent withLabel(String label, JComponent component) {
    return westAndCenter(jlabel(label + " "), component);
  }

  static public JTextField onEnterAndCtrlEnter(final JTextField tf, final Object action) {
    onEnter(tf, action);
    onCtrlEnter(tf, action);
    return tf;
  }

  static public JTextField jLiveValueTextField_bothWays(final SimpleLiveValue<String> lv) {
    final JTextField ta = jTextField();
    bindTextComponentToLiveValue_bothWays(ta, lv);
    return ta;
  }

  static public SimpleLiveValue dm_fieldLiveValue(String fieldName) {
    return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
  }

  static public SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
    Lock __0 = module.lock;
    lock(__0);
    try {
      Class type = getFieldType(module, fieldName);
      final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
      module.onChange(new Runnable() {

        public void run() {
          try {
            Object o = get(module, fieldName);
            value.set(o);
            ;
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ifdef dm_fieldLiveValue_debug\r\n      print(\"dm_fieldLiveValue: setting \" + fi...";
        }
      });
      value.onChange(new Runnable() {

        public void run() {
          try {
            module.setField(fieldName, value.get());
            ;
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ifdef dm_fieldLiveValue_debug\r\n      print(\"dm_fieldLiveValue: setting 2 \" + ...";
        }
      });
      return value;
    } finally {
      unlock(__0);
    }
  }

  static public Runnable runnableThread(final Runnable r) {
    return new Runnable() {

      public void run() {
        try {
          startThread(r);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "startThread(r)";
      }
    };
  }

  static public RuntimeException rethrow(Throwable t) {
    if (t instanceof Error)
      _handleError((Error) t);
    throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
  }

  static public RuntimeException rethrow(String msg, Throwable t) {
    throw new RuntimeException(msg, t);
  }

  static public JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue<Boolean> lv) {
    final JCheckBox cb = jCheckBox(text);
    bindCheckBoxToLiveValue(cb, lv);
    return cb;
  }

  static public JButton jbutton(String text, Object action) {
    return newButton(text, action);
  }

  static public JButton jbutton(String text) {
    return newButton(text, null);
  }

  static public JButton jbutton(Action action) {
    return swingNu(JButton.class, action);
  }

  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 Q dm_q() {
    return dm_current_mandatory().q();
  }

  static public void dm_q(Runnable r) {
    dm_inQ(r);
  }

  static public void dm_q(DynModule module, Runnable r) {
    module.q().add(r);
  }

  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(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 boolean signWithComputerIDAndDate_verbose = false;

  static public boolean signWithComputerIDAndDate_verify = false;

  static public String signWithComputerIDAndDate(String s, Object... __) {
    boolean verbose = optPar("verbose", __, signWithComputerIDAndDate_verbose);
    String computerID = getComputerID();
    s = rtrim(s) + "\n\n" + "-" + computerID() + ", " + localDateWithMilliseconds() + " (" + localTimeZone().getDisplayName(false, TimeZone.SHORT) + ")";
    s = fromLines(toLines(s));
    if (verbose)
      print("Signing text: " + shorten(quote(s)));
    String signed = s + "sig: " + getMySignatureForText(s);
    signed = fromLines(toLines(signed));
    if (optPar("verify", __, signWithComputerIDAndDate_verify))
      assertEqualsOptionalVerbose(verbose, "My own signature", computerID(), getAuthorOfSignedText(signed));
    return signed;
  }

  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 void logQuotedWithDate(String s) {
    logQuotedWithTime(s);
  }

  static public void logQuotedWithDate(String logFile, String s) {
    logQuotedWithTime(logFile, s);
  }

  static public void logQuotedWithDate(File logFile, String s) {
    logQuotedWithTime(logFile, s);
  }

  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 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 boolean cleanUp_interruptThreads = false;

  static public void cleanUp(Object c) {
    if (c == null)
      return;
    if (c instanceof AutoCloseable) {
      close_pcall(((AutoCloseable) c));
      return;
    }
    if (c instanceof java.util.Timer) {
      ((java.util.Timer) c).cancel();
      return;
    }
    if (c instanceof Collection) {
      cleanUp((Collection) c);
      return;
    }
    if (c instanceof Map) {
      for (Object o : keys((Map) c)) cleanUp(o);
      for (Object o : values((Map) c)) cleanUp(o);
      ((Map) c).clear();
      return;
    }
    try {
      preCleanUp(c);
      setOpt(c, "ping_pauseAll", false);
      innerCleanUp(c);
      List androids = (List) getOpt(c, "record_list");
      for (Object android : unnull(androids)) pcallOpt(android, "dispose");
      List<WeakReference> classes = (List<WeakReference>) (getOpt(c, "hotwire_classes"));
      if (classes != null)
        for (WeakReference cc : classes) {
          try {
            cleanUp(cc.get());
          } catch (Throwable __e) {
            _handleException(__e);
          }
        }
      if (cleanUp_interruptThreads) {
        List<Thread> threads = registeredThreads(c);
        if (nempty(threads)) {
          print("cleanUp: Interrupting " + n2(threads, "thread") + ": " + joinWithComma(allToString(threads)));
          interruptThreads(threads);
        }
      }
    } catch (Throwable __e) {
      _handleException(__e);
    }
    setOpt(c, "cleaningUp_flag", false);
    if (c instanceof Class && ((Class) c).getName().equals("main"))
      retireClassLoader(((Class) c).getClassLoader());
  }

  static public void cleanUp(Collection l) {
    if (l == null)
      return;
    for (Object c : l) cleanUp(c);
    l.clear();
  }

  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 exportComputerPublicKeyToServerMechList() {
    addToMechMap("Computer Public Keys", lithashmap(computerID(), getMyPublicKey()));
  }

  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 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 JWindow infoBox(String text) {
    return infoMessage(text);
  }

  static public JWindow infoBox(String text, double seconds) {
    return infoMessage(text, seconds);
  }

  static public JWindow infoBox(Throwable e) {
    return infoMessage(e);
  }

  static public int indent_default = 2;

  static public String indent(int indent) {
    return repeat(' ', indent);
  }

  static public String indent(int indent, String s) {
    return indent(repeat(' ', indent), s);
  }

  static public String indent(String indent, String s) {
    return indent + s.replace("\n", "\n" + indent);
  }

  static public String indent(String s) {
    return indent(indent_default, s);
  }

  static public List<String> indent(String indent, List<String> lines) {
    List<String> l = new ArrayList();
    if (lines != null)
      for (String s : lines) l.add(indent + s);
    return l;
  }

  static public File stefansOS_chat_receivedLogFile() {
    return javaxDataDir("OS Chat/received.log");
  }

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

  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 in " + c);
      }
    } catch (Exception __e) {
      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 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 Object _defaultClassFinder_value = defaultDefaultClassFinder();

  static public Object _defaultClassFinder() {
    return _defaultClassFinder_value;
  }

  static public String programID;

  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 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 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 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 <A extends JComponent> A applyDefaultMargin(final A c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg...";
        }
      });
    }
    return c;
  }

  static public JPanel centerAndSouth(final Component c, final Component s) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(BorderLayout.CENTER, wrap(c));
          if (s != null)
            panel.add(BorderLayout.SOUTH, wrap(s));
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.CENT...";
      }
    });
  }

  static public int withTopMargin_defaultWidth = 6;

  static public JPanel withTopMargin(Component c) {
    return withTopMargin(withTopMargin_defaultWidth, c);
  }

  static public JPanel withTopMargin(final int w, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = new JPanel(new BorderLayout());
          p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat...";
      }
    });
  }

  static public JPanel centerAndEastWithMarginInbetween(Component c, final Component e) {
    return centerAndEast(c, withLeftMargin(e));
  }

  static public JPanel westAndCenter(final Component w, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(BorderLayout.WEST, wrap(w));
          panel.add(BorderLayout.CENTER, wrap(c));
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.WEST...";
      }
    });
  }

  static public JLabel jlabel(final String text) {
    return swingConstruct(BetterLabel.class, text);
  }

  static public JLabel jlabel() {
    return jlabel(" ");
  }

  static public JTextField onEnter(final JTextField tf, final Object action) {
    if (action == null || tf == null)
      return tf;
    tf.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(java.awt.event.ActionEvent _evt) {
        try {
          tf.selectAll();
          callF(action);
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    });
    return tf;
  }

  static public JButton onEnter(JButton btn, final Object action) {
    if (action == null || btn == null)
      return btn;
    btn.addActionListener(actionListener(action));
    return btn;
  }

  static public JList onEnter(JList list, Object action) {
    list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
    return list;
  }

  static public JComboBox onEnter(final JComboBox cb, final Object action) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            if (cb.isEditable()) {
              JTextField text = (JTextField) cb.getEditor().getEditorComponent();
              onEnter(text, action);
            } else {
              cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
              cb.getActionMap().put("enter", abstractAction("", new Runnable() {

                public void run() {
                  try {
                    cb.hidePopup();
                    callF(action);
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "cb.hidePopup(); callF(action);";
                }
              }));
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (cb.isEditable()) {\r\n      JTextField text = (JTextField) cb.getEditor().g...";
        }
      });
    }
    return cb;
  }

  static public JTable onEnter(final JTable table, final Object action) {
    table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
    table.getActionMap().put("Enter", new AbstractAction() {

      public void actionPerformed(ActionEvent e) {
        callF(action, table.getSelectedRow());
      }
    });
    return table;
  }

  static public JTextField onEnter(Object action, JTextField tf) {
    return onEnter(tf, action);
  }

  static public <A extends JComponent> A onCtrlEnter(final A c, final Object action) {
    addKeyListener(c, ctrlEnterKeyListener(action));
    return c;
  }

  static public JTextField jTextField() {
    return jTextField("");
  }

  static public JTextField jTextField(final String text) {
    return swing(new F0<JTextField>() {

      public JTextField get() {
        try {
          JTextField tf = new JTextField(unnull(text));
          standardTextFieldPopupMenu(tf);
          jenableUndoRedo(tf);
          tf.selectAll();
          return tf;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JTextField tf = new JTextField(unnull(text));\r\n    standardTextFieldPopupMenu...";
      }
    });
  }

  static public JTextField jTextField(Object o) {
    return jTextField(strOrEmpty(o));
  }

  static public <A extends JTextComponent> A bindTextComponentToLiveValue_bothWays(final A tc, final SimpleLiveValue<String> lv) {
    bindLiveValueListenerToComponent(tc, lv, new Runnable() {

      public void run() {
        try {
          setTextKeepCaret(tc, lv.get());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "setTextKeepCaret(tc, lv.get())";
      }
    });
    onChange(tc, new Runnable() {

      public void run() {
        try {
          lv.set(getText(tc));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "lv.set(getText(tc))";
      }
    });
    return tc;
  }

  static public void lock(Lock lock) {
    try {
      ping();
      if (lock == null)
        return;
      try {
        lock.lockInterruptibly();
      } catch (InterruptedException e) {
        print("Locking interrupted! I probably deadlocked, oops.");
        printStackTrace(e);
        rethrow(e);
      }
      ping();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void lock(Lock lock, String msg) {
    print("Locking: " + msg);
    lock(lock);
  }

  static public void lock(Lock lock, String msg, long timeout) {
    print("Locking: " + msg);
    lockOrFail(lock, timeout);
  }

  static public ReentrantLock lock() {
    return fairLock();
  }

  static public Class getFieldType(Object o, String field) {
    return fieldType(o, field);
  }

  static public void unlock(Lock lock, String msg) {
    if (lock == null)
      return;
    print("Unlocking: " + msg);
    lock.unlock();
  }

  static public void unlock(Lock lock) {
    if (lock == null)
      return;
    lock.unlock();
  }

  static public void _handleError(Error e) {
    call(javax(), "_handleError", e);
  }

  static public JCheckBox jCheckBox() {
    return swingNu(JCheckBox.class);
  }

  static public JCheckBox jCheckBox(boolean checked) {
    return swingNu(JCheckBox.class, "", checked);
  }

  static public JCheckBox jCheckBox(String text, boolean checked) {
    return swingNu(JCheckBox.class, text, checked);
  }

  static public JCheckBox jCheckBox(String text) {
    return swingNu(JCheckBox.class, text);
  }

  static public JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
    JCheckBox cb = jCheckBox(checked, onChange);
    cb.setText(text);
    return cb;
  }

  static public JCheckBox jCheckBox(boolean checked, final Object onChange) {
    final JCheckBox cb = jCheckBox(checked);
    cb.addChangeListener(new ChangeListener() {

      public void stateChanged(ChangeEvent e) {
        pcallF(onChange, cb.isSelected());
      }
    });
    return cb;
  }

  static public <A extends JCheckBox> A bindCheckBoxToLiveValue(final A cb, final SimpleLiveValue<Boolean> lv) {
    bindLiveValueListenerToComponent(cb, lv, new Runnable() {

      public void run() {
        try {
          setChecked(cb, isTrue(lv.get()));
          ;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ifdef bindCheckBoxToLiveValue_debug\r\n      print(\"bindCheckBoxToLiveValue: se...";
      }
    });
    onChange(cb, new Runnable() {

      public void run() {
        try {
          lv.set(isChecked(cb));
          ;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ifdef bindCheckBoxToLiveValue_debug\r\n      print(\"bindCheckBoxToLiveValue: se...";
      }
    });
    return cb;
  }

  static public boolean newButton_autoToolTip = true;

  static public JButton newButton(final String text, final Object action) {
    return swing(new F0<JButton>() {

      public JButton get() {
        try {
          String text2 = dropPrefix("[disabled] ", text);
          final JButton btn = new JButton(text2);
          if (l(text2) < l(text))
            btn.setEnabled(false);
          if (newButton_autoToolTip) {
            btn.setToolTipText(btn.getText());
          }
          if (action != null)
            btn.addActionListener(actionListener(action, btn));
          return btn;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "S text2 = dropPrefix(\"[disabled] \", text);\r\n    final JButton btn = new JButt...";
      }
    });
  }

  static public <A> A swingNu(final Class<A> c, final Object... args) {
    return swingConstruct(c, args);
  }

  static public void dm_inQ(Runnable r) {
    dm_q().add(r);
  }

  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 <A> A optPar(ThreadLocal<A> tl, A defaultValue) {
    A a = tl.get();
    if (a != null) {
      tl.set(null);
      return a;
    }
    return defaultValue;
  }

  static public <A> A optPar(ThreadLocal<A> tl) {
    return optPar(tl, null);
  }

  static public Object optPar(Object[] params, String name) {
    return optParam(params, name);
  }

  static public Object optPar(String name, Object[] params) {
    return optParam(params, name);
  }

  static public Object optPar(String name, Map params) {
    return optParam(name, params);
  }

  static public <A> A optPar(Object[] params, String name, A defaultValue) {
    return optParam(params, name, defaultValue);
  }

  static public <A> A optPar(String name, Object[] params, A defaultValue) {
    return optParam(params, name, defaultValue);
  }

  static public String getComputerID() {
    try {
      return computerID();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String rtrim(String s) {
    if (s == null)
      return null;
    int i = s.length();
    while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i;
    return i < s.length() ? s.substring(0, i) : s;
  }

  static public String _computerID;

  static public Lock computerID_lock = lock();

  public static String computerID() {
    if (_computerID == null) {
      Lock __0 = computerID_lock;
      lock(__0);
      try {
        if (_computerID != null)
          return _computerID;
        File file = computerIDFile();
        _computerID = loadTextFile(file.getPath());
        if (_computerID == null) {
          _computerID = loadTextFile(userDir(".tinybrain/computer-id"));
          if (_computerID == null)
            _computerID = makeRandomID(12, new SecureRandom());
          saveTextFile(file, _computerID);
        }
      } finally {
        unlock(__0);
      }
    }
    return _computerID;
  }

  static public String localDateWithMilliseconds(Date time) {
    return localDateWithMilliseconds(time.getTime());
  }

  static public String localDateWithMilliseconds(long time) {
    SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss''SSSS");
    return format.format(time);
  }

  static public String localDateWithMilliseconds() {
    return localDateWithMilliseconds(now());
  }

  static public TimeZone localTimeZone() {
    return getTimeZone(standardTimeZone());
  }

  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 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 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 String getMySignatureForText(String s) {
    return base64encode(PKI.sign(toUtf8(s), PKI.getStandardPrivateKey()));
  }

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

  static public <A> A assertEqualsOptionalVerbose(boolean verbose, String msg, Object x, A y) {
    return verbose ? assertEqualsVerbose(msg, x, y) : assertEquals(msg, x, y);
  }

  static public boolean getAuthorOfSignedText_debug = false;

  static public String getAuthorOfSignedText(String signed) {
    return pairB(getAuthorOfSignedText2(signed));
  }

  static public Pair<String, String> getAuthorOfSignedText2(String signed) {
    try {
      List<String> lines = toLines(signed);
      String authorLine = nextToLast(lines);
      String sigLine = last(lines);
      if (getAuthorOfSignedText_debug)
        print("authorLine: " + authorLine);
      String text = fromLines(dropLast(lines));
      if (!startsWith(authorLine, "-"))
        return null;
      String author = dropPrefix("-", authorLine);
      author = beforeComma(author);
      if (!isComputerID(author))
        throw fail("Not a computer ID: " + author);
      String publicKey = getPublicKeyOfComputer(author);
      if (publicKey == null)
        throw fail("Computer " + author + " has to publish a public key.");
      if (!startsWith(sigLine, "sig: "))
        return null;
      String sig = dropPrefix("sig: ", sigLine);
      if (!PKI.verifySignature(PKI.publicKeyFromString(publicKey), PKI.signatureFromString(sig), toUtf8(text))) {
        print("Signature doesn't verify (key: ..." + publicKey + ")");
        print("Sig: " + sig);
        print("Text:");
        printIndent(">> ", text);
        return pair(author, null);
      }
      return pair(author, author);
    } catch (RuntimeException e) {
      printShortException(e);
      return null;
    }
  }

  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 void logQuotedWithTime(String s) {
    logQuotedWithTime(standardLogFile(), s);
  }

  static public void logQuotedWithTime(File logFile, String s) {
    logQuoted(logFile, logQuotedWithTime_format(s));
  }

  static public void logQuotedWithTime(String logFile, String s) {
    logQuoted(logFile, logQuotedWithTime_format(s));
  }

  static public String logQuotedWithTime_format(String s) {
    return (now()) + " " + s;
  }

  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 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 str(Object o) {
    return o == null ? "null" : o.toString();
  }

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

  static public void close_pcall(AutoCloseable c) {
    if (c != null) {
      try {
        c.close();
      } catch (Throwable __e) {
        _handleException(__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 <A, B> Collection<B> values(Map<A, B> map) {
    return map == null ? emptyList() : map.values();
  }

  static public void preCleanUp(Object c) {
    if (c instanceof Collection) {
      for (Object o : ((Collection) c)) preCleanUp(o);
      return;
    }
    callOpt(c, "licensed_off");
    setOpt(c, "ping_anyActions", true);
    setOpt(c, "cleaningUp_flag", true);
  }

  static public void innerCleanUp(Object c) {
    if (!isFalse(pcallOpt(c, "cleanMeUp")))
      for (String name : sorted(methodsStartingWith(c, "cleanMeUp_"))) try {
        callOpt(c, name);
      } catch (Throwable e) {
        print("Error cleaning up: " + programID(c));
        _handleException(e);
      }
  }

  static public void innerCleanUp() {
    innerCleanUp(mc());
  }

  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[]) new Object[0] : 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 Object pcallOpt(Object o, String method, Object... args) {
    try {
      return callOpt(o, method, args);
    } catch (Throwable __e) {
      _handleException(__e);
    }
    return null;
  }

  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 List<Thread> registeredThreads(Object o) {
    Map<Thread, Boolean> map = (Map<Thread, Boolean>) (getOpt(o, "_registerThread_threads"));
    if (map == null)
      return ll();
    map.size();
    synchronized (map) {
      return asList(keys(map));
    }
  }

  static public List<Thread> registeredThreads() {
    _registerThread_threads.size();
    return asList(keys(_registerThread_threads));
  }

  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 n2(long l) {
    return formatWithThousands(l);
  }

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

  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> 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> allToString(Iterable c) {
    List<String> l = new ArrayList();
    for (Object o : unnull(c)) l.add(str(o));
    return l;
  }

  static public List<String> allToString(Object[] c) {
    List<String> l = new ArrayList();
    for (Object o : unnull(c)) l.add(str(o));
    return l;
  }

  static public void interruptThreads(Collection<Thread> threads) {
    for (Thread t : unnull(threads)) t.interrupt();
  }

  static public void interruptThreads(Class mainClass) {
    interruptThreads(registeredThreads(mainClass));
  }

  static public void retireClassLoader(ClassLoader cl) {
    if (isJavaXClassLoader(cl))
      setOptAll(cl, "retired", true, "retiredMarker", new DefunctClassLoader());
  }

  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 String addToMechMap(String listName, Map<String, String> map) {
    return appendToMechMap(listName, map);
  }

  static public HashMap lithashmap(Object... x) {
    return litmap(x);
  }

  static public String getMyPublicKey() {
    return PKI.publicKeyToString(PKI.getStandardPublicKey());
  }

  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);
  }

  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 boolean infoMessage_alwaysOnTop = true;

  static public double infoMessage_defaultTime = 5.0;

  static public JWindow infoMessage(String text) {
    return infoMessage(text, infoMessage_defaultTime);
  }

  static public JWindow infoMessage(final String text, final double seconds) {
    printHidingCredentials(text);
    return infoMessage_noprint(text, seconds);
  }

  static public JWindow infoMessage_noprint(String text) {
    return infoMessage_noprint(text, infoMessage_defaultTime);
  }

  static public JWindow infoMessage_noprint(final String _text, final double seconds) {
    final String text = hideCredentials(_text);
    if (empty(text))
      return null;
    logQuotedWithDate(infoBoxesLogFile(), text);
    if (isHeadless())
      return null;
    return (JWindow) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          final JWindow window = showWindow(infoMessage_makePanel(text));
          window.setSize(300, 150);
          moveToTopRightCorner(window);
          if (infoMessage_alwaysOnTop)
            window.setAlwaysOnTop(true);
          window.setVisible(true);
          if (seconds != 0)
            disposeWindowAfter(iround(seconds * 1000), window);
          return window;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "final JWindow window = showWindow(infoMessage_makePanel(text));\r\n    window.s...";
      }
    });
  }

  static public JWindow infoMessage(Throwable e) {
    printStackTrace(e);
    return infoMessage(exceptionToStringShort(e));
  }

  static public String repeat(char c, int n) {
    n = Math.max(n, 0);
    char[] chars = new char[n];
    for (int i = 0; i < n; i++) chars[i] = c;
    return new String(chars);
  }

  static public <A> List<A> repeat(A a, int n) {
    n = Math.max(n, 0);
    List<A> l = new ArrayList(n);
    for (int i = 0; i < n; i++) l.add(a);
    return l;
  }

  static public <A> List<A> repeat(int n, A a) {
    return repeat(a, n);
  }

  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 List<String> classNames(Collection l) {
    return getClassNames(l);
  }

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

  static public Class __javax;

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

  static public int withMargin_defaultWidth = 6;

  static public JPanel withMargin(Component c) {
    return withMargin(withMargin_defaultWidth, c);
  }

  static public JPanel withMargin(int w, Component c) {
    return withMargin(w, w, c);
  }

  static public JPanel withMargin(int w, int h, Component c) {
    return withMargin(w, h, w, h, c);
  }

  static public JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = new JPanel(new BorderLayout());
          p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat...";
      }
    });
  }

  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 defaultDefaultClassFinder() {
    return new F1<String, Class>() {

      public Class get(String name) {
        try {
          Class c = findClass_fullName(name);
          if (c != null)
            return c;
          if (startsWith(name, "loadableUtils.utils$"))
            return findClass_fullName("main" + substring(name, 19));
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Class c = findClass_fullName(name);\r\n    if (c != null) ret c;\r\n    if (start...";
      }
    };
  }

  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 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 boolean eq(Object a, Object b) {
    return a == b || (a == null ? b == null : b != null && a.equals(b));
  }

  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 <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 Object swing(Object f) {
    return swingAndWait(f);
  }

  static public <A> A swing(F0<A> f) {
    return (A) swingAndWait(f);
  }

  static public <A> A swing(IF0<A> f) {
    return (A) swingAndWait(f);
  }

  static public JComponent wrap(Object swingable) {
    return _recordNewSwingComponent(wrap_2(swingable));
  }

  static public JComponent wrap_2(Object swingable) {
    if (swingable == null)
      return null;
    JComponent c;
    if (swingable instanceof Component)
      c = componentToJComponent(((Component) swingable));
    else
      c = componentToJComponent((Component) callOpt(swingable, "swing"));
    if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
      return jscroll(c);
    return c == null ? jlabel(str(swingable)) : c;
  }

  static public JPanel centerAndEast(final Component c, final Component e) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(BorderLayout.CENTER, wrap(c));
          panel.add(BorderLayout.EAST, wrap(e));
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.CENT...";
      }
    });
  }

  static public int withLeftMargin_defaultWidth = 6;

  static public JPanel withLeftMargin(Component c) {
    return withLeftMargin(withLeftMargin_defaultWidth, c);
  }

  static public JPanel withLeftMargin(final int margin, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = new JPanel(new BorderLayout());
          p.setBorder(BorderFactory.createEmptyBorder(0, margin, 0, 0));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat...";
      }
    });
  }

  static public <A> A swingConstruct(final Class<A> c, final Object... args) {
    return swing(new F0<A>() {

      public A get() {
        try {
          return nuObject(c, args);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret nuObject(c, args);";
      }
    });
  }

  static public void messageBox(final String msg) {
    if (headless())
      print(msg);
    else {
      swing(new Runnable() {

        public void run() {
          try {
            JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES...";
        }
      });
    }
  }

  static public void messageBox(Throwable e) {
    printStackTrace(e);
    messageBox(hideCredentials(innerException2(e)));
  }

  static public ActionListener actionListener(final Object runnable) {
    return actionListener(runnable, null);
  }

  static public ActionListener actionListener(final Object runnable, final Object instanceToHold) {
    if (runnable instanceof ActionListener)
      return (ActionListener) runnable;
    final Object info = _threadInfo();
    return new java.awt.event.ActionListener() {

      public void actionPerformed(java.awt.event.ActionEvent _evt) {
        try {
          _threadInheritInfo(info);
          AutoCloseable __0 = holdInstance(instanceToHold);
          try {
            callF(runnable);
          } finally {
            _close(__0);
          }
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

  static public KeyListener enterKeyListener(final Object action) {
    return new KeyAdapter() {

      public void keyPressed(KeyEvent ke) {
        if (ke.getKeyCode() == KeyEvent.VK_ENTER)
          pcallF(action);
      }
    };
  }

  static public Runnable rCallOnSelectedListItem(final JList list, final Object action) {
    return new Runnable() {

      public void run() {
        try {
          pcallF(action, getSelectedItem(list));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcallF(action, getSelectedItem(list))";
      }
    };
  }

  static public AbstractAction abstractAction(String name, final Object runnable) {
    return new AbstractAction(name) {

      public void actionPerformed(ActionEvent evt) {
        pcallF(runnable);
      }
    };
  }

  static public void addKeyListener(final Component c, final KeyListener l) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.addKeyListener(l);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.addKeyListener(l);";
        }
      });
    }
  }

  static public KeyListener ctrlEnterKeyListener(final Object action) {
    final Object info = _threadInfo();
    return new KeyAdapter() {

      public void keyReleased(KeyEvent ke) {
        if (ke.getKeyCode() == KeyEvent.VK_ENTER && ke.getModifiers() == KeyEvent.CTRL_MASK) {
          _threadInheritInfo(info);
          pcallF(action);
        }
      }
    };
  }

  static public JTextField standardTextFieldPopupMenu(final JTextField tf) {
    final WeakReference<JTextField> ref = weakRef(tf);
    componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() {

      public void run() {
        try {
          copyTextToClipboard(ref.get().getText());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "copyTextToClipboard(ref.get().getText())";
      }
    });
    componentPopupMenuItem(tf, "Paste", new Runnable() {

      public void run() {
        try {
          ref.get().paste();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ref.get().paste()";
      }
    });
    return tf;
  }

  static public <A extends JTextComponent> A jenableUndoRedo(final A textcomp) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            final UndoManager undo = new UndoManager();
            vm_generalWeakSet("Undo Managers").add(undo);
            textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {

              public void undoableEditHappened(UndoableEditEvent evt) {
                undo.addEdit(evt.getEdit());
              }
            });
            textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() {

              public void run() {
                try {
                  if (undo.canUndo())
                    undo.undo();
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "if (undo.canUndo()) undo.undo()";
              }
            }));
            textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() {

              public void run() {
                try {
                  if (undo.canRedo())
                    undo.redo();
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "if (undo.canRedo()) undo.redo()";
              }
            }));
            textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
            textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "final new UndoManager undo;\r\n    vm_generalWeakSet(\"Undo Managers\").add(undo)...";
        }
      });
    }
    return textcomp;
  }

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

  static public <A extends JComponent> A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
    if (lv != null)
      bindToComponent(component, new Runnable() {

        public void run() {
          try {
            lv.onChangeAndNow(listener);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ifdef bindLiveValueListenerToComponent_debug\r\n          print(\"bindLiveValueL...";
        }
      }, new Runnable() {

        public void run() {
          try {
            lv.removeOnChangeListener(listener);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "lv.removeOnChangeListener(listener)";
        }
      });
    return component;
  }

  static public <A extends JTextComponent> A setTextKeepCaret(final String text, final A c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            int caret = c.getCaretPosition();
            setText(c, text);
            setCaretPosition(c, caret);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "int caret = c.getCaretPosition();\r\n    setText(c, text);\r\n    setCaretPositio...";
        }
      });
    }
    return c;
  }

  static public <A extends JTextComponent> A setTextKeepCaret(A c, String text) {
    return setTextKeepCaret(text, c);
  }

  static public <A extends JSpinner> A onChange(A spinner, Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            spinner.addChangeListener(changeListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "spinner.addChangeListener(changeListener(r));";
        }
      });
    }
    return spinner;
  }

  static public <A extends AbstractButton> A onChange(A b, Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            b.addItemListener(itemListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "b.addItemListener(itemListener(r));";
        }
      });
    }
    return b;
  }

  static public void onChange(JTextComponent tc, Object r) {
    onUpdate(tc, r);
  }

  static public <A extends JSlider> A onChange(A slider, final Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            slider.addChangeListener(changeListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "slider.addChangeListener(changeListener(r));";
        }
      });
    }
    return slider;
  }

  static public JComboBox onChange(Object r, JComboBox cb) {
    return onChange(cb, r);
  }

  static public JComboBox onChange(JComboBox cb, final Object r) {
    if (isEditableComboBox(cb))
      onChange(textFieldFromComboBox(cb), r);
    else
      onSelectedItem(cb, new VF1<String>() {

        public void get(String s) {
          try {
            callF(r);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "callF(r)";
        }
      });
    return cb;
  }

  static public String getText(final AbstractButton c) {
    return c == null ? "" : (String) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          return c.getText();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getText();";
      }
    });
  }

  static public String getText(final JTextComponent c) {
    return c == null ? "" : (String) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          return c.getText();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getText();";
      }
    });
  }

  static public String getText(final JLabel l) {
    return l == null ? "" : (String) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          return l.getText();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret l.getText();";
      }
    });
  }

  static public String getText(final JComboBox cb) {
    if (cb == null)
      return null;
    if (isEditableComboBox(cb))
      return unnull((String) cb.getEditor().getItem());
    else
      return str(cb.getSelectedItem());
  }

  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 void lockOrFail(Lock lock, long timeout) {
    try {
      ping();
      if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
        String s = "Couldn't acquire lock after " + timeout + " ms.";
        if (lock instanceof ReentrantLock) {
          ReentrantLock l = (ReentrantLock) lock;
          s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
        }
        throw fail(s);
      }
      ping();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ReentrantLock fairLock() {
    return new ReentrantLock(true);
  }

  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 void setChecked(final JCheckBox checkBox, final boolean b) {
    if (checkBox != null) {
      swing(new Runnable() {

        public void run() {
          try {
            if (isChecked(checkBox) != b)
              checkBox.setSelected(b);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (isChecked(checkBox) != b)\r\n      checkBox.setSelected(b);";
        }
      });
    }
  }

  static public boolean isChecked(final JCheckBox checkBox) {
    return checkBox != null && (boolean) swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return checkBox.isSelected();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret checkBox.isSelected();";
      }
    });
  }

  static public boolean isChecked(final JCheckBoxMenuItem mi) {
    return mi != null && (boolean) swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return mi.isSelected();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret mi.isSelected();";
      }
    });
  }

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

  static public String getClassName(Object o) {
    return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
  }

  static public <A> A optParam(ThreadLocal<A> tl, A defaultValue) {
    return optPar(tl, defaultValue);
  }

  static public <A> A optParam(ThreadLocal<A> tl) {
    return optPar(tl);
  }

  static public Object optParam(String name, Map params) {
    return mapGet(params, name);
  }

  static public <A> A optParam(Object[] opt, String name, A defaultValue) {
    int n = l(opt);
    if (n == 1 && opt[0] instanceof Map) {
      Map map = (Map) (opt[0]);
      return map.containsKey(name) ? (A) map.get(name) : defaultValue;
    }
    if (!even(l(opt)))
      throw fail("Odd parameter length");
    for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
      return (A) opt[i + 1];
    return defaultValue;
  }

  static public Object optParam(Object[] opt, String name) {
    return optParam(opt, name, null);
  }

  static public File computerIDFile() {
    return javaxDataDir("Basic Info/computer-id.txt");
  }

  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 File userDir() {
    return new File(userHome());
  }

  static public File userDir(String path) {
    return new File(userHome(), path);
  }

  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 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 SimpleDateFormat simpleDateFormat_local(String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    sdf.setTimeZone(localTimeZone());
    return sdf;
  }

  static public long now_virtualTime;

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

  static public TimeZone getTimeZone(String name) {
    return TimeZone.getTimeZone(name);
  }

  static public String standardTimeZone_name = "Europe/Berlin";

  static public String standardTimeZone() {
    return standardTimeZone_name;
  }

  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 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 String base64encode(byte[] a) {
    int aLen = a.length;
    int numFullGroups = aLen / 3;
    int numBytesInPartialGroup = aLen - 3 * numFullGroups;
    int resultLen = 4 * ((aLen + 2) / 3);
    StringBuffer result = new StringBuffer(resultLen);
    char[] intToAlpha = intToBase64;
    int inCursor = 0;
    for (int i = 0; i < numFullGroups; i++) {
      int byte0 = a[inCursor++] & 0xff;
      int byte1 = a[inCursor++] & 0xff;
      int byte2 = a[inCursor++] & 0xff;
      result.append(intToAlpha[byte0 >> 2]);
      result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
      result.append(intToAlpha[(byte1 << 2) & 0x3f | (byte2 >> 6)]);
      result.append(intToAlpha[byte2 & 0x3f]);
    }
    if (numBytesInPartialGroup != 0) {
      int byte0 = a[inCursor++] & 0xff;
      result.append(intToAlpha[byte0 >> 2]);
      if (numBytesInPartialGroup == 1) {
        result.append(intToAlpha[(byte0 << 4) & 0x3f]);
        result.append("==");
      } else {
        int byte1 = a[inCursor++] & 0xff;
        result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
        result.append(intToAlpha[(byte1 << 2) & 0x3f]);
        result.append('=');
      }
    }
    return result.toString();
  }

  static final public char[] intToBase64 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

  static public byte[] toUtf8(String s) {
    try {
      return s.getBytes("UTF-8");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 + ": " : "") + (y) + " != " + (x));
    } else
      print("OK: " + (x));
    return y;
  }

  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> B pairB(Pair<A, B> p) {
    return p == null ? null : p.b;
  }

  static public <A> A nextToLast(List<A> l) {
    return get(l, l(l) - 2);
  }

  static public <A> A last(List<A> l) {
    return empty(l) ? null : l.get(l.size() - 1);
  }

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

  static public int last(int[] a) {
    return l(a) != 0 ? a[l(a) - 1] : 0;
  }

  static public <A> A last(A[] a) {
    return l(a) != 0 ? a[l(a) - 1] : null;
  }

  static public <A> A last(Iterator<A> it) {
    A a = null;
    while (it.hasNext()) {
      ping();
      a = it.next();
    }
    return a;
  }

  static public <A> A last(SortedSet<A> l) {
    return l == null ? null : l.last();
  }

  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 String beforeComma(String s) {
    return substring(s, 0, smartIndexOf(s, ','));
  }

  static public boolean isComputerID(String s) {
    return isRandomID(s, 12);
  }

  static public String getPublicKeyOfComputer(String computer) {
    if (!isComputerID(computer))
      return null;
    if (eq(computer, computerID()))
      return getMyPublicKey();
    return mechMap("Computer Public Keys").get(computer);
  }

  static public <A> A printIndent(A o) {
    print(indentx(str(o)));
    return o;
  }

  static public <A> A printIndent(String indent, A o) {
    print(indentx(indent, str(o)));
    return o;
  }

  static public void printIndent(int indent, Object o) {
    print(indentx(indent, str(o)));
  }

  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 void printShortException(Throwable e) {
    print(exceptionToStringShort(e));
  }

  static public void printShortException(String s, Throwable e) {
    print(s, exceptionToStringShort(e));
  }

  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 File standardLogFile() {
    return getProgramFile("log");
  }

  static public void logQuoted(String logFile, String line) {
    logQuoted(getProgramFile(logFile), line);
  }

  static public void logQuoted(File logFile, String line) {
    appendToFile(logFile, quote(line) + "\n");
  }

  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 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 <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> List<A> sorted(Collection<A> c, final Object comparator) {
    List<A> l = cloneList(c);
    sort(l, makeComparator(comparator));
    return l;
  }

  static public <A> List<A> sorted(Collection<A> c) {
    List<A> l = cloneList(c);
    sort(l);
    return l;
  }

  static public List<String> methodsStartingWith(Object o, final String prefix) {
    return filter(allMethodNames(o), new F1<String, Object>() {

      public Object get(String s) {
        try {
          return startsWith(s, prefix);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "startsWith(s, prefix)";
      }
    });
  }

  static public Map emptyMap() {
    return new HashMap();
  }

  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 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);
  }

  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 boolean isJavaXClassLoader(ClassLoader cl) {
    return startsWithOneOf(className(cl), "main$JavaXClassLoader", "x30$JavaXClassLoader");
  }

  static public void setOptAll(Object o, Map<String, Object> fields) {
    if (fields == null)
      return;
    for (String field : keys(fields)) setOpt(o, field, fields.get(field));
  }

  static public void setOptAll(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];
      setOpt(o, field, value);
    }
  }

  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 String appendToMechMap(String listName, Map<String, String> map) {
    return appendToMechList(listName, formatDoubleArrowMap(map));
  }

  static public HashMap litmap(Object... x) {
    HashMap map = new HashMap();
    litmap_impl(map, x);
    return map;
  }

  static public void litmap_impl(Map map, Object... x) {
    if (x != null)
      for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
        map.put(x[i], x[i + 1]);
  }

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

  static public <A> A printHidingCredentials(A o) {
    print(hideCredentials(str(o)));
    return o;
  }

  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)=[^&\\s\"]*", "$1$2=<hidden>");
  }

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

  static public File infoBoxesLogFile() {
    return new File(javaxDataDir(), "Logs/infoBoxes.txt");
  }

  static public void swingAndWait(Runnable r) {
    try {
      if (isAWTThread())
        r.run();
      else
        EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Object swingAndWait(final Object f) {
    if (isAWTThread())
      return callF(f);
    else {
      final Var result = new Var();
      swingAndWait(new Runnable() {

        public void run() {
          try {
            result.set(callF(f));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "result.set(callF(f));";
        }
      });
      return result.get();
    }
  }

  static public JWindow showWindow(Component c) {
    JWindow w = new JWindow();
    w.add(wrap(c));
    return w;
  }

  static public JPanel infoMessage_makePanel(String text) {
    final JTextArea ta = wrappedTextArea(text);
    onClick(ta, new Runnable() {

      public void run() {
        try {
          disposeWindow(ta);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "disposeWindow(ta)";
      }
    });
    int size = 14;
    if (l(text) <= 50)
      size *= 2;
    else if (l(text) < 100)
      size = iround(size * 1.5);
    ta.setFont(typeWriterFont(size));
    JScrollPane sp = jscroll(ta);
    return withMargin(sp);
  }

  static public int moveToTopRightCorner_inset = 20;

  static public <A extends Component> A moveToTopRightCorner(A a) {
    return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a);
  }

  static public <A extends Component> A moveToTopRightCorner(int insetX, int insetY, A a) {
    Window w = getWindow(a);
    if (w != null)
      w.setLocation(getScreenSize().width - w.getWidth() - insetX, insetY);
    return a;
  }

  static public <A extends Window> A disposeWindowAfter(int delay, final A w) {
    if (w != null)
      swingLater(delay, new Runnable() {

        public void run() {
          try {
            w.dispose();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "w.dispose();";
        }
      });
    return w;
  }

  static public <A extends Window> A disposeWindowAfter(A w, double seconds) {
    return disposeWindowAfter(toMS_int(seconds), w);
  }

  static public <A extends Window> A disposeWindowAfter(double seconds, A w) {
    return disposeWindowAfter(w, seconds);
  }

  static public int iround(double d) {
    return (int) Math.round(d);
  }

  static public int iround(Number n) {
    return iround(toDouble(n));
  }

  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 Throwable getExceptionCause(Throwable e) {
    Throwable c = e.getCause();
    return c != null ? c : e;
  }

  static public String joinWithSpace(Collection<String> 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);
  }

  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 getStackTrace2(Throwable e) {
    return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
  }

  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 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 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 <A extends Component> A _recordNewSwingComponent(A c) {
    if (c != null)
      callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
    return c;
  }

  static public JComponent componentToJComponent(Component c) {
    if (c instanceof JComponent)
      return (JComponent) c;
    if (c instanceof JFrame)
      return ((JFrame) c).getRootPane();
    if (c == null)
      return null;
    throw fail("boohoo " + getClassName(c));
  }

  static public JScrollPane jscroll(final Component c) {
    return swing(new F0<JScrollPane>() {

      public JScrollPane get() {
        try {
          return new JScrollPane(c);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new JScrollPane(c);";
      }
    });
  }

  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 headless() {
    return isHeadless();
  }

  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 ThreadLocal<List<Object>> holdInstance_l = new ThreadLocal();

  static public AutoCloseable holdInstance(Object o) {
    if (o == null)
      return null;
    listThreadLocalAdd(holdInstance_l, o);
    return new AutoCloseable() {

      public void close() {
        listThreadLocalPopLast(holdInstance_l);
      }
    };
  }

  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 String getSelectedItem(JList l) {
    return (String) l.getSelectedValue();
  }

  static public String getSelectedItem(JComboBox cb) {
    return strOrNull(cb.getSelectedItem());
  }

  static public <A extends JComponent> A componentPopupMenuItem(A c, final String name, final Object action) {
    componentPopupMenu(c, new VF1<JPopupMenu>() {

      public void get(JPopupMenu menu) {
        try {
          addMenuItem(menu, name, action);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "addMenuItem(menu, name, action);";
      }
    });
    return c;
  }

  static public void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) {
    componentPopupMenu(c, new VF1<JPopupMenu>() {

      public void get(JPopupMenu menu) {
        try {
          addMenuItem(menu, menuItem);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "addMenuItem(menu, menuItem);";
      }
    });
  }

  static public String copyTextToClipboard(Object _text) {
    String text = str(_text);
    StringSelection selection = new StringSelection(text);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
    vmBus_send("newClipboardContents", text);
    return text;
  }

  static public Set vm_generalWeakSet(Object name) {
    synchronized (get(javax(), "generalMap")) {
      Set set = (Set) (vm_generalMap_get(name));
      if (set == null)
        vm_generalMap_put(name, set = newWeakHashSet());
      return set;
    }
  }

  static public boolean setText_opt = true;

  static public <A extends JTextComponent> A setText(A c, Object text) {
    setText((JComponent) c, text);
    return c;
  }

  static public <A extends JComboBox> A setText(final A c, Object text) {
    final String s = strUnnull(text);
    {
      swing(new Runnable() {

        public void run() {
          try {
            c.getEditor().setItem(s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.getEditor().setItem(s);";
        }
      });
    }
    return c;
  }

  static public void setText(JLabel c, Object text) {
    setText((JComponent) c, text);
  }

  static public JButton setText(JButton c, Object text) {
    setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
    return c;
  }

  static public <A extends JComponent> A setText(final A c, Object text) {
    if (c == null)
      return null;
    final String s = strUnnull(text);
    {
      swing(new Runnable() {

        public void run() {
          try {
            if (!setText_opt || neq(callOpt(c, "getText"), s))
              call(c, "setText", s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n      call(c, \"setText\", s);";
        }
      });
    }
    return c;
  }

  static public void setCaretPosition(final JTextComponent c, final int pos) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            try {
              int _pos = max(0, min(l(c.getText()), pos));
              c.setCaretPosition(_pos);
            } catch (Throwable __e) {
              _handleException(__e);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "pcall {\r\n      int _pos = max(0, min(l(c.getText()), pos));\r\n      c.setCaret...";
        }
      });
    }
  }

  static public ChangeListener changeListener(final Object r) {
    return new ChangeListener() {

      public void stateChanged(ChangeEvent e) {
        pcallF(r);
      }
    };
  }

  static public ItemListener itemListener(final Object r) {
    return new ItemListener() {

      public void itemStateChanged(ItemEvent e) {
        pcallF(r);
      }
    };
  }

  static public void onUpdate(JComponent c, final Object r) {
    if (c instanceof JTextComponent)
      ((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {

        public void insertUpdate(DocumentEvent e) {
          call(r);
        }

        public void removeUpdate(DocumentEvent e) {
          call(r);
        }

        public void changedUpdate(DocumentEvent e) {
          call(r);
        }
      });
    else if (c instanceof ItemSelectable)
      ((ItemSelectable) c).addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
          call(r);
        }
      });
    else
      print("Warning: onUpdate doesn't know " + getClassName(c));
  }

  static public void onUpdate(List<? extends JComponent> l, Object r) {
    for (JComponent c : l) onUpdate(c, r);
  }

  static public boolean isEditableComboBox(final JComboBox cb) {
    return cb != null && swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return cb.isEditable();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret cb.isEditable();";
      }
    });
  }

  static public JTextField textFieldFromComboBox(JComboBox cb) {
    return (JTextField) cb.getEditor().getEditorComponent();
  }

  static public JComboBox onSelectedItem(final JComboBox cb, final VF1<String> f) {
    addActionListener(cb, new Runnable() {

      public void run() {
        try {
          pcallF(f, selectedItem(cb));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcallF(f, selectedItem(cb))";
      }
    });
    return cb;
  }

  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 Object pcallFunction(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable __e) {
      _handleException(__e);
    }
    return null;
  }

  static public <A, B> B mapGet(Map<A, B> map, A a) {
    return map == null || a == null ? null : map.get(a);
  }

  static public <A, B> B mapGet(A a, Map<A, B> map) {
    return map == null || a == null ? null : map.get(a);
  }

  static public boolean even(int i) {
    return (i & 1) == 0;
  }

  static public boolean even(long i) {
    return (i & 1) == 0;
  }

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

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

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

  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 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 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 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 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> 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 int smartIndexOf(String s, String sub, int i) {
    if (s == null)
      return 0;
    i = s.indexOf(sub, min(i, l(s)));
    return i >= 0 ? i : l(s);
  }

  static public int smartIndexOf(String s, int i, char c) {
    return smartIndexOf(s, c, i);
  }

  static public int smartIndexOf(String s, char c, int i) {
    if (s == null)
      return 0;
    i = s.indexOf(c, min(i, l(s)));
    return i >= 0 ? i : l(s);
  }

  static public int smartIndexOf(String s, String sub) {
    return smartIndexOf(s, sub, 0);
  }

  static public int smartIndexOf(String s, char c) {
    return smartIndexOf(s, c, 0);
  }

  static public <A> int smartIndexOf(List<A> l, A sub) {
    return smartIndexOf(l, sub, 0);
  }

  static public <A> int smartIndexOf(List<A> l, int start, A sub) {
    return smartIndexOf(l, sub, start);
  }

  static public <A> int smartIndexOf(List<A> l, A sub, int start) {
    int i = indexOf(l, sub, start);
    return i < 0 ? l(l) : i;
  }

  static public boolean isRandomID(String s, int len) {
    if (l(s) != len)
      return false;
    for (int i = 0; i < len; i++) if (!Character.isLetter(s.charAt(i)))
      return false;
    return true;
  }

  static public Map<String, String> mechMap(String listName) {
    return mechMapCI(listName);
  }

  static public String indentx(String s) {
    return indentx(indent_default, s);
  }

  static public String indentx(int n, String s) {
    return dropSuffix(repeat(' ', n), indent(n, s));
  }

  static public String indentx(String indent, String s) {
    return dropSuffix(indent, indent(indent, s));
  }

  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 File getProgramFile(String progID, String fileName) {
    if (new File(fileName).isAbsolute())
      return new File(fileName);
    return new File(getProgramDir(progID), fileName);
  }

  static public File getProgramFile(String fileName) {
    return getProgramFile(getProgramID(), fileName);
  }

  static public Lock appendToFile_lock = lock();

  static public boolean appendToFile_keepOpen = false;

  static public HashMap<String, Writer> appendToFile_writers = new HashMap();

  static public void appendToFile(String path, String s) {
    try {
      Lock __0 = appendToFile_lock;
      lock(__0);
      try {
        mkdirsForFile(new File(path));
        path = getCanonicalPath(path);
        Writer writer = appendToFile_writers.get(path);
        if (writer == null) {
          writer = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(path, true), "UTF-8"));
          if (appendToFile_keepOpen)
            appendToFile_writers.put(path, writer);
        }
        writer.write(s);
        if (!appendToFile_keepOpen)
          writer.close();
      } finally {
        unlock(__0);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void appendToFile(File path, String s) {
    if (path != null)
      appendToFile(path.getPath(), s);
  }

  static public void cleanMeUp_appendToFile() {
    AutoCloseable __2 = tempCleaningUp();
    try {
      Lock __1 = appendToFile_lock;
      lock(__1);
      try {
        closeAllWriters(values(appendToFile_writers));
        appendToFile_writers.clear();
      } finally {
        unlock(__1);
      }
    } finally {
      _close(__2);
    }
  }

  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 <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 <A> List<A> filter(Iterable<A> c, Object pred) {
    if (pred instanceof F1)
      return filter(c, (F1<A, Boolean>) pred);
    List x = new ArrayList();
    if (c != null)
      for (Object o : c) if (isTrue(callF(pred, o)))
        x.add(o);
    return x;
  }

  static public List filter(Object pred, Iterable c) {
    return filter(c, pred);
  }

  static public <A, B extends A> List<B> filter(Iterable<B> c, F1<A, Boolean> pred) {
    List x = new ArrayList();
    if (c != null)
      for (B o : c) if (pred.get(o))
        x.add(o);
    return x;
  }

  static public <A, B extends A> List<B> filter(F1<A, Boolean> pred, Iterable<B> c) {
    return filter(c, pred);
  }

  static public <A, B extends A> List<B> filter(Iterable<B> c, IF1<A, Boolean> pred) {
    List x = new ArrayList();
    if (c != null)
      for (B o : c) if (pred.get(o))
        x.add(o);
    return x;
  }

  static public <A, B extends A> List<B> filter(IF1<A, Boolean> pred, Iterable<B> c) {
    return filter(c, pred);
  }

  static public List<String> allMethodNames(Object o) {
    Class c = _getClass(o);
    TreeSet<String> names = new TreeSet();
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) names.add(m.getName());
      c = c.getSuperclass();
    }
    return asList(names);
  }

  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 formatWithThousandsSeparator(long l) {
    return NumberFormat.getInstance(new Locale("en_US")).format(l);
  }

  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 boolean startsWithOneOf(String s, String... l) {
    for (String x : l) if (startsWith(s, x))
      return true;
    return false;
  }

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

  static public void warnIfOddCount(Object... list) {
    if (odd(l(list)))
      printStackTrace("Odd list size: " + list);
  }

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

  static public String appendToMechList(String name, String text) {
    return botAppendToMechList_uniqCI(name, text);
  }

  static public String appendToMechList(String name, Collection<String> lines) {
    return botAppendToMechList_uniqCI(name, lines);
  }

  static public String formatDoubleArrowMap(Map map) {
    return lines(mapMapToList(map, new F2<Object, Object, String>() {

      public String get(Object key, Object value) {
        try {
          return str(key) + " => " + str(value);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "str(key) + \" => \" + str(value)";
      }
    }));
  }

  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 public Runnable addThreadInfoToRunnable(final Object r) {
    final Object info = _threadInfo();
    return info == null ? asRunnable(r) : new Runnable() {

      public void run() {
        try {
          _inheritThreadInfo(info);
          callF(r);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "_inheritThreadInfo(info); callF(r);";
      }
    };
  }

  static public JTextArea wrappedTextArea(final JTextArea ta) {
    enableWordWrapForTextArea(ta);
    return ta;
  }

  static public JTextArea wrappedTextArea() {
    return wrappedTextArea(jtextarea());
  }

  static public JTextArea wrappedTextArea(String text) {
    JTextArea ta = wrappedTextArea();
    setText(ta, text);
    return ta;
  }

  static public <A extends JComponent> A onClick(final A c, final Object runnable) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.addMouseListener(new MouseAdapter() {

              public void mouseClicked(MouseEvent e) {
                callF(runnable, e);
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.addMouseListener(new MouseAdapter {\r\n      public void mouseClicked(MouseEv...";
        }
      });
    }
    return c;
  }

  static public void onClick(JButton btn, final Object runnable) {
    onEnter(btn, runnable);
  }

  static public void disposeWindow(final Window window) {
    if (window != null) {
      swing(new Runnable() {

        public void run() {
          try {
            window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));
            myFrames_list.remove(window);
            window.dispose();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //...";
        }
      });
    }
  }

  static public void disposeWindow(final Component c) {
    disposeWindow(getWindow(c));
  }

  static public void disposeWindow(Object o) {
    if (o != null)
      disposeWindow(((Component) o));
  }

  static public void disposeWindow() {
    disposeWindow(heldInstance(Component.class));
  }

  static public Font typeWriterFont() {
    return typeWriterFont(iround(14 * getSwingFontScale()));
  }

  static public Font typeWriterFont(int size) {
    return new Font("Courier", Font.PLAIN, size);
  }

  static public Window getWindow(Object o) {
    if (!(o instanceof Component))
      return null;
    Component c = (Component) o;
    while (c != null) {
      if (c instanceof Window)
        return (Window) c;
      c = c.getParent();
    }
    return null;
  }

  static public Dimension getScreenSize() {
    return Toolkit.getDefaultToolkit().getScreenSize();
  }

  static public void swingLater(long delay, final Object r) {
    javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
    timer.setRepeats(false);
    timer.start();
  }

  static public void swingLater(Object r) {
    SwingUtilities.invokeLater(toRunnable(r));
  }

  static public int toMS_int(double seconds) {
    return toInt_checked((long) (seconds * 1000));
  }

  static public double toDouble(Object o) {
    if (o instanceof Number)
      return ((Number) o).doubleValue();
    if (o instanceof BigInteger)
      return ((BigInteger) o).doubleValue();
    if (o == null)
      return 0.0;
    throw fail(o);
  }

  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 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 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 <A> A[] makeArray(Class<A> type, int n) {
    return (A[]) Array.newInstance(type, n);
  }

  static public Map<JFrame, Boolean> myFrames_list = weakHashMap();

  static public List<JFrame> myFrames() {
    return swing(new F0<List<JFrame>>() {

      public List<JFrame> get() {
        try {
          return keysList(myFrames_list);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret keysList(myFrames_list);";
      }
    });
  }

  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 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 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 Object vm_generalMap_get(Object key) {
    return vm_generalMap().get(key);
  }

  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 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 List<Class> getClasses(Object[] array) {
    List<Class> l = emptyList(l(array));
    for (Object o : array) l.add(_getClass(o));
    return l;
  }

  static public <A> void listThreadLocalAdd(ThreadLocal<List<A>> tl, A a) {
    List<A> l = tl.get();
    if (l == null)
      tl.set(l = new ArrayList());
    l.add(a);
  }

  static public <A> A listThreadLocalPopLast(ThreadLocal<List<A>> tl) {
    List<A> l = tl.get();
    if (l == null)
      return null;
    A a = popLast(l);
    if (empty(l))
      tl.set(null);
    return a;
  }

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

  static public void addMenuItem(JPopupMenu menu, String text, Object action) {
    menu.add(jmenuItem(text, action));
  }

  static public void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
    menu.add(menuItem);
  }

  static public void addMenuItem(JMenu menu, String text, Object action) {
    menu.add(jmenuItem(text, action));
  }

  static public void addMenuItem(Menu menu, String text, Object action) {
    menu.add(menuItem(text, action));
  }

  static public void addMenuItem(JMenu menu, JMenuItem menuItem) {
    menu.add(menuItem);
  }

  static public Object vm_generalMap_put(Object key, Object value) {
    return mapPutOrRemove(vm_generalMap(), key, value);
  }

  static public <A> Set<A> newWeakHashSet() {
    return synchroWeakHashSet();
  }

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

  static public String jlabel_textAsHTML_center_ifNeeded(String text) {
    if (swic(text, "<html>") && ewic(text, "</html>"))
      return text;
    if (!containsNewLines(text))
      return text;
    return jlabel_textAsHTML_center(text);
  }

  static public void addActionListener(JTextField tf, final Runnable action) {
    onEnter(tf, action);
  }

  static public void addActionListener(final JComboBox cb, final Runnable action) {
    if (cb != null) {
      swing(new Runnable() {

        public void run() {
          try {
            cb.addActionListener(actionListener(action));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "cb.addActionListener(actionListener(action));";
        }
      });
    }
  }

  static public void addActionListener(final AbstractButton b, final Runnable action) {
    if (b != null) {
      swing(new Runnable() {

        public void run() {
          try {
            b.addActionListener(actionListener(action));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "b.addActionListener(actionListener(action));";
        }
      });
    }
  }

  static public String selectedItem(JList l) {
    return getSelectedItem(l);
  }

  static public String selectedItem(JComboBox cb) {
    return getSelectedItem(cb);
  }

  static public Object callFunction(Object f, Object... args) {
    return callF(f, args);
  }

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

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

  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 void _registerIO(Object object, String path, boolean opened) {
  }

  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 Map<String, Pair<String, Map<String, String>>> mechMapCI_cache = synchroMap();

  static public Map<String, String> mechMapCI(String listName) {
    Pair<String, Map<String, String>> p = mechMapCI_cache.get(listName);
    String text = mechList_raw(listName);
    if (p != null && eq(p.a, text))
      return p.b;
    String parsing = first(mechList_opt(listName + " | Parsing"));
    Map<String, String> map;
    if (parsing == null)
      map = parseDoubleArrowMapCI(tlft(text));
    else
      map = asCIMap((Map<String, String>) callAndMake(parsing, text));
    p = pair(text, map);
    mechMapCI_cache.put(listName, p);
    return p.b;
  }

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

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

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

  static public File getProgramDir(String snippetID) {
    return programDir(snippetID);
  }

  static public String getCanonicalPath(File f) {
    try {
      return f == null ? null : f.getCanonicalPath();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String getCanonicalPath(String path) {
    return getCanonicalPath(newFile(path));
  }

  static public AutoCloseable tempCleaningUp() {
    return tempSetTL(ping_isCleanUpThread, true);
  }

  static public void closeAllWriters(Collection<? extends Writer> l) {
    for (Writer w : unnull(l)) {
      try {
        w.close();
      } catch (Throwable __e) {
        _handleException(__e);
      }
    }
  }

  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 Throwable getException(Runnable r) {
    try {
      callF(r);
      return null;
    } catch (Throwable e) {
      return e;
    }
  }

  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 String botAppendToMechList_uniqCI(String name, String text) {
    return botAppendToMechList_mode(name, text, "uniqCI");
  }

  static public String botAppendToMechList_uniqCI(String name, Collection<String> lines) {
    return botAppendToMechList_mode(name, lines, "uniqCI");
  }

  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 List mapMapToList(Map map, Object f) {
    return map(map, f);
  }

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

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

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

  static public Runnable asRunnable(Object o) {
    return toRunnable(o);
  }

  static public void _inheritThreadInfo(Object info) {
    _threadInheritInfo(info);
  }

  static public void enableWordWrapForTextArea(final JTextArea ta) {
    if (ta != null) {
      swing(new Runnable() {

        public void run() {
          try {
            ta.setLineWrap(true);
            ta.setWrapStyleWord(true);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ta.setLineWrap(true);\r\n    ta.setWrapStyleWord(true);";
        }
      });
    }
  }

  static public JTextArea jtextarea() {
    return jTextArea();
  }

  static public JTextArea jtextarea(String text) {
    return jTextArea(text);
  }

  static public <A> A heldInstance(Class<A> c) {
    List<Object> l = holdInstance_l.get();
    for (int i = l(l) - 1; i >= 0; i--) {
      Object o = l.get(i);
      if (isInstanceOf(o, c))
        return (A) o;
    }
    throw fail("No instance of " + className(c) + " held");
  }

  static public float getSwingFontScale() {
    return or((Float) vm_generalMap_get("swingFontScale_value"), 1f);
  }

  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);
    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 toInt_checked(long l) {
    if (l != (int) l)
      throw fail("Too large for int: " + l);
    return (int) l;
  }

  static public Map<String, String> parseDoubleLeftArrowMapCI_tlft(String s) {
    return parseDoubleLeftArrowMapCI(tlft(s));
  }

  static public <A, B> Map<A, B> weakHashMap() {
    return newWeakHashMap();
  }

  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 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 Map vm_generalMap_map;

  static public Map vm_generalMap() {
    if (vm_generalMap_map == null)
      vm_generalMap_map = (Map) get(javax(), "generalMap");
    return vm_generalMap_map;
  }

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

  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 boolean jmenuItem_newThreads = false;

  static public JMenuItem jmenuItem(final String text) {
    return jMenuItem(text, null);
  }

  static public JMenuItem jmenuItem(final String text, final Object r) {
    return swing(new F0<JMenuItem>() {

      public JMenuItem get() {
        try {
          Pair<String, Integer> p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text));
          JMenuItem mi = new JMenuItem(p.a);
          if (startsWith(text, "[disabled] "))
            disableMenuItem(mi);
          if (p.b != 0)
            mi.setMnemonic(p.b);
          mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r));
          return mi;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Pair<S, Int> p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n    JM...";
      }
    });
  }

  static public MenuItem menuItem(String text, final Object r) {
    MenuItem mi = new MenuItem(text);
    mi.addActionListener(actionListener(r));
    return mi;
  }

  static public <A, B> B mapPutOrRemove(Map<A, B> map, A key, B value) {
    if (map != null && key != null)
      if (value != null)
        return map.put(key, value);
      else
        return map.remove(key);
    return null;
  }

  static public <A> Set<A> synchroWeakHashSet() {
    return Collections.newSetFromMap((Map) newWeakHashMap());
  }

  static public boolean swic(String a, String b) {
    return startsWithIgnoreCase(a, b);
  }

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

  static public boolean containsNewLines(String s) {
    return containsNewLine(s);
  }

  static public String jlabel_textAsHTML_center(String text) {
    return "<html><div style=\"text-align: center;\">" + replace(htmlencode(text), "\n", "<br>") + "</div></html>";
  }

  static public List collectField(Collection 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, Collection c) {
    return collectField(c, field);
  }

  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 Map synchroMap() {
    return synchroHashMap();
  }

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

  static public ExpiringMap2<String, String> mechList_raw_cache = new ExpiringMap2(10000).setMap(ciMap());

  static public Lock mechList_raw_lock = lock();

  static public int mechList_raw_timeout = 60000;

  static public String mechList_raw(String name) {
    try {
      Lock __0 = mechList_raw_lock;
      lock(__0);
      try {
        if (empty(name))
          return "";
        String src = mechList_raw_cache.get(name);
        if (src != null)
          return src;
        src = mechList_raw_fresh(name);
        if (src != null)
          mechList_raw_cache.put(name, src);
        return src;
      } finally {
        unlock(__0);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public VF2<String, Object> mechList_raw_listener = new VF2<String, Object>() {

    public void get(String msg, Object arg) {
      try {
        if (eq(msg, "mechChange") && arg instanceof String) {
          mechList_raw_cache.remove((String) arg);
        }
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public String toString() {
      return "if (eq(msg, 'mechChange) && arg instanceof S) {\r\n    //print(\"Got change noti...";
    }
  };

  static public void _onLoad_mechList_raw() {
    add(vm_busListeners_live(), mechList_raw_listener);
  }

  static public void cleanMeUp_mechList_raw() {
    remove(vm_busListeners_live(), mechList_raw_listener);
  }

  static public List<String> mechList_opt(String name) {
    return mechList_opt_tlft(name);
  }

  static public Map<String, String> parseDoubleArrowMapCI(List<String> l) {
    return parseDoubleArrowMap((Map) ciMap(), l);
  }

  static public List<String> tlft(String s) {
    return toLinesFullTrim(s);
  }

  static public List<String> tlft(File f) {
    return toLinesFullTrim(f);
  }

  static public <B> TreeMap<String, B> asCIMap(Map<String, B> map) {
    return asCaseInsensitiveMap(map);
  }

  static public Object callAndMake(String functionName, Object... args) {
    return callAndMake_orDirect(functionName, args);
  }

  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 <A> AutoCloseable tempSetTL(ThreadLocal<A> tl, A a) {
    return tempSetThreadLocal(tl, a);
  }

  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 String botAppendToMechList_mode(String name, String text, String mode) {
    if (empty(name) || empty(text))
      return "";
    String result = postPageSilently("http://butter.botcompany.de:8080/mech/raw/bot-list-append", arrayPlus(muricaCredentials(), "name", name, "text", text, "mode", mode));
    if (!swic(result, "No change")) {
      if (eq(mechMode().readMode, "localCopies")) {
        print("Appending to local list copy: " + name);
        appendToLocalMechListCopy(name, text);
      }
      mech_notifyBusOfChange(name);
      mechList_clearCache(name);
    }
    return result;
  }

  static public String botAppendToMechList_mode(String name, Collection<String> lines, String mode) {
    if (empty(lines))
      return "";
    return botAppendToMechList_mode(name, lines(lines), mode);
  }

  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 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 JTextArea jTextArea() {
    return jTextArea("");
  }

  static public JTextArea jTextArea(final String text) {
    return jTextAreaWithUndo(text);
  }

  static public boolean isInstanceOf(Object o, Class type) {
    return type.isInstance(o);
  }

  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 Map<String, String> parseDoubleLeftArrowMapCI(List<String> l) {
    return parseDoubleLeftArrowMap((Map) ciMap(), l);
  }

  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 <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 JMenuItem jMenuItem(final String text) {
    return jmenuItem(text);
  }

  static public JMenuItem jMenuItem(String text, Object r) {
    return jmenuItem(text, r);
  }

  static public Pair<String, Integer> jmenu_autoMnemonic(String s) {
    int i = indexOf(s, '&');
    if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i + 1)))
      return pair(substring(s, 0, i) + substring(s, i + 1), (int) s.charAt(i + 1));
    return pair(s, 0);
  }

  static public JMenuItem disableMenuItem(final JMenuItem mi) {
    if (mi != null) {
      swing(new Runnable() {

        public void run() {
          try {
            mi.setEnabled(false);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "mi.setEnabled(false);";
        }
      });
    }
    return mi;
  }

  static public ActionListener actionListenerInNewThread(final Object runnable) {
    return actionListenerInNewThread(runnable, null);
  }

  static public ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
    if (runnable instanceof ActionListener)
      return (ActionListener) runnable;
    return new java.awt.event.ActionListener() {

      public void actionPerformed(java.awt.event.ActionEvent _evt) {
        try {
          startThread("Action Listener", new Runnable() {

            public void run() {
              try {
                AutoCloseable __0 = holdInstance(instanceToHold);
                try {
                  callF(runnable);
                } finally {
                  _close(__0);
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "AutoCloseable __0 = holdInstance(instanceToHold); try {\r\n      callF(runnable...";
            }
          });
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

  static public boolean startsWithIgnoreCase(String a, String b) {
    return regionMatchesIC(a, 0, b, 0, b.length());
  }

  static public boolean containsNewLine(String s) {
    return contains(s, '\n');
  }

  static public <A> List<A> replace(List<A> l, A a, A b) {
    for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
      l.set(i, b);
    return l;
  }

  static public <A> List<A> replace(A a, A b, List<A> l) {
    return replace(l, a, b);
  }

  static public String replace(String s, String a, String b) {
    return s == null ? null : a == null || b == null ? s : s.replace(a, b);
  }

  static public String replace(String s, char a, char b) {
    return s == null ? null : s.replace(a, b);
  }

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

  static public String htmlencode(String s) {
    if (s == null)
      return "";
    StringBuilder out = new StringBuilder(Math.max(16, s.length()));
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
        int cp = s.codePointAt(i);
        out.append("&#x");
        out.append(intToHex_flexLength(cp));
        out.append(';');
        i += Character.charCount(cp) - 1;
      } else
        out.append(c);
    }
    return out.toString();
  }

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

  static public String mechList_raw_fresh(String name) {
    return mechList_opt_raw_fresh(name);
  }

  static public void add(BitSet bs, int i) {
    bs.set(i);
  }

  static public <A> boolean add(Collection<A> c, A a) {
    return c != null && c.add(a);
  }

  static public void add(Container c, Component x) {
    addToContainer(c, x);
  }

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

  static public <A> void remove(Collection<A> l, A a) {
    if (l != null)
      l.remove(a);
  }

  static public List<String> mechList_opt_tlft(String name) {
    return mechList_opt_tlft_cached(name);
  }

  static public Map<String, String> parseDoubleArrowMap(Map<String, String> map, List<String> l) {
    for (String s : l) {
      List<String> x = splitAtDoubleArrow_bothDirections(s);
      if (l(x) == 2)
        map.put(first(x), second(x));
    }
    return map;
  }

  static public List<String> toLinesFullTrim(String s) {
    List<String> l = new ArrayList();
    for (String line : toLines(s)) if (nempty(line = trim(line)))
      l.add(line);
    return l;
  }

  static public List<String> toLinesFullTrim(File f) {
    List<String> l = new ArrayList();
    for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
      l.add(line);
    return l;
  }

  static public <B> TreeMap<String, B> asCaseInsensitiveMap(Map<String, B> map) {
    if (isCIMap(map))
      return (TreeMap) map;
    TreeMap<String, B> m = ciMap();
    m.putAll(map);
    return m;
  }

  static public Object callAndMake_orDirect(String functionName, List args) {
    return callAndMake_orDirect(functionName, toObjectArray(args));
  }

  static public Object callAndMake_orDirect(String functionName, Object... args) {
    if (functionName == null)
      return null;
    if (hasMethod(mc(), functionName, args))
      return callMC(functionName, args);
    else
      return makeAndCall_cached(functionName, args);
  }

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

  static volatile public String caseID_caseID;

  static public String caseID() {
    return caseID_caseID;
  }

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

  static public MechMode mechMode_value = new MechMode();

  static public MechMode mechMode() {
    return mechMode_value;
  }

  static public <A> List<A> listMinusSet(Iterable<A> l, Collection<A> stuff) {
    if (l == null)
      return null;
    if (empty(stuff))
      return asList(l);
    Set<A> set = asSet(stuff);
    List<A> l2 = new ArrayList();
    for (A a : l) if (!set.contains(a))
      l2.add(a);
    return l2;
  }

  static public <A> List<A> listMinusSet(Iterable<A> l, Collection<A> stuff, Collection<A> stuff2) {
    return listMinusSet(listMinusSet(l, stuff), stuff2);
  }

  static public TreeSet<String> asCISet(Iterable<String> c) {
    return toCaseInsensitiveSet(c);
  }

  static public TreeSet<String> asCISet(String... x) {
    return toCaseInsensitiveSet(x);
  }

  static public void mech_notifyBusOfChange(String listName) {
    vmBus_send("mechChange", listName);
  }

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

  static public void mechList_clearCache(String listName) {
    {
      AutoCloseable __0 = tempSetTL(mechList_clearCache_inFunction, true);
      try {
        print("Sending mech clear: " + listName);
        vmBus_send("mechList_clearCache", listName);
      } finally {
        _close(__0);
      }
    }
    mechList_clearCache_noSend(listName);
  }

  static public void mechList_clearCache_noSend(String listName) {
    for (String field : mcFields()) if (startsWithEndsWith(field, "mech", "_cache")) {
      Object o = getOptMC(field);
      if (o instanceof Map)
        removeFromMapCI_sync((Map) o, listName);
    }
  }

  static public String postPageSilently(String url, Object... params) {
    return doPostSilently(litmap(params), url);
  }

  static public Object[] arrayPlus(Object[] a1, Object... a2) {
    return concatArrays(a1, a2);
  }

  static public Object[] muricaCredentials() {
    String pass = muricaPassword();
    return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0];
  }

  static public void appendToLocalMechListCopy(String listName, String text) {
    appendToTextFile(remoteMechListMirrorFile(listName), "\n" + text);
  }

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

  static public JTextArea jTextAreaWithUndo() {
    return jTextAreaWithUndo("");
  }

  static public JTextArea jTextAreaWithUndo(final String text) {
    return jenableUndoRedo(swingNu(JTextArea.class, text));
  }

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

  static public Map<String, String> parseDoubleLeftArrowMap(Map<String, String> map, List<String> l) {
    for (String s : l) {
      List<String> x = splitAtDoubleLeftArrow(s);
      if (l(x) == 2)
        map.put(second(x), first(x));
    }
    return map;
  }

  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 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 boolean isLetterOrDigit(char c) {
    return Character.isLetterOrDigit(c);
  }

  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 String intToHex_flexLength(int i) {
    return Integer.toHexString(i);
  }

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

  static public String mechList_opt_raw_fresh(String name) {
    Object readMode = mechMode().readMode;
    if (readMode instanceof File) {
      String md5Name = uniqueFileNameUsingMD5_80_v2(upper(name));
      return loadTextFileFromZipFile((File) readMode, md5Name);
    }
    boolean useLocal = false, useRemote = true;
    if (eq(readMode, "mergeLocalAndRemote"))
      useLocal = true;
    else if (eq(readMode, "local")) {
      useLocal = true;
      useRemote = false;
    }
    String s = "";
    if (useRemote) {
      if (eq(mechMode().readMode, "localCopies"))
        s = unnull(loadTextFile(remoteMechListMirrorFile(name)));
      else
        s = serverMechList_raw_fresh(name, true);
    }
    if (useLocal)
      s = appendNewLineIfNempty(s) + localMechList_opt_raw_fresh(name);
    return s;
  }

  static public void addToContainer(final Container a, final Component b) {
    if (a != null && b != null) {
      swing(new Runnable() {

        public void run() {
          try {
            a.add(b);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "a.add(b);";
        }
      });
    }
  }

  static public Map<String, MechListDependentCache<List<String>>> mechList_opt_tlft_cached_cache = ciMap();

  static public Lock mechList_opt_tlft_cached_lock = lock();

  static public List<String> mechList_opt_tlft_cached(String name) {
    MechListDependentCache<List<String>> listCache;
    {
      Lock __0 = mechList_opt_tlft_cached_lock;
      lock(__0);
      try {
        listCache = mechList_opt_tlft_cached_cache.get(name);
        if (listCache == null)
          mechList_opt_tlft_cached_cache.put(name, listCache = new MechListDependentCache(name, new F1<String, List<String>>() {

            public List<String> get(String x) {
              try {
                return tlft(x);
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "tlft(x)";
            }
          }));
      } finally {
        unlock(__0);
      }
    }
    return listCache.get();
  }

  static public List<String> splitAtDoubleArrow_bothDirections(String s) {
    return splitAtDoubleArrow_bothDirections(javaTok(s));
  }

  static public List<String> splitAtDoubleArrow_bothDirections(List<String> tok) {
    List<String> l = splitAtDoubleArrow(tok);
    if (l(l) != 2)
      l = reversedList(splitAtDoubleLeftArrow(tok));
    return l;
  }

  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 char second(String s) {
    return charAt(s, 1);
  }

  static public boolean isCIMap(Map m) {
    return m instanceof TreeMap && ((TreeMap) m).comparator() == caseInsensitiveComparator();
  }

  static public Object[] toObjectArray(Collection c) {
    List l = asList(c);
    return l.toArray(new Object[l.size()]);
  }

  static public boolean hasMethod(Object o, String method, Object... args) {
    return findMethod_cached(o, method, args) != null;
  }

  static public ThreadLocal makeAndCall_initChild = new ThreadLocal();

  static public Object makeAndCall_cached(String functionName, Object... args) {
    Class c = loadFunctions_cached(functionName);
    AutoCloseable closer = (AutoCloseable) (callF(makeAndCall_initChild.get(), c));
    AutoCloseable __0 = closer;
    try {
      return preciseCall(c, functionName, args);
    } finally {
      _close(__0);
    }
  }

  static public Set asSet(Object[] array) {
    HashSet set = new HashSet();
    for (Object o : array) if (o != null)
      set.add(o);
    return set;
  }

  static public Set<String> asSet(String[] array) {
    TreeSet<String> set = new TreeSet();
    for (String o : array) if (o != null)
      set.add(o);
    return set;
  }

  static public <A> Set<A> asSet(Iterable<A> l) {
    if (l instanceof Set)
      return (Set) l;
    HashSet<A> set = new HashSet();
    for (A o : unnull(l)) if (o != null)
      set.add(o);
    return set;
  }

  static public TreeSet<String> toCaseInsensitiveSet(Iterable<String> c) {
    if (isCISet(c))
      return (TreeSet) c;
    TreeSet<String> set = caseInsensitiveSet();
    addAll(set, c);
    return set;
  }

  static public TreeSet<String> toCaseInsensitiveSet(String... x) {
    TreeSet<String> set = caseInsensitiveSet();
    addAll(set, x);
    return set;
  }

  static public Set<String> mcFields() {
    return staticFieldNames(mc());
  }

  static public boolean startsWithEndsWith(String s, String prefix, String suffix) {
    return startsWith(s, prefix) && endsWith(s, suffix);
  }

  static public boolean startsWithEndsWith(String s, String prefixSuffix) {
    return startsWithEndsWith(s, prefixSuffix, prefixSuffix);
  }

  static public Object getOptMC(String field) {
    return getOpt(mc(), field);
  }

  static public void removeFromMapCI_sync(Map<String, Object> map, String key) {
    if (map == null)
      return;
    synchronized (getMutex(map)) {
      for (String k : cloneList(keys(map))) if (eqic(key, k))
        map.remove(k);
    }
  }

  static public String doPostSilently(Map urlParameters, String url) {
    return doPostSilently(makePostData(urlParameters), url);
  }

  static public String doPostSilently(String urlParameters, String url) {
    doPost_silently.set(true);
    return doPost(urlParameters, url);
  }

  static public Object[] concatArrays(Object[]... arrays) {
    int l = 0;
    for (Object[] a : arrays) l += l(a);
    Object[] x = new Object[l];
    int i = 0;
    for (Object[] a : arrays) if (a != null) {
      System.arraycopy(a, 0, x, i, l(a));
      i += l(a);
    }
    return x;
  }

  static volatile public boolean muricaPassword_pretendNotAuthed = false;

  static public String muricaPassword() {
    if (muricaPassword_pretendNotAuthed)
      return null;
    return trim(loadTextFile(muricaPasswordFile()));
  }

  static public void appendToTextFile(File file, String s) {
    appendToFile(file, s);
  }

  static public void appendToTextFile(String file, String s) {
    appendToTextFile(programFile(file), s);
  }

  static public File remoteMechListMirrorFile(String listName) {
    return newFile(remoteMechListMirrorsDir(), uniqueFileNameUsingMD5_80_v2(upper(listName)));
  }

  static public List<String> splitAtDoubleLeftArrow(String s) {
    return splitAtDoubleLeftArrow(javaTok(s));
  }

  static public List<String> splitAtDoubleLeftArrow(List<String> tok) {
    List<String> l = new ArrayList();
    int i = 0;
    while (i < l(tok)) {
      int j = indexOfSubList(tok, ll("<", "", "="), i);
      if (i >= l(tok))
        break;
      if (j < 0)
        j = l(tok);
      l.add(trimJoin(tok.subList(i, j)));
      i = j + 3;
    }
    return l;
  }

  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 Comparator<String> caseInsensitiveComparator() {
    return betterCIComparator();
  }

  static public String uniqueFileNameUsingMD5_80_v2(String fullName) {
    return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName));
  }

  static public String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) {
    return takeFirst(80 - 33, fileNameEncode(fullName)) + " - " + md5;
  }

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

  static public char upper(char c) {
    return Character.toUpperCase(c);
  }

  static public String loadTextFileFromZipFile(File inZip, String fileName) {
    try {
      if (!fileExists(inZip))
        return null;
      try {
        ZipFile zip = new ZipFile(inZip);
        try {
          return loadTextFileFromZipFile(zip, fileName);
        } finally {
          _close(zip);
        }
      } catch (Throwable e) {
        throw fail(f2s(inZip), e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadTextFileFromZipFile(ZipFile zip, String fileName) {
    try {
      ZipEntry entry = zip.getEntry(fileName);
      if (entry == null)
        return null;
      InputStream fin = zip.getInputStream(entry);
      try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copyStream(fin, baos);
        return fromUTF8(baos.toByteArray());
      } finally {
        _close(fin);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean serverMechList_raw_fresh_verbose = false;

  static public String serverMechList_raw_fresh(String name) {
    return serverMechList_raw_fresh(name, false);
  }

  static public String serverMechList_raw_fresh(String name, boolean opt) {
    Lock __0 = downloadLock();
    lock(__0);
    try {
      String text = null;
      try {
        text = loadTextFile(remoteMechListMirrorFile(name));
      } catch (Throwable __e) {
        _handleException(__e);
      }
      Object[] params = muricaCredentialsPlus("md5", md5OrNull(text), "l", l(text), "opt", opt ? 1 : 0, "withStatus", 1);
      String url = "http://butter.botcompany.de:8080/mech/raw/list-text/" + urlencode(name);
      String page = postPageSilently(url, params);
      Map map = jsonDecodeMap(page);
      boolean same = eq(map.get("Same"), true);
      boolean appended = eq(map.get("Appended"), true);
      saveTextFile(remoteMechListMirrorMetaFile(name), struct(getMultipleKeys(map, "Name", "Status")));
      if (!same) {
        if (appended)
          text += (String) map.get("Text");
        else
          text = (String) map.get("Text");
        saveTextFile(remoteMechListMirrorFile(name), text);
        File nameFile = remoteMechListMirrorNameFile(name);
        if (!fileExists(nameFile)) {
          String actualName = or((String) map.get("Name"), name);
          saveTextFile(nameFile, actualName);
        }
      }
      if (serverMechList_raw_fresh_verbose)
        print("Mech list " + name + ": " + (appended ? "appended" : same ? "same" : "downloaded") + ": " + n2(countLines(text), "line"));
      if (!same)
        vmBus_send("remoteMechListMirrorChanged", name);
      return text;
    } finally {
      unlock(__0);
    }
  }

  static public String appendNewLineIfNempty(String s) {
    return empty(s) ? "" : s + "\n";
  }

  static public String localMechList_opt_raw_fresh(String name) {
    return unnull(loadTextFile(localMechListFile(name)));
  }

  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 List<String> splitAtDoubleArrow(String s) {
    return splitAtDoubleArrow(javaTok(s));
  }

  static public List<String> splitAtDoubleArrow(List<String> tok) {
    List<String> l = new ArrayList();
    int i = 0;
    while (i < l(tok)) {
      int j = indexOfSubList(tok, splitAtDoubleArrow_tok(), i);
      if (i >= l(tok))
        break;
      if (j < 0)
        j = l(tok);
      l.add(trimJoin(tok.subList(i, j)));
      i = j + 3;
    }
    return l;
  }

  static public <A> List<A> reversedList(Collection<A> l) {
    List<A> x = cloneList(l);
    Collections.reverse(x);
    return x;
  }

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

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

  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 HashMap<Set<String>, Class> loadFunctions_cache = new HashMap();

  static public Lock loadFunctions_cached_lock = lock();

  static public boolean loadFunctions_preferDiskCache = false;

  static public Class loadFunctions_cached(String... functions) {
    return loadFunctions_cached(asList(functions));
  }

  static public Class loadFunctions_cached(Collection<String> functions) {
    TreeSet<String> functionSet = new TreeSet<String>(functions);
    Lock __0 = loadFunctions_cached_lock;
    lock(__0);
    try {
      Class c = loadFunctions_cache.get(functionSet);
      if (c != null)
        return c;
      String cached = getTranspiledStandardFunctionsIfCached(functionSet);
      String transpilation = null;
      if (cached != null && (loadFunctions_preferDiskCache || standardFunctionsCacheUpToDate(functionSet)))
        transpilation = cached;
      if (transpilation != null) {
        print("Loading " + joinWithPlus(functionSet));
        c = veryQuickJava_finish(transpilation, emptyList());
      }
      if (c == null)
        c = loadFunctions(functionSet);
      loadFunctions_cache.put(functionSet, c);
      assertNotNull(loadFunctions_cache.get(functionSet));
      return c;
    } finally {
      unlock(__0);
    }
  }

  static public void loadFunctions_cached_clearCache() {
    Lock __1 = loadFunctions_cached_lock;
    lock(__1);
    try {
      loadFunctions_cache.clear();
    } finally {
      unlock(__1);
    }
  }

  static public void _onLoad_loadFunctions_cached() {
    ownResource(vmBus_onMessage("refreshedTranspiler", new Runnable() {

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

      public String toString() {
        return "loadFunctions_clearCache();";
      }
    }));
  }

  static public boolean preciseCall_debug = false;

  static public Object preciseCall(Object o, String method, Object... args) {
    try {
      if (o instanceof Class) {
        _MethodCache cache = callOpt_getCache(((Class) o));
        List<Method> methods = cache.cache.get(method);
        Lowest<Method> best = new Lowest();
        if (methods != null)
          for (Method m : methods) {
            {
              if (!(isStaticMethod(m)))
                continue;
            }
            int score = methodApplicabilityScore(m, args);
            if (score < Integer.MAX_VALUE) {
              if (preciseCall_debug)
                print("Method score: " + m + " " + score);
              best.put(m, score);
            }
          }
        Method m = best.get();
        if (m != null)
          return invokeMethod(m, null, args);
        return call_withVarargs(((Class) o), method, args);
      } else
        throw todo();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isCISet(Iterable<String> l) {
    return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
  }

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

  static public TreeSet<String> caseInsensitiveSet(Collection<String> c) {
    return caseInsensitiveSet_treeSet(c);
  }

  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 Set<String> staticFieldNames(Object o) {
    TreeSet<String> fields = new TreeSet();
    Class _c = _getClass(o);
    do {
      for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & Modifier.STATIC) != 0)
        fields.add(f.getName());
      _c = _c.getSuperclass();
    } while (_c != null);
    return fields;
  }

  static public Object getMutex(Object o) {
    return collectionMutex(o);
  }

  static public String makePostData(Map<Object, Object> map) {
    StringBuilder buf = new StringBuilder();
    for (Map.Entry<Object, Object> e : map.entrySet()) {
      String key = (String) (e.getKey());
      Object val = e.getValue();
      if (val != null) {
        String value = str(val);
        if (nempty(buf))
          buf.append("&");
        buf.append(urlencode(key)).append("=").append(urlencode((value)));
      }
    }
    return str(buf);
  }

  static public String makePostData(Object... params) {
    StringBuilder buf = new StringBuilder();
    int n = l(params);
    for (int i = 0; i + 1 < n; i += 2) {
      String key = (String) (params[i]);
      Object val = params[i + 1];
      if (val != null) {
        String value = str(val);
        if (nempty(buf))
          buf.append("&");
        buf.append(urlencode(key)).append("=").append(urlencode((value)));
      }
    }
    return str(buf);
  }

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

  static public ThreadLocal<Long> doPost_timeout = new ThreadLocal();

  static public ThreadLocal<Map<String, String>> doPost_extraHeaders = new ThreadLocal();

  static public String doPost(Map urlParameters, String url) {
    return doPost(makePostData(urlParameters), url);
  }

  static public String doPost(String urlParameters, String url) {
    try {
      URL _url = new URL(url);
      ping();
      return doPost(urlParameters, _url.openConnection(), _url);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String doPost(String urlParameters, URLConnection conn, URL url) {
    try {
      boolean silently = isTrue(optParam(doPost_silently));
      Long timeout = optParam(doPost_timeout);
      Map<String, String> extraHeaders = optPar(doPost_extraHeaders);
      setHeaders(conn);
      for (String key : keys(extraHeaders)) conn.setRequestProperty(key, extraHeaders.get(key));
      int l = lUtf8(urlParameters);
      if (!silently)
        print("Sending POST request: " + hideCredentials(url) + " (" + l + " bytes)");
      if (timeout != null)
        setURLConnectionTimeouts(conn, timeout);
      ((HttpURLConnection) conn).setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-Length", str(l));
      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
      writer.write(urlParameters);
      writer.flush();
      String contents = loadPage_utf8(conn, url, false);
      writer.close();
      return contents;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File muricaPasswordFile() {
    return new File(javaxSecretDir(), "murica/muricaPasswordFile");
  }

  static public File programFile(String name) {
    return prepareProgramFile(name);
  }

  static public File programFile(String progID, String name) {
    return prepareProgramFile(progID, name);
  }

  static public File remoteMechListMirrorsDir() {
    return javaxDataDir("Remote Mech Lists");
  }

  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 String trimJoin(List<String> s) {
    return trim(join(s));
  }

  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 String md5(String text) {
    try {
      if (text == null)
        return "-";
      return bytesToHex(md5_impl(toUtf8(text)));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String md5(byte[] data) {
    if (data == null)
      return "-";
    return bytesToHex(md5_impl(data));
  }

  static public byte[] md5_impl(byte[] data) {
    try {
      return MessageDigest.getInstance("MD5").digest(data);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String md5(File file) {
    return md5OfFile(file);
  }

  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) {
    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 String fileNameEncode_safeChars = " ()[]#,!";

  static public String fileNameEncode(String s) {
    StringBuilder buf = new StringBuilder();
    int n = l(s);
    for (int i = 0; i < n; i++) {
      char c = s.charAt(i);
      if (contains(fileNameEncode_safeChars, c))
        buf.append(c);
      else
        buf.append(urlencode(str(c)));
    }
    return str(buf);
  }

  static public boolean fileExists(String path) {
    return path != null && new File(path).exists();
  }

  static public boolean fileExists(File f) {
    return f != null && f.exists();
  }

  static public String fromUTF8(byte[] bytes) {
    return fromUtf8(bytes);
  }

  static public Lock downloadLock_lock = fairLock();

  static public Lock downloadLock() {
    return downloadLock_lock;
  }

  static public Object[] muricaCredentialsPlus(Object... params) {
    return concatArrays(muricaCredentials(), params);
  }

  static public String md5OrNull(String s) {
    return s == null ? null : md5(s);
  }

  static public String urlencode(String x) {
    try {
      return URLEncoder.encode(unnull(x), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

  static public Map jsonDecodeMap(String s) {
    Object o = jsonDecode(s);
    if (o instanceof List && empty((List) o))
      return new HashMap();
    if (o instanceof Map)
      return (Map) o;
    else
      throw fail("Not a JSON map: " + s);
  }

  static public File remoteMechListMirrorMetaFile(String listName) {
    return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".meta");
  }

  static public <A, B> Map<A, B> getMultipleKeys(Map<A, B> map, A... keys) {
    Map<A, B> map2 = similarEmptyMap(map);
    if (map != null)
      for (A key : keys) map2.put(key, map.get(key));
    return map2;
  }

  static public File remoteMechListMirrorNameFile(String listName) {
    return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".name");
  }

  static public int countLines(String s) {
    return l(toLines(s));
  }

  static public File localMechListFile(String listName) {
    return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text");
  }

  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 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 List<String> splitAtDoubleArrow_tok;

  static public List<String> splitAtDoubleArrow_tok() {
    if (splitAtDoubleArrow_tok == null)
      splitAtDoubleArrow_tok = ll("=", "", ">");
    return splitAtDoubleArrow_tok;
  }

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

  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 String getTranspiledStandardFunctionsIfCached(TreeSet<String> functionSet) {
    try {
      File f = transpiledStandardFunctions_file(functionSet);
      return loadTextFile(f);
    } catch (Throwable __e) {
      return null;
    }
  }

  static public boolean standardFunctionsCacheUpToDate(TreeSet<String> functionSet) {
    File f = transpiledStandardFunctions_file(functionSet);
    long date = recommendedTranspilationDateForStandardFunctions(functionSet);
    return date != 0 && f.lastModified() >= date;
  }

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

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

  static public Class veryQuickJava_finish(String src, List<String> libs) {
    libs = cloneList(libs);
    src = findTranslators2(src, libs);
    String dehlibs = join(" ", libs);
    File bytecode = null;
    bytecode = javaCompile_overInternalBot(src, dehlibs);
    return hotwireCore(concatLists(ll(bytecode), loadLibraries(libs)));
  }

  static public boolean loadFunctions_debug = false;

  static public Object loadFunctions_veryQuickJava;

  static public Class loadFunctions(String... functions) {
    return loadFunctions(asList(functions));
  }

  static public Class loadFunctions(Collection<String> functions) {
    print("Compiling " + joinWithPlus(functions));
    TreeSet<String> functionSet = new TreeSet<String>(functions);
    StringBuilder buf = new StringBuilder();
    for (String s : functionSet) buf.append("please include function " + assertIdentifier(s) + ".\n");
    long time = sysNow();
    Class c;
    if (loadFunctions_veryQuickJava != null)
      c = (Class) callF(loadFunctions_veryQuickJava, str(buf));
    else {
      veryQuickJava_transpiled.set("");
      c = veryQuickJava(str(buf));
      saveTranspiledStandardFunctions(functionSet, getAndClearThreadLocal(veryQuickJava_transpiled));
    }
    if (loadFunctions_debug)
      done2_always(time, "loadFunctions: " + join(" ", functions));
    return c;
  }

  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 void ownResource(AutoCloseable c) {
    _registerAutoCloseable(c);
  }

  static public <A> AutoCloseable vmBus_onMessage(final String msg, final VF1<A> onMessage) {
    Map<String, Set> map = vm_busListenersByMessage_live();
    synchronized (map) {
      Set listeners = map.get(msg);
      if (listeners == null)
        map.put(msg, listeners = syncIdentityHashSet());
      return tempAdd(listeners, new VF2<String, Object>() {

        public void get(String _msg, Object arg) {
          try {
            callF(onMessage, arg);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "callF(onMessage, arg)";
        }
      });
    }
  }

  static public <A, B> AutoCloseable vmBus_onMessage(String msg, final VF2<A, B> onMessage) {
    return vmBus_onMessage(msg, new VF1<Object[]>() {

      public void get(Object[] o) {
        try {
          callF(onMessage, first(o), second(o));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(onMessage, first(o), second(o));";
      }
    });
  }

  static public AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) {
    return vmBus_onMessage(msg, runnableToVF1(onMessage));
  }

  static public void loadFunctions_clearCache() {
    callOptMC("loadFunctions_cached_clearCache");
  }

  static public int methodApplicabilityScore(Method m, Object[] args) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length)
      return Integer.MAX_VALUE;
    int score = 0;
    for (int i = 0; i < types.length; i++) {
      Object a = args[i];
      Class c = types[i];
      if (a == null)
        ++score;
      else if (c == a.getClass()) {
      } else if (isInstanceX(c, a))
        ++score;
      else
        return Integer.MAX_VALUE;
    }
    return score;
  }

  static public RuntimeException todo() {
    throw new RuntimeException("TODO");
  }

  static public RuntimeException todo(Object msg) {
    throw new RuntimeException("TODO: " + msg);
  }

  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 void setHeaders(URLConnection con) throws IOException {
    String computerID = getComputerID_quick();
    if (computerID != null)
      try {
        con.setRequestProperty("X-ComputerID", computerID);
        con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
      } catch (Throwable e) {
      }
  }

  static public int lUtf8(String s) {
    return l(utf8(s));
  }

  static public URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
    con.setConnectTimeout(toInt(timeout));
    con.setReadTimeout(toInt(timeout));
    if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
      print("Warning: Timeouts not set by JDK.");
    return con;
  }

  static public File javaxSecretDir_dir;

  static public File javaxSecretDir() {
    return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
  }

  static public File javaxSecretDir(String sub) {
    return newFile(javaxSecretDir(), sub);
  }

  static public File prepareProgramFile(String name) {
    return mkdirsForFile(getProgramFile(name));
  }

  static public File prepareProgramFile(String progID, String name) {
    return mkdirsForFile(getProgramFile(progID, name));
  }

  public static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

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

  static public boolean md5OfFile_verbose = false;

  static public String md5OfFile(String path) {
    return md5OfFile(newFile(path));
  }

  static public String md5OfFile(File f) {
    try {
      if (!f.exists())
        return "-";
      if (md5OfFile_verbose)
        print("Getting MD5 of " + f);
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      FileInputStream in = new FileInputStream(f);
      try {
        byte[] buf = new byte[65536];
        int l;
        while (true) {
          l = in.read(buf);
          if (l <= 0)
            break;
          md5.update(buf, 0, l);
        }
        return bytesToHex(md5.digest());
      } finally {
        _close(in);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 String fromUtf8(byte[] bytes) {
    try {
      return bytes == null ? null : new String(bytes, "UTF-8");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean jsonDecode_useOrderedMaps = true;

  static public Object jsonDecode(final String text) {
    final List<String> tok = jsonTok(text);
    if (l(tok) == 1)
      return null;
    class Y {

      public int i = 1;

      public Object parse() {
        String t = tok.get(i);
        if (t.startsWith("\"")) {
          String s = unquote(tok.get(i));
          i += 2;
          return s;
        }
        if (t.equals("{"))
          return parseMap();
        if (t.equals("["))
          return this.parseList();
        if (t.equals("null")) {
          i += 2;
          return null;
        }
        if (t.equals("false")) {
          i += 2;
          return false;
        }
        if (t.equals("true")) {
          i += 2;
          return true;
        }
        boolean minus = false;
        if (t.equals("-")) {
          minus = true;
          i += 2;
          t = get(tok, i);
        }
        if (isInteger(t)) {
          i += 2;
          if (eq(get(tok, i), ".")) {
            String x = t + "." + get(tok, i + 2);
            i += 4;
            double d = parseDouble(x);
            if (minus)
              d = -d;
            return d;
          } else {
            long l = parseLong(t);
            if (minus)
              l = -l;
            return l != (int) l ? new Long(l) : new Integer((int) l);
          }
        }
        throw new RuntimeException("Unknown token " + (i + 1) + ": " + t + ": " + text);
      }

      public Object parseList() {
        consume("[");
        List list = new ArrayList();
        while (!tok.get(i).equals("]")) {
          list.add(parse());
          if (tok.get(i).equals(","))
            i += 2;
        }
        consume("]");
        return list;
      }

      public Object parseMap() {
        consume("{");
        Map map = jsonDecode_useOrderedMaps ? new LinkedHashMap() : new TreeMap();
        while (!tok.get(i).equals("}")) {
          String key = unquote(tok.get(i));
          i += 2;
          consume(":");
          Object value = parse();
          map.put(key, value);
          if (tok.get(i).equals(","))
            i += 2;
        }
        consume("}");
        return map;
      }

      public void consume(String s) {
        if (!tok.get(i).equals(s)) {
          String prevToken = i - 2 >= 0 ? tok.get(i - 2) : "";
          String nextTokens = join(tok.subList(i, Math.min(i + 4, tok.size())));
          throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");
        }
        i += 2;
      }
    }
    return new Y().parse();
  }

  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 File localMechListsDir() {
    return javaxDataDir("Mech Lists");
  }

  static public File transpiledStandardFunctions_file(TreeSet<String> functionSet) {
    String name = uniqueFileNameUsingMD5_80_v2(join("+", functionSet));
    File dir = javaxCachesDir("Transpiled Standard Functions");
    saveTextFileUnlessExists(newFile(dir, name + ".functions"), lines(functionSet));
    return newFile(dir, name + ".java");
  }

  static public long recommendedTranspilationDateForStandardFunctions(Collection<String> sfNames) {
    long date = 0;
    for (String name : sfNames) {
      long d = recommendedTranspilationDateForStandardFunction(name);
      if (d == 0)
        return 0;
      date = max(date, d);
    }
    return date;
  }

  static public String findTranslators2(String src, List<String> libsOut) {
    return join(findTranslators2(javaTok(src), libsOut));
  }

  static public List<String> findTranslators2(List<String> tok, List<String> libsOut) {
    int i;
    while ((i = jfind(tok, "!<int>")) >= 0) {
      setAdd(libsOut, tok.get(i + 2));
      clearTokens(tok, i, i + 3);
    }
    return tok;
  }

  static public File javaCompile_overInternalBot(String src) {
    return javaCompile_overInternalBot(src, "");
  }

  static synchronized public File javaCompile_overInternalBot(String src, String dehlibs) {
    return CompilerBot.compile(src, dehlibs);
  }

  static public Class hotwireCore(List<File> files) {
    try {
      JavaXClassLoader classLoader = hotwire_makeClassLoader(files);
      Class<?> theClass = classLoader.loadClass("main");
      setOpt(theClass, "__javax", getJavaX());
      if (getOpt(theClass, "programID") == null)
        setOpt(theClass, "programID", "#3999999");
      if (!_inCore())
        hotwire_copyOver(theClass);
      return theClass;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public List<File> loadLibraries(List<String> snippetIDs) {
    return map("loadLibrary", snippetIDs);
  }

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

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

  static public long sysNow() {
    ping();
    return System.nanoTime() / 1000000;
  }

  static public Class veryQuickJava(CharSequence mainJava) {
    return veryQuickJava3(str(mainJava));
  }

  static public void saveTranspiledStandardFunctions(TreeSet<String> functionSet, String transpiledSrc) {
    try {
      saveTextFile(transpiledStandardFunctions_file(functionSet), transpiledSrc);
    } catch (Throwable __e) {
      _handleException(__e);
    }
  }

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

  static public long done2_always(long startTime, String desc) {
    long time = sysNow() - startTime;
    saveTiming_noPrint(time);
    print(desc + " [" + time + " ms]");
    return time;
  }

  static public long done2_always(String desc, long startTime) {
    return done2_always(startTime, desc);
  }

  static public long done2_always(long startTime) {
    return done2_always(startTime, "");
  }

  static public Set<AutoCloseable> _registerAutoCloseable_set = synchroHashSet();

  static public void _registerAutoCloseable(AutoCloseable c) {
    addIfNotNull(_registerAutoCloseable_set, c);
  }

  static public void cleanMeUp__registerAutoCloseable() {
    closeAutoCloseables(getAndClearList(_registerAutoCloseable_set));
  }

  static public <A> Set<A> syncIdentityHashSet() {
    return (Set) synchronizedSet(identityHashSet());
  }

  static public <A> AutoCloseable tempAdd(final Collection<A> l, final A a) {
    if (l == null || l.contains(a))
      return null;
    l.add(a);
    return new AutoCloseable() {

      public String toString() {
        return "l.remove(a);";
      }

      public void close() throws Exception {
        l.remove(a);
      }
    };
  }

  static public <A> A third(List<A> l) {
    return _get(l, 2);
  }

  static public <A> A third(Iterable<A> l) {
    if (l == null)
      return null;
    Iterator<A> it = iterator(l);
    for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
      if (!it.hasNext())
        return null;
      it.next();
    }
    return it.hasNext() ? it.next() : null;
  }

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

  static public <A> VF1<A> runnableToVF1(final Runnable r) {
    return r == null ? null : new VF1<A>() {

      public void get(A a) {
        try {
          r.run();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "r.run()";
      }
    };
  }

  static public Object callOptMC(String method, Object... args) {
    return callOpt(mc(), method, args);
  }

  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 String getComputerID_quick() {
    return computerID();
  }

  static public byte[] utf8(String s) {
    return toUtf8(s);
  }

  static public File loadLibrary(String snippetID) {
    return loadBinarySnippet(snippetID);
  }

  static public List<String> jsonTok(String s) {
    List<String> tok = new ArrayList();
    int l = l(s);
    int i = 0;
    while (i < l) {
      int j = i;
      char c;
      String cc;
      while (j < l) {
        c = s.charAt(j);
        cc = s.substring(j, Math.min(j + 2, l));
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (cc.equals("/*")) {
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
          j = Math.min(j + 2, l);
        } else if (cc.equals("//")) {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      tok.add(s.substring(i, j));
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      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.isLetter(c))
        do ++j; while (j < l && Character.isLetter(s.charAt(j)));
      else if (Character.isDigit(c))
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      else
        ++j;
      tok.add(s.substring(i, j));
      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 double parseDouble(String s) {
    return Double.parseDouble(s);
  }

  static public File javaxCachesDir_dir;

  static public File javaxCachesDir() {
    return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
  }

  static public File javaxCachesDir(String sub) {
    return newFile(javaxCachesDir(), sub);
  }

  static public void saveTextFileUnlessExists(File f, String contents) {
    if (f != null && !f.exists())
      saveTextFile(f, contents);
  }

  static public long recommendedTranspilationDateForStandardFunction(String sfName) {
    return toLong(mechMap("Recommended SF Transpilation Date").get(sfName));
  }

  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> boolean setAdd(Collection<A> c, A a) {
    if (c == null || c.contains(a))
      return false;
    c.add(a);
    return true;
  }

  static public void clearTokens(List<String> tok) {
    clearAllTokens(tok);
  }

  static public void clearTokens(List<String> tok, int i, int j) {
    clearAllTokens(tok, i, j);
  }

  static public JavaXClassLoader hotwire_makeClassLoader(List<File> files) {
    Collection<String> toShare = hotwire_classesToShare();
    return nempty(toShare) ? new JavaXClassLoaderWithParent2(null, files, myClassLoader(), cloneList(toShare)) : new JavaXClassLoader(null, files);
  }

  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 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 boolean veryQuickJava_silent = true;

  static public boolean veryQuickJava_useCompilerBot = true;

  static public ThreadLocal<String> veryQuickJava_transpiled = new ThreadLocal();

  static public Object veryQuickJava3_cacheFunction;

  static public Class veryQuickJava3(String mainJava) {
    return veryQuickJava3(mainJava, emptyList());
  }

  static public Class veryQuickJava3(String mainJava, List<String> libs) {
    Class c = (Class) (callF(veryQuickJava3_cacheFunction, mainJava, libs));
    if (c != null)
      return c;
    transpileRaw_silent = veryQuickJava_silent;
    String src = transpileRaw(mainJava);
    if (empty(src)) {
      printWithIndent("JAVAX> ", mainJava);
      throw fail("Transpiler returned empty result");
    }
    if (veryQuickJava_transpiled.get() != null)
      veryQuickJava_transpiled.set(src);
    return veryQuickJava_finish(src, libs);
  }

  static public ThreadLocal<Long> saveTiming_last = new ThreadLocal();

  static public void saveTiming(long ms) {
    print(ms + " ms");
    saveTiming_noPrint(ms);
  }

  static public void saveTiming_noPrint(long ms) {
    saveTiming_last.set(ms);
  }

  static public <A> Set<A> synchroHashSet() {
    return Collections.synchronizedSet(new HashSet<A>());
  }

  static public <A> void addIfNotNull(Collection<A> l, A a) {
    if (a != null && l != null)
      l.add(a);
  }

  static public <A> void addIfNotNull(MultiSet<A> ms, A a) {
    if (a != null && ms != null)
      ms.add(a);
  }

  static public void closeAutoCloseables(Collection<AutoCloseable> l) {
    if (l != null)
      for (AutoCloseable c : l) {
        try {
          c.close();
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
  }

  static public <A> List<A> getAndClearList(Collection<A> l) {
    if (l == null)
      return emptyList();
    synchronized (collectionMutex(l)) {
      List<A> out = cloneList(l);
      l.clear();
      return out;
    }
  }

  static public <A> Set<A> synchronizedSet() {
    return synchroHashSet();
  }

  static public <A> Set<A> synchronizedSet(Set<A> set) {
    return Collections.synchronizedSet(set);
  }

  static public <A> Set<A> identityHashSet() {
    return Collections.newSetFromMap(new IdentityHashMap());
  }

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

  static public Object _get(Object o, String field) {
    return get(o, field);
  }

  static public Object _get(String field, Object o) {
    return get(o, field);
  }

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

  static public File loadBinarySnippet(String snippetID) {
    try {
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.loadLibrary(snippetID);
      long id = parseSnippetID(snippetID);
      if (isImageServerSnippet(id))
        return loadImageAsFile(snippetID);
      File f = DiskSnippetCache_getLibrary(id);
      if (fileSize(f) == 0)
        f = loadDataSnippetToFile(snippetID);
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public long toLong(Object o) {
    if (o instanceof Number)
      return ((Number) o).longValue();
    if (o instanceof String)
      return parseLong((String) o);
    return 0;
  }

  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[] 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 <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 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 Set<String> hotwire_classesToShare = synchroSet();

  static public Set<String> hotwire_classesToShare() {
    return hotwire_classesToShare;
  }

  static public ClassLoader myClassLoader() {
    return _getClass(mc()).getClassLoader();
  }

  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 boolean isIdentifier(String s) {
    return isJavaIdentifier(s);
  }

  static public boolean transpileRaw_silent = true;

  static public boolean transpileRaw_useDiskCache = false;

  static public Class transpileRaw_trans;

  static public boolean transpileRaw_verySilent = false;

  static public boolean transpileRaw_dontCopyFromCreator = false;

  static public Lock transpileRaw_lock = lock();

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

  static public String transpileRaw(String mainJava) {
    return transpileRaw(mainJava, false, transpileRaw_useDiskCache);
  }

  static public String transpileRaw(String mainJava, boolean fragment) {
    return transpileRaw(mainJava, fragment, transpileRaw_useDiskCache);
  }

  static public String transpileRaw(String mainJava, boolean fragment, boolean useDiskCache) {
    mainJava = dropTranslators(mainJava);
    if (!transpileRaw_dontCopyFromCreator)
      transpileRaw_copyFromCreator();
    Lock __0 = transpileRaw_lock;
    lock(__0);
    try {
      File cacheFile = null;
      if (useDiskCache) {
        cacheFile = new File(javaxCodeDir(), "Transpilations/" + uniqueFileNameUsingMD5_80_v2(mainJava) + ".java");
        {
          String __4 = loadTextFile(cacheFile);
          if (!empty(__4))
            return __4;
        }
      }
      AutoCloseable __2 = transpileRaw_verySilent ? null : tempLoadingAnim("Transpiling...");
      try {
        transpileRaw_translator();
        setOpt(transpileRaw_trans, "localStuffOnly", fragment);
        setOpt(transpileRaw_trans, "asInclude", isTrue(transpileRaw_asInclude.get()));
        set(transpileRaw_trans, "mainJava", mainJava);
        set(transpileRaw_trans, "print_byThread", print_byThread);
        if (!transpileRaw_verySilent) {
          print("Running translator " + getOpt(transpileRaw_trans, "programID"));
          if (!transpileRaw_silent) {
            print("Translator ID: " + systemHashCode(transpileRaw_trans) + ", print_byThread=" + getTL((ThreadLocal) getOpt(transpileRaw_trans, "print_byThread")));
            call(transpileRaw_trans, "print", "test");
          }
        }
        callMain(transpileRaw_trans);
        String main = (String) (get(transpileRaw_trans, "mainJava"));
        if (useDiskCache) {
          saveTextFile(new File(cacheFile.getPath() + "x"), mainJava);
          saveTextFile(cacheFile, main);
        }
        return main;
      } finally {
        _close(__2);
      }
    } finally {
      unlock(__0);
    }
  }

  static public Class transpileRaw_translator() {
    if (transpileRaw_trans == null) {
      transpileRaw_trans = hotwireSharingLibraries_silently(defaultJavaXTranslatorID());
      makeDependent(transpileRaw_trans);
    }
    setOpt(transpileRaw_trans, "print_silent", transpileRaw_silent);
    return transpileRaw_trans;
  }

  static public void transpileRaw_copyFromCreator() {
    Lock __1 = transpileRaw_lock;
    lock(__1);
    try {
      if (transpileRaw_trans != null)
        return;
      Object c = creator();
      if (c == null)
        return;
      Class trans = (Class) (getOpt(c, "transpileRaw_trans"));
      Lock lock = (Lock) (getOpt(c, "transpileRaw_lock"));
      if (trans != null && lock != null) {
        print("Using creator's transpiler: " + getProgramID(c) + " => " + programID());
        transpileRaw_lock = lock;
        transpileRaw_trans = trans;
      }
    } finally {
      unlock(__1);
    }
  }

  static public void cleanMeUp_transpileRaw() {
    transpileRaw_trans = null;
  }

  static public <A> A printWithIndent(A o) {
    return printIndent(o);
  }

  static public <A> A printWithIndent(String indent, A o) {
    return printIndent(indent, o);
  }

  static public void printWithIndent(int indent, Object o) {
    printIndent(indent, o);
  }

  static public IResourceLoader vm_getResourceLoader() {
    return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
  }

  static public boolean isImageServerSnippet(long id) {
    return id >= 1100000 && id < 1200000;
  }

  static public File loadImageAsFile(String snippetIDOrURL) {
    try {
      if (isURL(snippetIDOrURL))
        throw fail("not implemented");
      if (!isSnippetID(snippetIDOrURL))
        throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
      String snippetID = "" + parseSnippetID(snippetIDOrURL);
      File file = imageSnippetCacheFile(snippetID);
      if (fileSize(file) > 0)
        return file;
      String imageURL = snippetImageURL_noHttps(snippetID);
      System.err.println("Loading image: " + imageURL);
      byte[] data = loadBinaryPage(imageURL);
      saveBinaryFile(file, data);
      return file;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File DiskSnippetCache_file(long snippetID) {
    return new File(getGlobalCache(), "data_" + snippetID + ".jar");
  }

  public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
    File file = DiskSnippetCache_file(snippetID);
    return file.exists() ? file : null;
  }

  public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
    saveBinaryFile(DiskSnippetCache_file(snippetID), data);
  }

  static public byte[] loadDataSnippetImpl(String snippetID) throws IOException {
    byte[] data;
    try {
      URL url = new URL(dataSnippetLink(snippetID));
      print("Loading library: " + hideCredentials(url));
      try {
        data = loadBinaryPage(url.openConnection());
      } catch (RuntimeException e) {
        data = null;
      }
      if (data == null || data.length == 0) {
        url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID));
        print("Loading library: " + hideCredentials(url));
        data = loadBinaryPage(url.openConnection());
      }
      print("Bytes loaded: " + data.length);
    } catch (FileNotFoundException e) {
      throw new IOException("Binary snippet #" + snippetID + " not found or not public");
    }
    return data;
  }

  static public long fileSize(String path) {
    return getFileSize(path);
  }

  static public long fileSize(File f) {
    return getFileSize(f);
  }

  static public File loadDataSnippetToFile(String snippetID) {
    try {
      snippetID = fsI(snippetID);
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.loadLibrary(snippetID);
      File f = DiskSnippetCache_file(parseSnippetID(snippetID));
      List<URL> urlsTried = new ArrayList();
      List<Throwable> errors = new ArrayList();
      try {
        URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
        print("Loading library: " + hideCredentials(url));
        try {
          loadBinaryPageToFile(openConnection(url), f);
          if (fileSize(f) == 0)
            throw fail();
        } catch (Throwable e) {
          errors.add(e);
          url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID)));
          print("Trying other server: " + hideCredentials(url));
          loadBinaryPageToFile(openConnection(url), f);
          print("Got bytes: " + fileSize(f));
        }
        if (fileSize(f) == 0)
          throw fail();
        System.err.println("Bytes loaded: " + fileSize(f));
      } catch (Throwable e) {
        errors.add(e);
        throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
      }
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  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 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 <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 <A> Set<A> synchroSet() {
    return synchroHashSet();
  }

  static public <A> Set<A> synchroSet(Set<A> set) {
    return Collections.synchronizedSet(set);
  }

  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 String dropTranslators(String src) {
    return findTranslators2(src, null);
  }

  static public List<String> dropTranslators(List<String> tok) {
    return findTranslators2(tok, null);
  }

  static public File javaxCodeDir_dir;

  static public File javaxCodeDir() {
    return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code");
  }

  static public File javaxCodeDir(String sub) {
    return newFile(javaxCodeDir(), sub);
  }

  static public <A> AutoCloseable tempLoadingAnim(String msg) {
    return tempDisposeWindow(loadingAnim(msg));
  }

  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 int systemHashCode(Object o) {
    return identityHashCode(o);
  }

  static public Object getTL(Object o, String name) {
    return getThreadLocal(o, name);
  }

  static public <A> A getTL(ThreadLocal<A> tl) {
    return getThreadLocal(tl);
  }

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

  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 Class<?> hotwireSharingLibraries_silently(String progID) {
    AutoCloseable __0 = temp_loadPage_silent();
    try {
      return hotwireSharingLibraries(progID);
    } finally {
      _close(__0);
    }
  }

  static public String defaultJavaXTranslatorID_value = "#759";

  static public String defaultJavaXTranslatorID() {
    return defaultJavaXTranslatorID_value;
  }

  static public Object makeDependent_postProcess;

  static public void makeDependent(Object c) {
    if (c == null)
      return;
    assertTrue("Not a class", c instanceof Class);
    dependentClasses();
    hotwire_classes.add(new WeakReference(c));
    Object local_log = getOpt(mc(), "local_log");
    if (local_log != null)
      setOpt(c, "local_log", local_log);
    Object print_byThread = getOpt(mc(), "print_byThread");
    if (print_byThread != null)
      setOpt(c, "print_byThread", print_byThread);
    callF(makeDependent_postProcess, c);
  }

  static public WeakReference<Object> creator_class;

  static public Object creator() {
    return creator_class == null ? null : creator_class.get();
  }

  static public boolean loadBufferedImage_useImageCache = true;

  static public BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) {
    try {
      ping();
      if (snippetIDOrURLOrFile == null)
        return null;
      if (isURL(snippetIDOrURLOrFile))
        return imageIO_readURL(snippetIDOrURLOrFile);
      if (isAbsolutePath(snippetIDOrURLOrFile))
        return loadBufferedImage(new File(snippetIDOrURLOrFile));
      if (!isSnippetID(snippetIDOrURLOrFile))
        throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
      String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return loadBufferedImage(rl.loadLibrary(snippetID));
      File dir = imageSnippetsCacheDir();
      if (loadBufferedImage_useImageCache) {
        dir.mkdirs();
        File file = new File(dir, snippetID + ".png");
        if (file.exists() && file.length() != 0)
          try {
            return ImageIO.read(file);
          } catch (Throwable e) {
            e.printStackTrace();
          }
      }
      String imageURL = snippetImageURL_http(snippetID);
      print("Loading image: " + imageURL);
      BufferedImage image = imageIO_readURL(imageURL);
      if (loadBufferedImage_useImageCache) {
        File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
        ImageIO.write(image, "png", tempFile);
        tempFile.renameTo(new File(dir, snippetID + ".png"));
      }
      return image;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedImage loadBufferedImage(File file) {
    try {
      return file.isFile() ? ImageIO.read(file) : null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A proxy(Class<A> intrface, final Object target) {
    if (target == null)
      return null;
    if (isInstance(intrface, target))
      return (A) target;
    return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new InvocationHandler() {

      public Object invoke(Object proxy, Method method, Object[] args) {
        return call(target, method.getName(), unnull(args));
      }
    });
  }

  static public <A> A proxy(Object target, Class<A> intrface) {
    return proxy(intrface, target);
  }

  static public boolean isURL(String s) {
    return startsWithOneOf(s, "http://", "https://", "file:");
  }

  static public File imageSnippetCacheFile(String snippetID) {
    File dir = imageSnippetsCacheDir();
    if (!loadBufferedImage_useImageCache)
      return null;
    return new File(dir, parseSnippetID(snippetID) + ".png");
  }

  static public String snippetImageURL_noHttps(String snippetID) {
    return snippetImageURL_noHttps(snippetID, "png");
  }

  static public String snippetImageURL_noHttps(String snippetID, String contentType) {
    return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/");
  }

  static public ThreadLocal<Map<String, List<String>>> loadBinaryPage_responseHeaders = new ThreadLocal();

  static public ThreadLocal<Map<String, String>> loadBinaryPage_extraHeaders = new ThreadLocal();

  static public byte[] loadBinaryPage(String url) {
    try {
      print("Loading " + url);
      return loadBinaryPage(loadPage_openConnection(new URL(url)));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] loadBinaryPage(URLConnection con) {
    try {
      Map<String, String> extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders);
      setHeaders(con);
      for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
      return loadBinaryPage_noHeaders(con);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] loadBinaryPage_noHeaders(URLConnection con) {
    try {
      ByteArrayOutputStream buf = new ByteArrayOutputStream();
      InputStream inputStream = con.getInputStream();
      loadBinaryPage_responseHeaders.set(con.getHeaderFields());
      long len = 0;
      try {
        len = con.getContentLength();
      } catch (Throwable e) {
        printStackTrace(e);
      }
      int n = 0;
      while (true) {
        int ch = inputStream.read();
        if (ch < 0)
          break;
        buf.write(ch);
        if (++n % 100000 == 0)
          println("  " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
      }
      inputStream.close();
      return buf.toByteArray();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static byte[] saveBinaryFile(String fileName, byte[] contents) {
    try {
      File file = new File(fileName);
      File parentFile = file.getParentFile();
      if (parentFile != null)
        parentFile.mkdirs();
      String tempFileName = fileName + "_temp";
      FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
      fileOutputStream.write(contents);
      fileOutputStream.close();
      if (file.exists() && !file.delete())
        throw new IOException("Can't delete " + fileName);
      if (!new File(tempFileName).renameTo(file))
        throw new IOException("Can't rename " + tempFileName + " to " + fileName);
      vmBus_send("wroteFile", file);
      return contents;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] saveBinaryFile(File fileName, byte[] contents) {
    return saveBinaryFile(fileName.getPath(), contents);
  }

  static public File getGlobalCache() {
    File file = new File(javaxCachesDir(), "Binary Snippets");
    file.mkdirs();
    return file;
  }

  static public String dataSnippetLink(String snippetID) {
    long id = parseSnippetID(snippetID);
    if (id >= 1100000 && id < 1200000)
      return imageServerURL() + id;
    if (id >= 1400000 && id < 1500000)
      return "http://butter.botcompany.de:8080/files/" + id + "?_pass=" + muricaPassword();
    if (id >= 1200000 && id < 1300000) {
      String pw = muricaPassword();
      if (empty(pw))
        throw fail("Please set 'murica password by running #1008829");
      return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw;
    } else
      return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=application/binary";
  }

  static public String tb_mainServer_default = "http://code.botcompany.de:8081";

  static public Object tb_mainServer_override;

  static public String tb_mainServer() {
    if (tb_mainServer_override != null)
      return (String) callF(tb_mainServer_override);
    return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
  }

  static public File tb_mainServer_file() {
    return getProgramFile("#1001638", "mainserver.txt");
  }

  static public boolean tb_mainServer_isDefault() {
    return eq(tb_mainServer(), tb_mainServer_default);
  }

  static public String fsI(String id) {
    return formatSnippetID(id);
  }

  static public String fsI(long id) {
    return formatSnippetID(id);
  }

  static public <B, A extends B> A addAndReturn(Collection<B> c, A a) {
    if (c != null)
      c.add(a);
    return a;
  }

  static public void loadBinaryPageToFile(String url, File file) {
    try {
      print("Loading " + url);
      loadBinaryPageToFile(openConnection(new URL(url)), file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void loadBinaryPageToFile(URLConnection con, File file) {
    try {
      setHeaders(con);
      loadBinaryPageToFile_noHeaders(con, file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void loadBinaryPageToFile_noHeaders(URLConnection con, File file) {
    try {
      File ftemp = new File(f2s(file) + "_temp");
      FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
      try {
        InputStream inputStream = con.getInputStream();
        long len = 0;
        try {
          len = con.getContentLength();
        } catch (Throwable e) {
          printStackTrace(e);
        }
        String pat = "  {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
        copyStreamWithPrints(inputStream, buf, pat);
        inputStream.close();
        buf.close();
        file.delete();
        renameFile_assertTrue(ftemp, file);
      } finally {
        if (buf != null)
          buf.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public URLConnection openConnection(String url) {
    try {
      return openConnection(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public URLConnection openConnection(URL url) {
    try {
      ping();
      callOpt(javax(), "recordOpenURLConnection", str(url));
      return url.openConnection();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public long psI(String snippetID) {
    return parseSnippetID(snippetID);
  }

  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 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> AutoCloseable tempDisposeWindow(final Window w) {
    return new AutoCloseable() {

      public void close() {
        disposeWindow(w);
      }
    };
  }

  static public JWindow loadingAnim() {
    return showLoadingAnimation();
  }

  static public JWindow loadingAnim(String text) {
    return showLoadingAnimation(text);
  }

  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 int identityHashCode(Object o) {
    return System.identityHashCode(o);
  }

  static public AutoCloseable temp_loadPage_silent() {
    return tempSetThreadLocal(loadPage_silent, true);
  }

  static public Class<?> hotwireSharingLibraries(String progID) {
    try {
      Pair<File, String> p = CompilerBot.compileSnippet2(progID);
      File jar = p.a;
      assertTrue(f2s(jar), jar.isFile());
      List<File> files = ll(jar);
      String dehlibs = unnull(loadTextFileFromZip(jar, "libraries"));
      List<File> myLibraries = myLibraryFiles();
      Matcher matcher = Pattern.compile("\\d+").matcher(dehlibs);
      while (matcher.find()) {
        String libID = matcher.group();
        File lib = loadLibrary(libID);
        if (myLibraries.contains(lib)) {
        } else {
          files.add(lib);
        }
      }
      JavaXClassLoaderWithParent classLoader = new JavaXClassLoaderWithParent(progID, files, myClassLoader());
      return hotwire_finish(classLoader, progID, p.b);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public List<Class> dependentClasses() {
    return cleanUpAndGetWeakReferencesList(hotwire_classes);
  }

  static public List<WeakReference<Class>> hotwire_classes = synchroList();

  static public Class<?> hotwireDependent(String src) {
    Class c = hotwire(src);
    makeDependent(c);
    return c;
  }

  static public BufferedImage imageIO_readURL(String url) {
    try {
      if (startsWith(url, "https:"))
        disableCertificateValidation();
      return ImageIO.read(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isAbsolutePath(String s) {
    return s != null && new File(s).isAbsolute();
  }

  static public boolean isAbsolutePath(File f) {
    return f != null && f.isAbsolute();
  }

  static public File imageSnippetsCacheDir() {
    return javaxCachesDir("Image-Snippets");
  }

  static public String snippetImageURL_http(String snippetID) {
    return snippetImageURL_http(snippetID, "png");
  }

  static public String snippetImageURL_http(String snippetID, String contentType) {
    return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
  }

  static public boolean isInstance(Class type, Object arg) {
    return type.isInstance(arg);
  }

  static public String snippetImageURL(long snippetID) {
    return snippetImageURL(fsI(snippetID));
  }

  static public String snippetImageURL(String snippetID) {
    return snippetImageURL(snippetID, "png");
  }

  static public String snippetImageURL(String snippetID, String contentType) {
    if (isURL(snippetID))
      return snippetID;
    long id = parseSnippetID(snippetID);
    String url;
    if (id == 1000010 || id == 1000012)
      url = "http://tinybrain.de:8080/tb/show-blobimage.php?id=" + id;
    else if (isImageServerSnippet(id))
      url = imageServerLink(id);
    else
      url = "https://www.botcompany.de:8443/img/" + id;
    return url;
  }

  static public int loadPage_defaultTimeout = 60000;

  static public ThreadLocal<String> loadPage_charset = new ThreadLocal();

  static public boolean loadPage_allowGzip = true, loadPage_debug;

  static public boolean loadPage_anonymous = false;

  static public int loadPage_verboseness = 100000;

  static public int loadPage_retries = 1;

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

  static volatile public int loadPage_forcedTimeout;

  static public ThreadLocal<Integer> loadPage_forcedTimeout_byThread = new ThreadLocal();

  static public ThreadLocal<Map<String, List<String>>> loadPage_responseHeaders = new ThreadLocal();

  static public ThreadLocal<Map<String, String>> loadPage_extraHeaders = new ThreadLocal();

  public static String loadPageSilently(String url) {
    try {
      return loadPageSilently(new URL(loadPage_preprocess(url)));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String loadPageSilently(URL url) {
    try {
      if (url.getProtocol().equals("https"))
        disableCertificateValidation();
      if (!networkAllowanceTest(str(url)))
        throw fail("Not allowed: " + url);
      IOException e = null;
      for (int tries = 0; tries < loadPage_retries; tries++) try {
        URLConnection con = loadPage_openConnection(url);
        return loadPage(con, url);
      } catch (IOException _e) {
        e = _e;
        if (loadPageThroughProxy_enabled) {
          print("Trying proxy because of: " + e);
          try {
            return loadPageThroughProxy(str(url));
          } catch (Throwable e2) {
            print("  " + exceptionToStringShort(e2));
          }
        } else if (loadPage_debug)
          print(exceptionToStringShort(e));
        if (tries < loadPage_retries - 1)
          sleepSeconds(1);
      }
      throw e;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadPage_preprocess(String url) {
    if (url.startsWith("tb/"))
      url = tb_mainServer() + "/" + url;
    if (url.indexOf("://") < 0)
      url = "http://" + url;
    return url;
  }

  static public String loadPage(String url) {
    try {
      url = loadPage_preprocess(url);
      if (!isTrue(loadPage_silent.get()))
        printWithTime("Loading: " + hideCredentials(url));
      return loadPageSilently(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadPage(URL url) {
    return loadPage(url.toExternalForm());
  }

  static public String loadPage(URLConnection con, URL url) throws IOException {
    return loadPage(con, url, true);
  }

  static public String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
    Map<String, String> extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
    if (addHeaders)
      try {
        if (!loadPage_anonymous)
          setHeaders(con);
        if (loadPage_allowGzip)
          con.setRequestProperty("Accept-Encoding", "gzip");
        con.setRequestProperty("X-No-Cookies", "1");
        for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
      } catch (Throwable e) {
      }
    vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
    loadPage_responseHeaders.set(con.getHeaderFields());
    InputStream in = null;
    try {
      in = urlConnection_getInputStream(con);
      if (loadPage_debug)
        print("Put stream in map: " + currentThread());
      String contentType = con.getContentType();
      if (contentType == null) {
        throw new IOException("Page could not be read: " + hideCredentials(url));
      }
      String charset = loadPage_charset == null ? null : loadPage_charset.get();
      if (charset == null)
        charset = loadPage_guessCharset(contentType);
      if ("gzip".equals(con.getContentEncoding())) {
        if (loadPage_debug)
          print("loadPage: Using gzip.");
        in = newGZIPInputStream(in);
      }
      Reader r;
      try {
        r = new InputStreamReader(in, unquote(charset));
      } catch (UnsupportedEncodingException e) {
        print(toHex(utf8(charset)));
        throw e;
      }
      boolean silent = isTrue(loadPage_silent.get());
      StringBuilder buf = new StringBuilder();
      int n = 0;
      while (true) {
        int ch = r.read();
        if (ch < 0)
          break;
        buf.append((char) ch);
        ++n;
        if (!silent && (n % loadPage_verboseness) == 0)
          print("  " + n + " chars read");
      }
      return buf.toString();
    } finally {
      if (loadPage_debug)
        print("loadPage done");
      vm_generalSubMap("URLConnection per thread").remove(currentThread());
      if (in != null)
        in.close();
    }
  }

  static public String loadPage_guessCharset(String contentType) {
    Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
    String match = m.matches() ? m.group(1) : null;
    if (loadPage_debug)
      print("loadPage: contentType=" + contentType + ", match: " + match);
    return or(match, "UTF-8");
  }

  static public URLConnection loadPage_openConnection(URL url) {
    URLConnection con = openConnection(url);
    int timeout = toInt(loadPage_forcedTimeout_byThread.get());
    if (timeout == 0)
      timeout = loadPage_forcedTimeout;
    if (timeout != 0)
      setURLConnectionTimeouts(con, loadPage_forcedTimeout);
    else
      setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
    return con;
  }

  static public <A> A println(A a) {
    return print(a);
  }

  static public String imageServerURL() {
    return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
  }

  public static File mkdirsFor(File file) {
    return mkdirsForFile(file);
  }

  static public void copyStreamWithPrints(InputStream in, OutputStream out, String pat) {
    try {
      byte[] buf = new byte[65536];
      int total = 0;
      while (true) {
        int n = in.read(buf);
        if (n <= 0)
          return;
        out.write(buf, 0, n);
        if ((total + n) / 100000 > total / 100000)
          print(pat.replace("{*}", str(roundDownTo(total, 100000))));
        total += n;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void renameFile_assertTrue(File a, File b) {
    try {
      if (!a.exists())
        throw fail("Source file not found: " + f2s(a));
      if (b.exists())
        throw fail("Target file exists: " + f2s(b));
      mkdirsForFile(b);
      if (!a.renameTo(b))
        throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public JWindow showLoadingAnimation() {
    return showLoadingAnimation("Hold on user...");
  }

  static public JWindow showLoadingAnimation(String text) {
    try {
      return showAnimationInTopRightCorner("#1003543", text);
    } catch (Throwable __e) {
      return null;
    }
  }

  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 loadTextFileFromZip(File inZip, String fileName) {
    return loadTextFileFromZipFile(inZip, fileName);
  }

  static public List<File> myLibraryFiles() {
    return (List<File>) get(myClassLoader(), "files");
  }

  static public Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource) {
    return hotwire_finish(classLoader, progID, javaSource, "main");
  }

  static public Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource, String mainClass) {
    try {
      Class<?> theClass = classLoader.loadClass(mainClass);
      Class j = getJavaX();
      setOpt(theClass, "myJavaSource_code", javaSource);
      synchronized (j) {
        call(j, "setVars", theClass, progID);
        callOpt(j, "addInstance", progID, theClass);
      }
      hotwire_copyOver(theClass);
      vmBus_send("hotwireFinished", theClass, mc());
      return theClass;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> List<A> cleanUpAndGetWeakReferencesList(List<WeakReference<A>> l) {
    if (l == null)
      return null;
    synchronized (l) {
      List<A> out = new ArrayList();
      for (int i = 0; i < l(l); i++) {
        A a = l.get(i).get();
        if (a == null)
          l.remove(i--);
        else
          out.add(a);
      }
      return out;
    }
  }

  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 volatile public boolean disableCertificateValidation_attempted = false;

  static public void disableCertificateValidation() {
    try {
      if (disableCertificateValidation_attempted)
        return;
      disableCertificateValidation_attempted = true;
      try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

          public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
          }

          public void checkClientTrusted(X509Certificate[] certs, String authType) {
          }

          public void checkServerTrusted(X509Certificate[] certs, String authType) {
          }
        } };
        HostnameVerifier hv = new HostnameVerifier() {

          public boolean verify(String hostname, SSLSession session) {
            return true;
          }
        };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
      } catch (Throwable __e) {
        _handleException(__e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String imageServerLink(String md5OrID) {
    if (possibleMD5(md5OrID))
      return "https://botcompany.de/images/md5/" + md5OrID;
    return imageServerLink(parseSnippetID(md5OrID));
  }

  static public String imageServerLink(long id) {
    return "https://botcompany.de/images/" + id;
  }

  static public boolean networkAllowanceTest(String url) {
    return isAllowed("networkAllowanceTest", url);
  }

  static final public boolean loadPageThroughProxy_enabled = false;

  static public String loadPageThroughProxy(String url) {
    return null;
  }

  static public void sleepSeconds(double s) {
    if (s > 0)
      sleep(round(s * 1000));
  }

  static public <A> A printWithTime(A a) {
    return printWithTime("", a);
  }

  static public <A> A printWithTime(String s, A a) {
    print(hmsWithColons() + ": " + s, a);
    return a;
  }

  static public Map vm_generalSubMap(Object name) {
    synchronized (get(javax(), "generalMap")) {
      Map map = (Map) (vm_generalMap_get(name));
      if (map == null)
        vm_generalMap_put(name, map = synchroMap());
      return map;
    }
  }

  static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
    UnknownHostException lastException = null;
    for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
      try {
        if (con instanceof HttpURLConnection)
          if (((HttpURLConnection) con).getResponseCode() == 500)
            throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
        return con.getInputStream();
      } catch (UnknownHostException e) {
        lastException = e;
        print("Retrying because of: " + e);
        continue;
      }
    }
    throw lastException;
  }

  static public String toHex(byte[] bytes) {
    return bytesToHex(bytes);
  }

  static public String toHex(byte[] bytes, int ofs, int len) {
    return bytesToHex(bytes, ofs, len);
  }

  static public Matcher regexpMatcher(String pat, String s) {
    return compileRegexp(pat).matcher(unnull(s));
  }

  static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
    if (con.getConnectTimeout() == 0) {
      con.setConnectTimeout(toInt(timeout));
      if (con.getConnectTimeout() != timeout)
        print("Warning: URL connect timeout not set by JDK.");
    }
    if (con.getReadTimeout() == 0) {
      con.setReadTimeout(toInt(timeout));
      if (con.getReadTimeout() != timeout)
        print("Warning: URL read timeout not set by JDK.");
    }
    return con;
  }

  static public String or2(String a, String b) {
    return nempty(a) ? a : b;
  }

  static public String or2(String a, String b, String c) {
    return or2(or2(a, b), c);
  }

  static public int roundDownTo(int x, int n) {
    return x / n * n;
  }

  static public long roundDownTo(long x, long n) {
    return x / n * n;
  }

  static public boolean showAnimationInTopRightCorner_alwaysOnTop = true;

  static public boolean showAnimationInTopRightCorner_on = true;

  static public JWindow showAnimationInTopRightCorner(String imageID, String text) {
    if (isHeadless() || !showAnimationInTopRightCorner_on)
      return null;
    return showAnimationInTopRightCorner(imageIcon(imageID), text);
  }

  static public JWindow showAnimationInTopRightCorner(final Image image, final String text) {
    if (image == null || isHeadless() || !showAnimationInTopRightCorner_on)
      return null;
    return showAnimationInTopRightCorner(imageIcon(image), text);
  }

  static public JWindow showAnimationInTopRightCorner(final ImageIcon imageIcon, final String text) {
    if (isHeadless() || !showAnimationInTopRightCorner_on)
      return null;
    return (JWindow) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          JLabel label = new JLabel(imageIcon);
          if (nempty(text)) {
            label.setText(text);
            label.setVerticalTextPosition(SwingConstants.BOTTOM);
            label.setHorizontalTextPosition(SwingConstants.CENTER);
          }
          final JWindow window = showInTopRightCorner(label);
          onClick(label, new Runnable() {

            public void run() {
              try {
                window.dispose();
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "window.dispose()";
            }
          });
          if (showAnimationInTopRightCorner_alwaysOnTop)
            window.setAlwaysOnTop(true);
          return window;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JLabel label = new JLabel(imageIcon);\r\n    if (nempty(text)) {\r\n      label.s...";
      }
    });
  }

  static public JWindow showAnimationInTopRightCorner(final String imageID) {
    return showAnimationInTopRightCorner(imageID, "");
  }

  static public JWindow showAnimationInTopRightCorner(String imageID, double seconds) {
    return showAnimationInTopRightCorner(imageID, "", seconds);
  }

  static public JWindow showAnimationInTopRightCorner(String imageID, String text, double seconds) {
    if (isHeadless())
      return null;
    return disposeWindowAfter(iround(seconds * 1000), showAnimationInTopRightCorner(imageID, text));
  }

  static public JWindow showAnimationInTopRightCorner(BufferedImage img, String text, double seconds) {
    return disposeWindowAfter(iround(seconds * 1000), showAnimationInTopRightCorner(img, text));
  }

  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 possibleMD5(String s) {
    return isMD5(s);
  }

  static volatile public Object isAllowed_function;

  static volatile public boolean isAllowed_all = true;

  static public boolean isAllowed(String askingMethod, Object... args) {
    Object f = vm_generalMap_get("isAllowed_function");
    if (f != null && !isTrue(callF(f, askingMethod, args)))
      return false;
    return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
  }

  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 long round(double d) {
    return Math.round(d);
  }

  static public String hmsWithColons() {
    return hmsWithColons(now());
  }

  static public String hmsWithColons(long time) {
    return new SimpleDateFormat("HH:mm:ss").format(time);
  }

  static public String joinNemptiesWithColonSpace(String... strings) {
    return joinNempties(": ", strings);
  }

  static public String joinNemptiesWithColonSpace(Collection<String> strings) {
    return joinNempties(": ", strings);
  }

  static public String tryToReadErrorStreamFromURLConnection(URLConnection conn) {
    try {
      if (conn instanceof HttpURLConnection)
        return stream2string(((HttpURLConnection) conn).getErrorStream());
      return null;
    } catch (Throwable __e) {
      return null;
    }
  }

  static public Map<String, java.util.regex.Pattern> compileRegexp_cache = syncMRUCache(10);

  static public java.util.regex.Pattern compileRegexp(String pat) {
    java.util.regex.Pattern p = compileRegexp_cache.get(pat);
    if (p == null) {
      compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
    }
    return p;
  }

  static public int imageIcon_cacheSize = 10;

  static public boolean imageIcon_verbose = false;

  static public Map<String, ImageIcon> imageIcon_cache;

  static public Lock imageIcon_lock = lock();

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

  static public ImageIcon imageIcon(String imageID) {
    try {
      if (imageID == null)
        return null;
      Lock __0 = imageIcon_lock;
      lock(__0);
      try {
        if (imageIcon_cache == null)
          imageIcon_cache = new MRUCache(imageIcon_cacheSize);
        imageID = fsI(imageID);
        ImageIcon ii = imageIcon_cache.get(imageID);
        if (ii == null) {
          if (imageIcon_verbose)
            print("Loading image icon: " + imageID);
          File f = loadBinarySnippet(imageID);
          Boolean b = imageIcon_fixGIF.get();
          if (!isFalse(b))
            ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
          else
            ii = new ImageIcon(f.toURI().toURL());
        } else
          imageIcon_cache.remove(imageID);
        imageIcon_cache.put(imageID, ii);
        return ii;
      } finally {
        unlock(__0);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ImageIcon imageIcon(File f) {
    try {
      return new ImageIcon(f.toURI().toURL());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ImageIcon imageIcon(Image img) {
    return new ImageIcon(img);
  }

  static public ImageIcon imageIcon(RGBImage img) {
    return imageIcon(img.getBufferedImage());
  }

  static public JWindow showInTopRightCorner(Component c) {
    return swing(() -> {
      JWindow w = new JWindow();
      w.add(c);
      w.pack();
      moveToTopRightCorner(w);
      w.setVisible(true);
      return w;
    });
  }

  static public boolean isMD5(String s) {
    return l(s) == 32 && isLowerHexString(s);
  }

  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 String joinNempties(String sep, String... strings) {
    return joinStrings(sep, strings);
  }

  static public String joinNempties(String sep, Collection<String> strings) {
    return joinStrings(sep, strings);
  }

  static public String stream2string(InputStream in) {
    return utf8streamToString(in);
  }

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

  static public boolean loadBufferedImageFixingGIFs_debug = false;

  static public ThreadLocal<Var<byte[]>> loadBufferedImageFixingGIFs_output = new ThreadLocal();

  static public Image loadBufferedImageFixingGIFs(File file) {
    try {
      if (!file.exists())
        return null;
      if (!isGIF(file))
        return ImageIO.read(file);
      if (loadBufferedImageFixingGIFs_debug)
        print("loadBufferedImageFixingGIFs" + ": checking gif");
      ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
      reader.setInput(ImageIO.createImageInputStream(file));
      int numImages = reader.getNumImages(true);
      IIOMetadata imageMetaData = reader.getImageMetadata(0);
      String metaFormatName = imageMetaData.getNativeMetadataFormatName();
      boolean foundBug = false;
      for (int i = 0; i < numImages && !foundBug; i++) {
        IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
        int nNodes = root.getLength();
        for (int j = 0; j < nNodes; j++) {
          org.w3c.dom.Node node = root.item(j);
          if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
            String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
            if (Integer.parseInt(delay) == 0) {
              foundBug = true;
            }
            break;
          }
        }
      }
      if (loadBufferedImageFixingGIFs_debug)
        print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
      Image image;
      if (!foundBug) {
        image = Toolkit.getDefaultToolkit().createImage(f2s(file));
      } else {
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        {
          ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
          try {
            ImageWriter writer = ImageIO.getImageWriter(reader);
            writer.setOutput(ios);
            writer.prepareWriteSequence(null);
            for (int i = 0; i < numImages; i++) {
              BufferedImage frameIn = reader.read(i);
              IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
              int nNodes = root.getLength();
              for (int j = 0; j < nNodes; j++) {
                org.w3c.dom.Node node = root.item(j);
                if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
                  String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
                  if (Integer.parseInt(delay) == 0) {
                    ((IIOMetadataNode) node).setAttribute("delayTime", "10");
                  }
                  break;
                }
              }
              IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
              metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
              IIOImage frameOut = new IIOImage(frameIn, null, metadata);
              writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
            }
            writer.endWriteSequence();
          } finally {
            _close(ios);
          }
        }
        byte[] data = baoStream.toByteArray();
        setVar(loadBufferedImageFixingGIFs_output.get(), data);
        if (loadBufferedImageFixingGIFs_debug)
          print("Data size: " + l(data));
        image = Toolkit.getDefaultToolkit().createImage(data);
      }
      return image;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isLowerHexString(String s) {
    for (int i = 0; i < l(s); i++) {
      char c = s.charAt(i);
      if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
      } else
        return false;
    }
    return true;
  }

  static public String joinStrings(String sep, String... strings) {
    return joinStrings(sep, Arrays.asList(strings));
  }

  static public String joinStrings(String sep, Collection<String> strings) {
    StringBuilder buf = new StringBuilder();
    for (String s : unnull(strings)) if (nempty(s)) {
      if (nempty(buf))
        buf.append(sep);
      buf.append(s);
    }
    return str(buf);
  }

  static public String utf8streamToString(InputStream in) {
    return readerToString(utf8bufferedReader(in));
  }

  static public byte[] isGIF_magic = bytesFromHex("47494638");

  static public boolean isGIF(byte[] data) {
    return byteArrayStartsWith(data, isGIF_magic);
  }

  static public boolean isGIF(File f) {
    return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
  }

  static public <A> void setVar(IVar<A> v, A value) {
    if (v != null)
      v.set(value);
  }

  static public String readerToString(Reader r) {
    try {
      try {
        StringBuilder buf = new StringBuilder();
        int n = 0;
        while (true) {
          int ch = r.read();
          if (ch < 0)
            break;
          buf.append((char) ch);
          ++n;
        }
        return buf.toString();
      } finally {
        r.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] bytesFromHex(String s) {
    return hexToBytes(s);
  }

  static public boolean byteArrayStartsWith(byte[] a, byte[] b) {
    if (a == null || b == null)
      return false;
    if (a.length < b.length)
      return false;
    for (int i = 0; i < b.length; i++) if (a[i] != b[i])
      return false;
    return true;
  }

  static public byte[] loadBeginningOfBinaryFile(File file, int maxBytes) {
    return loadBinaryFilePart(file, 0, maxBytes);
  }

  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 byte[] loadBinaryFilePart(File file, long start, long end) {
    try {
      RandomAccessFile raf = new RandomAccessFile(file, "r");
      int n = toInt(min(raf.length(), end - start));
      byte[] buffer = new byte[n];
      try {
        raf.seek(start);
        raf.readFully(buffer, 0, n);
        return buffer;
      } finally {
        raf.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 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 char stringToChar(String s) {
    if (l(s) != 1)
      throw fail("bad stringToChar: " + s);
    return firstChar(s);
  }

  static public char firstChar(String s) {
    return s.charAt(0);
  }

  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 StefansOS_ConnectToServer implements AutoCloseable {

    public DialogIO io;

    volatile public boolean on = false;

    public Set<String> subs = synchroLinkedHashSet();

    public VF1<String> onLine;

    public void start() {
      if (on)
        return;
      on = true;
      _connect();
      doEvery_daemon_highPriority(30000, new Runnable() {

        public void run() {
          try {
            if (io != null)
              io.sendLine("");
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (io != null) io.sendLine(\"\")";
        }
      });
    }

    public void cleanMeUp() {
      on = false;
      closeIO();
    }

    public void close() {
      cleanMeUp();
    }

    public void _connect() {
      startThread("Connect", new Runnable() {

        public void run() {
          try {
            while (licensed() && on) {
              try {
                io = talkTo("botcompany.de", 6000);
                io.getSocket().setSoTimeout(30000 + 10000);
                print("Connected.");
                AutoCloseable __0 = tempAfterwards(new Runnable() {

                  public void run() {
                    try {
                      print("Disconnected.");
                    } catch (Exception __e) {
                      throw rethrow(__e);
                    }
                  }

                  public String toString() {
                    return "print(\"Disconnected.\")";
                  }
                });
                try {
                  io.sendLine(format("computerID=*", computerID()));
                  for (String channel : cloneList(subs)) io.sendLine(format("sub *", channel));
                  print("Sent computer ID: " + computerID());
                  String line;
                  while ((line = io.readLine()) != null) pcallF(onLine, line);
                } finally {
                  _close(__0);
                }
              } catch (Throwable e) {
                printShortException(e);
              }
              closeIO();
              sleepSeconds(5);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "while (licensed() && on) {\r\n        try {\r\n          io = talkTo(\"botcompany....";
        }
      });
    }

    public void closeIO() {
      if (io != null) {
        try {
          io.close();
        } catch (Throwable __e) {
          _handleException(__e);
        }
        io = null;
      }
    }

    public boolean connected() {
      return io != null;
    }

    public void sub(String channel) {
      if (subs.add(channel) && io != null) {
        try {
          io.sendLine(format("sub *", channel));
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
    }

    public void startWithSubs(String... channels) {
      for (String channel : channels) sub(channel);
      start();
    }

    public void sendLine(String line) {
      if (io != null)
        io.sendLine(line);
      else
        print("Can't send, not connected: " + line);
    }
  }

  static abstract public class VF2<A, B> {

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

  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 class MechListDependentCache<A> extends Cache<A> {

    public String listName, lastListContents;

    public MechListDependentCache() {
    }

    public MechListDependentCache(String listName, Object maker) {
      this.maker = maker;
      this.listName = listName;
    }

    public A make() {
      return (A) callF(maker, lastListContents);
    }

    public A get() {
      if (hasLock(lock))
        return value;
      {
        String listContents = mL_raw(listName);
        Lock __0 = lock;
        lock(__0);
        try {
          if (!eqOrSame(listContents, lastListContents))
            clear();
          lastListContents = listContents;
        } finally {
          unlock(__0);
        }
      }
      return super.get();
    }
  }

  static public class DefunctClassLoader {
  }

  static abstract public class TokCondition {

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

  static abstract public class LiveValue<A> {

    abstract public Class<A> getType();

    abstract public A get();

    abstract public void onChange(Runnable l);

    abstract public void removeOnChangeListener(Runnable l);

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }
  }

  static public class SimpleLiveValue<A> extends LiveValue<A> {

    public Class<A> type;

    volatile public A value;

    transient public List onChange = synchroList();

    public SimpleLiveValue(Class<A> type) {
      this.type = type;
    }

    public SimpleLiveValue(Class<A> type, A value) {
      this.value = value;
      this.type = type;
    }

    public Class<A> getType() {
      return type;
    }

    public A get() {
      return value;
    }

    public void onChange(Runnable l) {
      onChange.add(l);
    }

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }

    public void removeOnChangeListener(Runnable l) {
      onChange.remove(l);
    }

    public void fireChanged() {
      pcallFAll(onChange);
    }

    public void set(A a) {
      if (neq(value, a)) {
        value = a;
        fireChanged();
      }
    }
  }

  static public class Lowest<A> {

    public A best;

    public double score;

    transient public Object onChange;

    synchronized public boolean isNewBest(double score) {
      return best == null || score < this.score;
    }

    synchronized public double bestScore() {
      return best == null ? Double.NaN : score;
    }

    public double score() {
      return bestScore();
    }

    synchronized public float floatScore() {
      return best == null ? Float.NaN : (float) score;
    }

    synchronized public float floatScoreOr(float defaultValue) {
      return best == null ? defaultValue : (float) score;
    }

    public boolean put(A a, double score) {
      boolean change = false;
      synchronized (this) {
        if (a != null && isNewBest(score)) {
          best = a;
          this.score = score;
          change = true;
        }
      }
      if (change)
        pcallF(onChange);
      return change;
    }

    synchronized public A get() {
      return best;
    }

    synchronized public boolean has() {
      return best != null;
    }

    synchronized public Pair<A, Double> pair() {
      return best == null ? null : new Pair(best, bestScore());
    }
  }

  static public interface IResourceLoader {

    public String loadSnippet(String snippetID);

    public String getTranspiled(String snippetID);

    public int getSnippetType(String snippetID);

    public String getSnippetTitle(String snippetID);

    public File loadLibrary(String snippetID);

    public File pathToJavaXJar();

    public File getSnippetJar(String snippetID, String transpiledSrc);
  }

  static public class CompilerBot {

    static public boolean verbose = false;

    static public File compileSnippet(String snippetID) {
      return compileSnippet(snippetID, "");
    }

    static public Pair<File, String> compileSnippet2(String snippetID) {
      return compileSnippet2(snippetID, "");
    }

    static public File compileSnippet(String snippetID, String javaTarget) {
      return compileSnippet2(snippetID, javaTarget).a;
    }

    static public Pair<File, String> compileSnippet2(String snippetID, String javaTarget) {
      String transpiledSrc = getServerTranspiled2(snippetID);
      int i = transpiledSrc.indexOf('\n');
      String libs = transpiledSrc.substring(0, Math.max(0, i));
      if (verbose)
        print("Compiling snippet: " + snippetID + ". Libs: " + libs);
      transpiledSrc = transpiledSrc.substring(i + 1);
      return pair(compile(transpiledSrc, libs, javaTarget, snippetID), transpiledSrc);
    }

    static public File compile(String src) {
      return compile(src, "");
    }

    static public File compile(String src, String libs) {
      return compile(src, libs, null);
    }

    static public File compile(String src, String dehlibs, String javaTarget) {
      return compile(src, dehlibs, javaTarget, null);
    }

    static public File compile(String src, String dehlibs, String javaTarget, String progID) {
      if (verbose)
        print("Compiling " + l(src) + " chars");
      String md5 = md5(dehlibs + "\n" + src + "\n" + fsIOpt(progID));
      File jar = getJarFile(md5);
      if (jar == null || jar.length() <= 22) {
        List<String> mainClass = findMainClass(javaTok(src));
        boolean canRename = mainClass != null && useDummyMainClasses() && isSnippetID(progID) && !tok_classHasModifier(mainClass, "public");
        if (verbose)
          print("useRenaming: " + useDummyMainClasses() + ", canRename: " + canRename + ", progID: " + progID);
        javaCompileToJar_optionalRename(src, dehlibs, jar, canRename ? progID : null, progID);
      } else {
        if (verbose)
          print("Getting classes from cache (" + jar.getAbsolutePath() + ", " + jar.length() + " bytes)");
        touchFile(jar);
      }
      return jar;
    }

    static public File getJarFile(String md5) {
      assertTrue(isMD5(md5));
      String sub = "JavaX-Caches/#1002203/" + md5 + ".jar";
      File f = actualUserDir(sub);
      return fileExists(f) ? f : userDir(sub);
    }
  }

  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 class JavaXClassLoader extends URLClassLoader {

    public String progID;

    public List<File> files;

    public Set<String> triedToLoad = synchroSet();

    public Set<Class> loadedClasses = synchroSet();

    public boolean retired = false;

    public Object retiredMarker;

    public JavaXClassLoader(String progID, List<File> files) {
      this(progID, files, getSystemClassLoader());
    }

    public JavaXClassLoader(String progID, List<File> files, ClassLoader parent) {
      super(new URL[0], parent);
      this.progID = progID;
      this.files = files;
      {
        try {
          for (File f : files) addURL(f.toURI().toURL());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }
      fixACCInClassLoader(this);
    }

    public Class<?> findClass(String name) throws ClassNotFoundException {
      boolean triedBefore = !triedToLoad.add(name);
      try {
        Class<?> c = super.findClass(name);
        loadedClasses.add(c);
        if (eq(name, "main"))
          callOpt(javax(), "registerAMainClass", c);
        return c;
      } catch (ClassNotFoundException e) {
        throw new ClassNotFoundException("Class " + name + " not found in " + joinWithComma(map("f2s", files)) + " (progID=" + progID + ")" + (triedBefore ? ", tried to load before" : ""), e);
      }
    }

    public String toString() {
      return "JavaXClassLoader[" + systemHashCodeHex(this) + "] - " + progID;
    }
  }

  static public class JavaXClassLoaderWithParent extends JavaXClassLoader {

    public ClassLoader virtualParent;

    public JavaXClassLoaderWithParent(String progID, List<File> files, ClassLoader virtualParent) {
      super(progID, files);
      this.virtualParent = virtualParent;
    }

    public Class<?> findClass(String name) throws ClassNotFoundException {
      if (virtualParent != null && !eq(name, "main") && !name.startsWith("main$")) {
        try {
          return virtualParent.loadClass(name);
        } catch (ClassNotFoundException e) {
        }
      }
      return super.findClass(name);
    }
  }

  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 class PKI {

    static public String getProvider() {
      return isAndroid() ? "BC" : "SUN";
    }

    public static boolean verifySignature(byte[] publicKey, byte[] signature, String file) throws InvalidKeyException, NoSuchProviderException, NoSuchAlgorithmException, IOException, SignatureException, InvalidKeySpecException {
      Signature sig = initPublicSignature(publicKey);
      FileInputStream datafis = new FileInputStream(file);
      BufferedInputStream bufin = new BufferedInputStream(datafis);
      byte[] buffer = new byte[1024];
      while (bufin.available() != 0) {
        int len = bufin.read(buffer);
        sig.update(buffer, 0, len);
      }
      bufin.close();
      return sig.verify(signature);
    }

    public static boolean verifySignature(byte[] publicKey, byte[] signature, byte[] data) {
      try {
        Signature sig = initPublicSignature(publicKey);
        sig.update(data);
        return sig.verify(signature);
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    static public Signature initPublicSignature(byte[] publicKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidKeyException {
      Signature sig = Signature.getInstance("SHA1withDSA", getProvider());
      PublicKey pub = KeyFactory.getInstance("DSA", getProvider()).generatePublic(new X509EncodedKeySpec(publicKey));
      sig.initVerify(pub);
      return sig;
    }

    public static byte[] sign(String file, byte[] privateKey) {
      try {
        Signature dsa = initSignature(privateKey);
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bufin = new BufferedInputStream(fis);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bufin.read(buffer)) >= 0) dsa.update(buffer, 0, len);
        bufin.close();
        return dsa.sign();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public static byte[] sign(byte[] data, byte[] privateKey) {
      try {
        Signature dsa = initSignature(privateKey);
        dsa.update(data);
        return dsa.sign();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    static public Signature initSignature(byte[] privateKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidKeyException {
      Signature dsa = Signature.getInstance("SHA1withDSA", getProvider());
      EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
      PrivateKey priv = KeyFactory.getInstance("DSA", getProvider()).generatePrivate(keySpec);
      dsa.initSign(priv);
      return dsa;
    }

    public static KeyPair makeKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", getProvider());
      SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
      keyGen.initialize(1024, random);
      return keyGen.generateKeyPair();
    }

    public static boolean makeStandardKeyPairIfNecessary() {
      try {
        File publicKeyPath = getStandardPublicKeyPath();
        File privateKeyPath = getStandardPrivateKeyPath();
        if (!publicKeyPath.exists()) {
          print("PKI: Making standard key pair");
          KeyPair keyPair = makeKeyPair();
          byte[] privateKey = keyPair.getPrivate().getEncoded();
          print("PKI: Private key hex (debug) - " + bytesToHex(privateKey));
          saveTextFile(privateKeyPath, privateKeyToString(privateKey));
          String publicKey = publicKeyToString(keyPair.getPublic());
          saveTextFile(publicKeyPath, publicKey);
          print("PKI: Standard key pair made!");
          print();
          printInfo();
          return true;
        }
        return false;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    static public void printInfo() {
      print("PKI: Machine's public key: " + publicKeyToString(getStandardPublicKey()));
      print("PKI: Machine's private key in: " + getStandardPrivateKeyPath());
      print("PKI: Machine's public key also in: " + getStandardPublicKeyPath());
      print("PKI: User's public key: " + publicKeyToString(userPublicKey()));
      print("PKI: User's private key in: " + userPrivateKeyPath());
      print("PKI: User's public key also in: " + userPublicKeyPath());
    }

    public static File getStandardPrivateKeyPath() {
      return new File(getSecretProgramDir("#1001547"), "Computer-Private-Key");
    }

    public static File userPublicKeyPath() {
      return new File(getProgramDir("#1001547"), "User-Public-Key");
    }

    public static File userPrivateKeyPath() {
      return new File(getSecretProgramDir("#1001547"), "User-Private-Key");
    }

    public static File getStandardPublicKeyPath() {
      return new File(getProgramDir("#1001547"), "Computer-Public-Key");
    }

    public static byte[] getStandardPrivateKey() {
      makeStandardKeyPairIfNecessary();
      return privateKeyFromString(loadTextFile(getStandardPrivateKeyPath()));
    }

    public static byte[] getStandardPublicKey() {
      makeStandardKeyPairIfNecessary();
      return publicKeyFromString(loadTextFile(getStandardPublicKeyPath()));
    }

    public static byte[] userPrivateKey() {
      makeUserKeyPairIfNecessary();
      return privateKeyFromString(loadTextFile(userPrivateKeyPath()));
    }

    public static byte[] userPublicKey() {
      makeUserKeyPairIfNecessary();
      return publicKeyFromString(loadTextFile(userPublicKeyPath()));
    }

    static public String publicKeyToString(PublicKey publicKey) {
      return publicKeyToString(publicKey.getEncoded());
    }

    public static String privateKeyToString(PrivateKey privateKey) {
      return privateKeyToString(privateKey.getEncoded());
    }

    public static byte[] publicKeyFromString(String key) {
      return base64decode(dropPrefixMandatory("publickey:", trim(key)));
    }

    public static byte[] privateKeyFromString(String key) {
      return base64decode(dropPrefixMandatory("privatekey:", trim(key)));
    }

    public static byte[] signatureFromString(String key) {
      return base64decode(key);
    }

    public static byte[] dataFromString(String text) {
      return toUtf8(text);
    }

    public static String signatureToString(byte[] signature) {
      return base64encode(signature);
    }

    public static String publicKeyToString(byte[] key) {
      return "publickey:" + base64encode(key);
    }

    public static String privateKeyToString(byte[] key) {
      return "privatekey:" + base64encode(key);
    }

    static public boolean makeUserKeyPairIfNecessary() {
      try {
        File publicKeyPath = userPublicKeyPath();
        File privateKeyPath = userPrivateKeyPath();
        if (!publicKeyPath.exists()) {
          print("PKI: Making user key pair");
          KeyPair keyPair = makeKeyPair();
          byte[] privateKey = keyPair.getPrivate().getEncoded();
          print("PKI: Private key hex (debug) - " + bytesToHex(privateKey));
          saveTextFile(privateKeyPath, privateKeyToString(privateKey));
          String publicKey = publicKeyToString(keyPair.getPublic());
          saveTextFile(publicKeyPath, publicKey);
          print("PKI: User key pair made!");
          print();
          printInfo();
          return true;
        }
        return false;
      } 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 class ExpiringMap2<A, B> extends AbstractMap<A, B> {

    public Map<A, Pair<Long, B>> byKey = new HashMap();

    public PriorityBlockingQueue<Pair<Long, A>> queue = new PriorityBlockingQueue();

    public long standardExpiryTime;

    public boolean renewOnOverwrite = true, renewOnGet;

    public Object onChange;

    public ExpiringMap2() {
    }

    public ExpiringMap2(long standardExpiryTime) {
      this.standardExpiryTime = standardExpiryTime;
    }

    public ExpiringMap2(long standardExpiryTime, Object onChange) {
      this.onChange = onChange;
      this.standardExpiryTime = standardExpiryTime;
    }

    synchronized public boolean clean() {
      boolean changes = false;
      Pair<Long, A> p;
      while ((p = queue.peek()) != null && sysTime() >= p.a) {
        p = queue.poll();
        Pair<Long, B> v = byKey.get(p.b);
        if (v != null) {
          byKey.remove(p.b);
          changes = true;
          change();
        }
      }
      return changes;
    }

    public void change() {
      callF(onChange);
    }

    synchronized public B put(A a, B b) {
      clean();
      long timeout = sysTime() + standardExpiryTime;
      Pair<Long, B> p = byKey.get(a);
      if (p != null && renewOnOverwrite)
        queue.remove(new Pair(p.a, a));
      byKey.put(a, pair(timeout, b));
      change();
      if (p == null || renewOnOverwrite)
        queue.add(new Pair(timeout, a));
      return pairB(p);
    }

    synchronized public B remove(Object a) {
      clean();
      Pair<Long, B> p = byKey.get(a);
      if (p == null)
        return null;
      queue.remove(new Pair(p.a, a));
      byKey.remove(a);
      change();
      return p.b;
    }

    synchronized public B get(Object a) {
      clean();
      Pair<Long, B> p = byKey.get(a);
      if (renewOnGet && p != null) {
        queue.remove(new Pair(p.a, a));
        long timeout = sysTime() + standardExpiryTime;
        byKey.put((A) a, pair(timeout, p.b));
        queue.add(new Pair(timeout, a));
      }
      return pairB(p);
    }

    synchronized public Set<Map.Entry<A, B>> entrySet() {
      clean();
      return synchronizedSet(mapValues("pairB", byKey).entrySet());
    }

    synchronized public Set<A> keySet() {
      clean();
      return synchronizedSet(byKey.keySet());
    }

    synchronized public int size() {
      clean();
      return byKey.size();
    }

    public void setStandardExpiryTime(long ms) {
      standardExpiryTime = ms;
    }

    synchronized public ExpiringMap2<A, B> setMap(Map innerMap) {
      byKey = innerMap;
      return this;
    }
  }

  static public class JavaXClassLoaderWithParent2 extends JavaXClassLoader {

    public ClassLoader virtualParent;

    public List<String> classesToSkip;

    public JavaXClassLoaderWithParent2(String progID, List<File> files, ClassLoader virtualParent, List<String> classesToSkip) {
      super(progID, files);
      this.virtualParent = virtualParent;
      this.classesToSkip = classesToSkip;
    }

    public Class<?> findClass(String name) throws ClassNotFoundException {
      if (shouldDelegate(name)) {
        Class<?> c = virtualParent.loadClass(name);
        if (c != null)
          return c;
      }
      return super.findClass(name);
    }

    public boolean shouldDelegate(String name) {
      for (String s : classesToSkip) if (eq(name, s) || startsWith(name, s + "$"))
        return true;
      return false;
    }
  }

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

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

  static public interface IVar<A> {

    public void set(A a);

    public A get();

    default public boolean has() {
      return get() != null;
    }

    default public void clear() {
      set(null);
    }
  }

  static public class MechMode implements IFieldsToList {

    public Object readMode;

    public Object writeMode;

    public MechMode() {
    }

    public MechMode(Object readMode, Object writeMode) {
      this.writeMode = writeMode;
      this.readMode = readMode;
    }

    public String toString() {
      return "MechMode(" + readMode + ", " + writeMode + ")";
    }

    public boolean equals(Object o) {
      if (!(o instanceof MechMode))
        return false;
      MechMode x = (MechMode) o;
      return eq(readMode, x.readMode) && eq(writeMode, x.writeMode);
    }

    public int hashCode() {
      int h = -866263200;
      h = boostHashCombine(h, _hashCode(readMode));
      h = boostHashCombine(h, _hashCode(writeMode));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { readMode, writeMode };
    }
  }

  static public interface IFieldsToList {

    public Object[] _fieldsToList();
  }

  static abstract public class DialogIO implements AutoCloseable {

    public String line;

    public boolean eos, loud, noClose;

    public Lock lock = lock();

    abstract public String readLineImpl();

    abstract public boolean isStillConnected();

    abstract public void sendLine(String line);

    abstract public boolean isLocalConnection();

    abstract public Socket getSocket();

    public int getPort() {
      Socket s = getSocket();
      return s == null ? 0 : s.getPort();
    }

    public boolean helloRead = false;

    public int shortenOutputTo = 500;

    public String readLineNoBlock() {
      String l = line;
      line = null;
      return l;
    }

    public boolean waitForLine() {
      try {
        ping();
        if (line != null)
          return true;
        line = readLineImpl();
        if (line == null)
          eos = true;
        return line != null;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public String readLine() {
      waitForLine();
      helloRead = true;
      return readLineNoBlock();
    }

    public String ask(String s, Object... args) {
      if (loud)
        return askLoudly(s, args);
      if (!helloRead)
        readLine();
      if (args.length != 0)
        s = format3(s, args);
      sendLine(s);
      return readLine();
    }

    public String askLoudly(String s, Object... args) {
      if (!helloRead)
        readLine();
      if (args.length != 0)
        s = format3(s, args);
      print("> " + shorten(s, shortenOutputTo));
      sendLine(s);
      String answer = readLine();
      print("< " + shorten(answer, shortenOutputTo));
      return answer;
    }

    public void pushback(String l) {
      if (line != null)
        throw fail();
      line = l;
      helloRead = false;
    }
  }

  static abstract public class DialogHandler {

    abstract public void run(DialogIO io);
  }

  static public class Cache<A> {

    public Object maker;

    public A value;

    public long loaded;

    static public boolean debug = false;

    public long changeCount;

    public Lock lock = lock();

    public Cache() {
    }

    public Cache(Object maker) {
      this.maker = maker;
    }

    public A get() {
      if (hasLock(lock))
        return value;
      Lock __0 = lock;
      lock(__0);
      try {
        if (loaded == 0) {
          value = make();
          changeCount++;
          loaded = sysNow();
        }
        return value;
      } finally {
        unlock(__0);
      }
    }

    public void clear() {
      Lock __1 = lock;
      lock(__1);
      try {
        if (debug && loaded != 0)
          print("Clearing cache");
        value = null;
        changeCount++;
        loaded = 0;
      } finally {
        unlock(__1);
      }
    }

    public void clear(double seconds) {
      Lock __2 = lock;
      lock(__2);
      try {
        if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000)
          clear();
      } finally {
        unlock(__2);
      }
    }

    public void set(A a) {
      Lock __3 = lock;
      lock(__3);
      try {
        value = a;
        ++changeCount;
        loaded = sysNow();
      } finally {
        unlock(__3);
      }
    }

    public A make() {
      return (A) callF(maker);
    }
  }

  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 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 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> Set<A> synchroLinkedHashSet() {
    return Collections.synchronizedSet(new LinkedHashSet<A>());
  }

  static public FixedRateTimer doEvery_daemon_highPriority(long delay, final Object r) {
    return doEvery_daemon_highPriority(delay, delay, r);
  }

  static public FixedRateTimer doEvery_daemon_highPriority(long delay, long firstDelay, final Object r) {
    return doEvery_daemon(delay, firstDelay, new Runnable() {

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

      public String toString() {
        return "highThreadPriority();\r\n    callF(r);";
      }
    });
  }

  static public FixedRateTimer doEvery_daemon_highPriority(double delaySeconds, final Object r) {
    return doEvery_daemon_highPriority(toMS(delaySeconds), r);
  }

  static public DialogIO talkTo(int port) {
    return talkTo("localhost", port);
  }

  static public int talkTo_defaultTimeout = 10000;

  static public int talkTo_timeoutForReads = 0;

  static public ThreadLocal<Map<String, DialogIO>> talkTo_byThread = new ThreadLocal();

  static public DialogIO talkTo(String ip, int port) {
    try {
      String full = ip + ":" + port;
      Map<String, DialogIO> map = talkTo_byThread.get();
      if (map != null && map.containsKey(full))
        return map.get(full);
      if (isLocalhost(ip) && port == vmPort())
        return talkToThisVM();
      return new talkTo_IO(ip, port);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public class talkTo_IO extends DialogIO {

    public String ip;

    public int port;

    public Socket s;

    public Writer w;

    public BufferedReader in;

    public talkTo_IO(String ip, int port) {
      this.port = port;
      this.ip = ip;
      try {
        s = new Socket();
        try {
          if (talkTo_timeoutForReads != 0)
            s.setSoTimeout(talkTo_timeoutForReads);
          s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout);
        } catch (Throwable e) {
          throw fail("Tried talking to " + ip + ":" + port, e);
        }
        w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
        in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public boolean isLocalConnection() {
      return s.getInetAddress().isLoopbackAddress();
    }

    public boolean isStillConnected() {
      return !(eos || s.isClosed());
    }

    public void sendLine(String line) {
      try {
        Lock __0 = lock;
        lock(__0);
        try {
          w.write(line + "\n");
          w.flush();
        } finally {
          unlock(__0);
        }
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public String readLineImpl() {
      try {
        return in.readLine();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void close() {
      try {
        if (!noClose)
          s.close();
      } catch (IOException e) {
      }
    }

    public Socket getSocket() {
      return s;
    }
  }

  static public AutoCloseable tempAfterwards(final Object r) {
    return new AutoCloseable() {

      public void close() {
        callF(r);
      }
    };
  }

  static public String format(String pat, Object... args) {
    return format3(pat, args);
  }

  static public boolean hasLock(Lock lock) {
    return ((ReentrantLock) lock).isHeldByCurrentThread();
  }

  static public String mL_raw(String name) {
    return mechList_raw(name);
  }

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

  static public void clear(Collection c) {
    if (c != null)
      c.clear();
  }

  static public float score(Scored s) {
    return s == null ? 0 : s.score();
  }

  static public boolean getServerTranspiled2_allowLocalFallback = true, getServerTranspiled2_localFallbackVerbose = true;

  static public Map<String, String> getServerTranspiled2_tempCache;

  static public String getServerTranspiled2(String id) {
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return rl.getTranspiled(id);
    id = fsIOpt(id);
    String transpiled = mapGet(getServerTranspiled2_tempCache, id);
    if (transpiled != null)
      return transpiled;
    transpiled = loadCachedTranspilation(id);
    String md5 = null;
    if (machineIsOffline() || isOfflineMode() || isLocalSnippet(id))
      return transpiled;
    if (transpiled != null)
      md5 = md5(transpiled);
    String transpiledSrc;
    try {
      transpiledSrc = getServerTranspiled(formatSnippetID(id), md5);
    } catch (Throwable e) {
      if (!getServerTranspiled2_allowLocalFallback)
        rethrow(e);
      printExceptionShort(e);
      if (getServerTranspiled2_localFallbackVerbose)
        print("Fallback to local code");
      return transpiled;
    }
    if (eq(transpiledSrc, "SAME")) {
      if (!isTrue(loadPage_silent.get()))
        print("SAME");
      return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiled);
    }
    return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiledSrc);
  }

  static public String fsIOpt(String s) {
    return formatSnippetIDOpt(s);
  }

  static public List<String> findMainClass(List<String> tok) {
    for (List<String> c : reversedList(allClasses(tok))) {
      String name = getClassDeclarationName(c);
      if (eq(name, "main") || name.startsWith("x"))
        return c;
    }
    return findBlock("m {", tok);
  }

  static public boolean useDummyMainClasses() {
    return true;
  }

  static public boolean tok_classHasModifier(List<String> classDecl, String modifier) {
    if (classDecl == null)
      return false;
    int i = classDecl.indexOf("class");
    return subList(classDecl, 0, i).contains(modifier);
  }

  static public boolean javaCompileToJar_useRAMDisk = false;

  static public File javaCompileToJar_optionalRename(String src, File destJar, String progIDForRename) {
    return javaCompileToJar_optionalRename(src, "", destJar, progIDForRename);
  }

  static synchronized public File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename) {
    return javaCompileToJar_optionalRename(src, dehlibs, destJar, progIDForRename, null);
  }

  static synchronized public File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename, String progID) {
    String javaTarget = null;
    String dummyClass = "main";
    if (progIDForRename != null) {
      dummyClass = dummyMainClassName(progIDForRename);
      src += "\nclass " + dummyClass + "{}";
    }
    String md5 = md5(src);
    File jar = destJar;
    Class j = getJavaX();
    if (javaTarget != null)
      setOpt(j, "javaTarget", javaTarget);
    File srcDir = tempDir();
    String className = "main";
    String fileName = dummyClass + ".java";
    List<String> tok = javaTok(src);
    String packageName = tok_packageName(tok);
    if (packageName != null)
      fileName = packageName.replace(".", "/") + "/" + tok_firstClassName(tok) + ".java";
    File mainJava = new File(srcDir, fileName);
    saveTextFile(mainJava, src);
    File classesDir = javaCompileToJar_useRAMDisk ? tempDirPossiblyInRAMDisk() : tempDir();
    try {
      List<File> libraries = new ArrayList();
      Matcher m = Pattern.compile("\\d+").matcher(dehlibs);
      while (m.find()) {
        String libID = m.group();
        assertTrue(isSnippetID(libID));
        libraries.add(loadLibraryOrSrcLib(libID));
      }
      libraries.add(pathToJavaxJar());
      String compilerOutput;
      try {
        compilerOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir);
      } catch (Throwable e) {
        compilerOutput = (String) get(getJavaX(), "javaCompilerOutput");
        compilerOutput = indentx("> ", cleanJavaCompilerOutput(compilerOutput));
        if (!swic(e.getMessage(), "Java compiler returned errors."))
          compilerOutput = appendWithNewLine(compilerOutput, str(e));
        throw fail(compilerOutput, e);
      }
      compilerOutput = cleanJavaCompilerOutput("Annotation processing got disabled, since it requires a 1.6 compliant JVM");
      if (nempty(compilerOutput)) {
        print("Compiler said: " + compilerOutput);
      }
      if (!anyFileWithExtensionInDir(classesDir, ".class")) {
        printWithIndent("SRC> ", src);
        throw fail("No classes generated (was compiling " + nChars(src) + ")");
      }
      saveTextFile(new File(classesDir, "main.java"), src);
      if (nempty(dehlibs))
        saveTextFile(new File(classesDir, "libraries"), dehlibs);
      saveTextFile(new File(classesDir, "progID"), progID);
      dir2zip_recurse_verbose = false;
      int n = dir2zip_recurse(classesDir, jar);
      return jar;
    } finally {
      if (isInRAMDisk(classesDir))
        deleteDirectory(classesDir);
    }
  }

  static public void touchFile(File file) {
    try {
      closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw"));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File actualUserDir() {
    return new File(actualUserHome());
  }

  static public File actualUserDir(String path) {
    return new File(actualUserHome(), path);
  }

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

  static public void fixACCInClassLoader(Object o) {
    try {
      AccessControlContext acc = vm_globalACC();
      if (acc != null)
        replaceACCInClassLoader(o, acc);
    } catch (Throwable __e) {
      _handleException(__e);
    }
  }

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

  static public Class findClass(String name) {
    synchronized (findClass_cache) {
      if (findClass_cache.containsKey(name))
        return findClass_cache.get(name);
      if (!isJavaIdentifier(name))
        return null;
      Class c;
      try {
        c = Class.forName("main$" + name);
      } catch (ClassNotFoundException e) {
        c = null;
      }
      findClass_cache.put(name, c);
      return c;
    }
  }

  static public String systemHashCodeHex(Object o) {
    return intToHex(identityHashCode(o));
  }

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

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

  static public File getSecretProgramDir(String snippetID) {
    if (empty(snippetID))
      return javaxSecretDir();
    return newFile(javaxSecretDir(), formatSnippetID(snippetID));
  }

  static public byte[] base64decode(String s) {
    byte[] alphaToInt = base64decode_base64toint;
    int sLen = s.length();
    int numGroups = sLen / 4;
    if (4 * numGroups != sLen)
      throw new IllegalArgumentException("String length must be a multiple of four.");
    int missingBytesInLastGroup = 0;
    int numFullGroups = numGroups;
    if (sLen != 0) {
      if (s.charAt(sLen - 1) == '=') {
        missingBytesInLastGroup++;
        numFullGroups--;
      }
      if (s.charAt(sLen - 2) == '=')
        missingBytesInLastGroup++;
    }
    byte[] result = new byte[3 * numGroups - missingBytesInLastGroup];
    int inCursor = 0, outCursor = 0;
    for (int i = 0; i < numFullGroups; i++) {
      int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch3 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
      result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
      result[outCursor++] = (byte) ((ch2 << 6) | ch3);
    }
    if (missingBytesInLastGroup != 0) {
      int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
      if (missingBytesInLastGroup == 1) {
        int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
        result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
      }
    }
    return result;
  }

  static public int base64decode_base64toint(char c, byte[] alphaToInt) {
    int result = alphaToInt[c];
    if (result < 0)
      throw new IllegalArgumentException("Illegal character " + c);
    return result;
  }

  static final public byte[] base64decode_base64toint = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };

  static public String dropPrefixMandatory(String prefix, String s) {
    if (s.startsWith(prefix))
      return s.substring(prefix.length());
    else
      throw fail("Prefix " + prefix + " not found in: " + s);
  }

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

  static public long sysTime() {
    return sysNow();
  }

  static public void change() {
    callOpt(getOptMC("mainConcepts"), "allChanged");
  }

  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 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 Map mapValues(Map map, Object func) {
    return mapValues(func, map);
  }

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

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

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

  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 volatile public boolean readLine_noReadLine = false;

  static public String readLine_lastInput;

  static public String readLine_prefix = "[] ";

  static public String readLine() {
    if (readLine_noReadLine)
      return null;
    String s = readLineHidden();
    if (s != null) {
      readLine_lastInput = s;
      print(readLine_prefix + s);
    }
    return s;
  }

  static public FixedRateTimer doEvery_daemon(long delay, final Object r) {
    return doEvery_daemon(delay, delay, r);
  }

  static public FixedRateTimer doEvery_daemon(long delay, long firstDelay, final Object r) {
    FixedRateTimer timer = new FixedRateTimer(true);
    timer.scheduleAtFixedRate(smartTimerTask(r, timer, delay), firstDelay, delay);
    return timer;
  }

  static public FixedRateTimer doEvery_daemon(double delaySeconds, final Object r) {
    return doEvery_daemon(toMS(delaySeconds), r);
  }

  static public void highThreadPriority() {
    currentThread().setPriority(Thread.NORM_PRIORITY + 1);
  }

  static public long toMS(double seconds) {
    return (long) (seconds * 1000);
  }

  static public boolean isLocalhost(String ip) {
    return isLoopbackIP(ip) || eqic(ip, "localhost");
  }

  static public int vmPort() {
    return myVMPort();
  }

  static public DialogIO talkToThisVM() {
    return new talkToThisVM_IO();
  }

  static public class talkToThisVM_IO extends DialogIO {

    public List<String> answers = ll(thisVMGreeting());

    public boolean isLocalConnection() {
      return true;
    }

    public boolean isStillConnected() {
      return true;
    }

    public int getPort() {
      return vmPort();
    }

    public void sendLine(String line) {
      answers.add(or2(sendToThisVM_newThread(line), "?"));
    }

    public String readLineImpl() {
      try {
        return popFirst(answers);
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void close() {
    }

    public Socket getSocket() {
      return null;
    }
  }

  static public String loadCachedTranspilation(String id) {
    try {
      return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id));
    } catch (Throwable __e) {
      return null;
    }
  }

  static public boolean machineIsOffline() {
    return isFalse(callF(vmGeneralMap_get("areWeOnline")));
  }

  static public boolean isOfflineMode() {
    return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode")));
  }

  static public boolean isLocalSnippet(String snippetID) {
    return isLocalSnippetID(snippetID);
  }

  static public boolean isLocalSnippet(long snippetID) {
    return isLocalSnippetID(snippetID);
  }

  static public String getServerTranspiled(String snippetID) {
    return getServerTranspiled(snippetID, null);
  }

  static public boolean getServerTranspiled_printStackTrace = false;

  static public String getServerTranspiled(String snippetID, String expectedMD5) {
    try {
      if (getServerTranspiled_printStackTrace)
        printStackTrace();
      long id = parseSnippetID(snippetID);
      String text = loadPage_utf8(tb_mainServer() + "/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1" + (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "") + standardCredentials());
      if (nempty(text) && neq(text, "SAME"))
        saveTranspiledCode(snippetID, text);
      return text;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void printExceptionShort(Throwable e) {
    print(exceptionToStringShort(e));
  }

  static public <A, B> B mapPut_returnValue(Map<A, B> map, A key, B value) {
    mapPut(map, key, value);
    return value;
  }

  static public HashSet<String> allClasses_keywords = lithashset("class", "interface", "enum", "sclass", "sinterface", "record", "srecord", "asclass");

  static public List<List<String>> allClasses(List<String> tok) {
    List<List<String>> l = new ArrayList();
    int n = tok.size();
    HashSet<String> _allClasses_keywords = allClasses_keywords;
    for (int i = 1; i < n; i += 2) {
      String t = tok.get(i);
      if ("{".equals(t))
        i = findEndOfBlock(tok, i) - 1;
      else if (_allClasses_keywords.contains(t) && (tok_isJavaxMetaCommandLeftOf(tok, i) || !eqGetOneOf(tok, i - 2, ".", "include"))) {
        int j = i;
        while (j < n && !tok.get(j).equals("{")) j += 2;
        j = findEndOfBlock(tok, j) + 1;
        i = leftScanModifiers(tok, i);
        l.add(tok.subList(i - 1, Math.min(n, j)));
        i = j - 2;
      }
    }
    return l;
  }

  static public List<List<String>> allClasses(String text) {
    return allClasses(javaTok(text));
  }

  static public String getClassDeclarationName(List<String> tok) {
    if (tok != null)
      for (int i = 1; i + 2 < tok.size(); i += 2) if (allClasses_keywords.contains(tok.get(i)) && isIdentifier(tok.get(i + 2))) {
        if (eqGet(tok, i + 2, "noeq"))
          i += 2;
        return tok.get(i + 2);
      }
    return null;
  }

  static public List<String> findBlock(String pat, List<String> tok) {
    List<String> tokpat = javaTok(pat);
    int i = findCodeTokens(tok, toStringArray(codeTokensOnly(tokpat)));
    if (i < 0)
      return null;
    int bracketIdx = i + tokpat.size() - 3;
    assertEquals("{", tok.get(bracketIdx));
    int endIdx = findEndOfBlock(tok, bracketIdx);
    return subList(tok, i - 1, endIdx + 1);
  }

  static public String dummyMainClassName(String progID) {
    return "m" + psI(progID);
  }

  static public File tempDir() {
    return makeTempDir();
  }

  static public String tok_packageName(List<String> tok) {
    int i = jfind(tok, "package");
    if (i < 0)
      return "";
    i += 2;
    int j = jfind(tok, i, ";");
    if (j < 0)
      return "";
    return join(codeTokensOnly(subList(tok, i - 1, j)));
  }

  static public String tok_firstClassName(List<String> tok) {
    int i = jfind(tok, "class <id>");
    return i < 0 ? null : tok.get(i + 2);
  }

  static public File tempDirPossiblyInRAMDisk() {
    File f = linux_fileInRamDisk(aGlobalID());
    if (f != null) {
      f.mkdirs();
      return f;
    }
    return makeTempDir();
  }

  static public boolean loadLibraryOrSrcLib_srcLibsEnabled = true;

  static public ThreadLocal<Map<Long, File>> loadLibraryOrSrcLib_tempCache = new ThreadLocal();

  static public File loadLibraryOrSrcLib(String snippetID) {
    try {
      long id = parseSnippetID(snippetID);
      if (loadLibraryOrSrcLib_tempCache.get() != null) {
        File f = loadLibraryOrSrcLib_tempCache.get().get(id);
        if (f != null)
          return f;
      }
      boolean srcLib = loadLibraryOrSrcLib_srcLibsEnabled && isMarkedAsSrcLib(snippetID);
      if (srcLib) {
        File f = pairA(hotwire_compile(snippetID));
        mapPut(loadLibraryOrSrcLib_tempCache.get(), id, f);
      }
      File f = DiskSnippetCache_getLibrary(id);
      if (fileSize(f) != 0)
        return f;
      try {
        return loadDataSnippetToFile(snippetID);
      } catch (Throwable e) {
        if (loadLibraryOrSrcLib_srcLibsEnabled && nempty(loadSnippet(snippetID))) {
          markAsSrcLib(snippetID);
          return pairA(hotwire_compile(snippetID));
        }
        throw rethrow(e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File pathToJavaxJar() {
    try {
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.pathToJavaXJar();
      int x = latestInstalledJavaX();
      File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar");
      if (!xfile.isFile()) {
        print("Saving " + f2s(xfile));
        String url = x30JarServerURL();
        byte[] data = loadBinaryPage(url);
        if (data.length < 1000000)
          throw fail("Could not load " + url);
        saveBinaryFile(xfile.getPath(), data);
      }
      return xfile;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String cleanJavaCompilerOutput(String s) {
    return dropPrefixTrim("Annotation processing got disabled, since it requires a 1.6 compliant JVM", s);
  }

  static public String appendWithNewLine(String a, String b) {
    if (empty(b))
      return a;
    if (empty(a))
      return b;
    return addSuffix(a, "\n") + b;
  }

  static public boolean anyFileWithExtensionInDir(File dir, String ext) {
    return nempty(filesWithExtension(ext, findAllFiles_noDirs(dir)));
  }

  static public String nChars(int n) {
    return n2(n, "char");
  }

  static public String nChars(String s) {
    return nChars(l(s));
  }

  static public boolean dir2zip_recurse_verbose = false;

  static public int dir2zip_recurse(File inDir, File zip) {
    return dir2zip_recurse(inDir, zip, "");
  }

  static public int dir2zip_recurse(File inDir, File zip, String outPrefix) {
    try {
      mkdirsForFile(zip);
      FileOutputStream fout = newFileOutputStream(zip);
      ZipOutputStream outZip = new ZipOutputStream(fout);
      try {
        return dir2zip_recurse(inDir, outZip, outPrefix, 0);
      } finally {
        outZip.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public int dir2zip_recurse(File inDir, ZipOutputStream outZip) {
    return dir2zip_recurse(inDir, outZip, "", 0);
  }

  static public int dir2zip_recurse(File inDir, ZipOutputStream outZip, String outPrefix, int level) {
    try {
      if (++level >= 20)
        throw fail("woot? 20 levels in zip?");
      List<File> files = new ArrayList();
      for (File f : listFiles(inDir)) files.add(f);
      int n = 0;
      sortFilesByName(files);
      for (File f : files) {
        if (f.isDirectory()) {
          print("dir2zip_recurse: Scanning " + f.getAbsolutePath());
          n += dir2zip_recurse(f, outZip, outPrefix + f.getName() + "/", level);
        } else {
          if (dir2zip_recurse_verbose)
            print("Copying " + f.getName());
          outZip.putNextEntry(new ZipEntry(outPrefix + f.getName()));
          InputStream fin = new FileInputStream(f);
          copyStream(fin, outZip);
          fin.close();
          ++n;
        }
      }
      return n;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isInRAMDisk(File f) {
    return startsWith(f2s(f), "/dev/shm");
  }

  static public void deleteDirectory(File dir) {
    deleteDirectory(dir, false, false);
  }

  static public void deleteDirectory(File dir, boolean verbose, boolean testRun) {
    deleteAllFilesInDirectory(dir, verbose, testRun);
    if (verbose)
      print((testRun ? "Would delete " : "Deleting ") + dir.getAbsolutePath());
    if (!testRun)
      dir.delete();
  }

  static public void closeRandomAccessFile(RandomAccessFile f) {
    if (f != null)
      try {
        f.close();
        callJavaX("dropIO", f);
      } catch (Throwable e) {
        printStackTrace(e);
      }
  }

  static public RandomAccessFile newRandomAccessFile(File path, String mode) throws IOException {
    boolean forWrite = mode.indexOf('w') >= 0;
    if (forWrite)
      mkdirsForFile(path);
    RandomAccessFile f = new RandomAccessFile(path, mode);
    callJavaX("registerIO", f, path, forWrite);
    return f;
  }

  static public AccessControlContext vm_globalACC() {
    return (AccessControlContext) vm_generalMap_get("Global ACC");
  }

  static public void replaceACCInClassLoader(Object o, AccessControlContext newACC) {
    ClassLoader cl = getClassLoaderOrSame(o);
    if (cl instanceof URLClassLoader) {
      try {
        setOpt(cl, "acc", newACC);
        try {
          setOpt((Object) getOpt(cl, "ucp"), "acc", newACC);
        } catch (Throwable e) {
          printShortException("replaceACCInClassLoader: ", e);
          if (java10OrHigher())
            if (addDefaultVMOption("--add-opens java.base/jdk.internal.loader=ALL-UNNAMED"))
              print("Please restart the OS");
        }
      } catch (Throwable __e) {
        _handleException(__e);
      }
    }
  }

  static public String intToHex(int i) {
    return bytesToHex(intToBytes(i));
  }

  static public String readLineHidden() {
    try {
      if (get(javax(), "readLine_reader") == null)
        set(javax(), "readLine_reader", new BufferedReader(new InputStreamReader(System.in, "UTF-8")));
      try {
        return ((BufferedReader) get(javax(), "readLine_reader")).readLine();
      } finally {
        consoleClearInput();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
    return new SmartTimerTask(r, timer, delay, _threadInfo());
  }

  static public class SmartTimerTask extends TimerTask implements IFieldsToList {

    public Object r;

    public java.util.Timer timer;

    public long delay;

    public Object threadInfo;

    public SmartTimerTask() {
    }

    public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
      this.threadInfo = threadInfo;
      this.delay = delay;
      this.timer = timer;
      this.r = r;
    }

    public String toString() {
      return "SmartTimerTask(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")";
    }

    public Object[] _fieldsToList() {
      return new Object[] { r, timer, delay, threadInfo };
    }

    public long lastRun;

    public void run() {
      if (!licensed())
        timer.cancel();
      else {
        _threadInheritInfo(threadInfo);
        AutoCloseable __0 = tempActivity(r);
        try {
          lastRun = fixTimestamp(lastRun);
          long now = now();
          if (now >= lastRun + delay * 0.9) {
            lastRun = now;
            if (eq(false, pcallF(r)))
              timer.cancel();
          }
        } finally {
          _close(__0);
        }
      }
    }
  }

  static public boolean isLoopbackIP(String ip) {
    return eq(ip, "127.0.0.1");
  }

  static public int myVMPort() {
    List records = (List) (get(getJavaX(), "record_list"));
    Object android = last(records);
    return or0((Integer) get(android, "port"));
  }

  static public String thisVMGreeting() {
    List record_list = (List) (get(getJavaX(), "record_list"));
    Object android = first(record_list);
    return getString(android, "greeting");
  }

  static public String sendToThisVM_newThread(String s, Object... args) {
    final String _s = format(s, args);
    try {
      return (String) evalInNewThread(new F0<Object>() {

        public Object get() {
          try {
            return callStaticAnswerMethod(getJavaX(), _s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ret callStaticAnswerMethod(getJavaX(), _s);";
        }
      });
    } catch (Throwable e) {
      e = getInnerException(e);
      printStackTrace(e);
      return str(e);
    }
  }

  static public <A> A popFirst(List<A> l) {
    if (empty(l))
      return null;
    A a = first(l);
    l.remove(0);
    return a;
  }

  static public <A> A popFirst(Collection<A> l) {
    if (empty(l))
      return null;
    A a = first(l);
    l.remove(a);
    return a;
  }

  static public <A> List<A> popFirst(int n, List<A> l) {
    List<A> part = cloneSubList(l, 0, n);
    removeSubList(l, 0, n);
    return part;
  }

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

  static public String loadTextFilePossiblyGZipped(String fileName, String defaultContents) {
    File gz = new File(fileName + ".gz");
    return gz.exists() ? loadGZTextFile(gz) : loadTextFile(fileName, defaultContents);
  }

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

  static public String loadTextFilePossiblyGZipped(File fileName, String defaultContents) {
    return loadTextFilePossiblyGZipped(fileName.getPath(), defaultContents);
  }

  static public File getCachedTranspilationFile(String id) {
    return newFile(getCodeProgramDir(id), "Transpilation");
  }

  static public Object vmGeneralMap_get(Object key) {
    return vm_generalMap_get(key);
  }

  static public String loadProgramTextFile(String name) {
    return loadTextFile(getProgramFile(name));
  }

  static public String loadProgramTextFile(String progID, String name) {
    return loadTextFile(getProgramFile(progID, name));
  }

  static public String loadProgramTextFile(String progID, String name, String defaultText) {
    return loadTextFile(getProgramFile(progID, name), defaultText);
  }

  static public boolean isLocalSnippetID(String snippetID) {
    return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
  }

  static public boolean isLocalSnippetID(long snippetID) {
    return snippetID >= 1000 && snippetID <= 9999;
  }

  static public String standardCredentials() {
    String user = standardCredentialsUser();
    String pass = standardCredentialsPass();
    if (nempty(user) && nempty(pass))
      return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
    return "";
  }

  static public void saveTranspiledCode(String progID, String code) {
    File dir = getCodeProgramDir(progID);
    new File(dir, "Transpilation").delete();
    saveGZTextFile(new File(dir, "Transpilation.gz"), code);
  }

  static public <A, B> void mapPut(Map<A, B> map, A key, B value) {
    if (map != null && key != null && value != null)
      map.put(key, value);
  }

  static public int findEndOfBlock(List<String> cnc, int i) {
    int j = i + 2, level = 1, n = cnc.size();
    while (j < n) {
      String t = cnc.get(j);
      if ("{".equals(t))
        ++level;
      else if ("}".equals(t))
        --level;
      if (level == 0)
        return j + 1;
      j += 2;
    }
    return n;
  }

  static public boolean tok_isJavaxMetaCommandLeftOf(List<String> tok, int i) {
    int j = i - 2 * 4 - 1;
    if (j >= 0 && jfind(subList(tok, j, i), "set flag <id> .") == 1)
      return true;
    return false;
  }

  static public <A> boolean eqGetOneOf(List<A> l, int i, A... options) {
    return eqOneOf(get(l, i), options);
  }

  static public int leftScanModifiers(List<String> tok, int i) {
    List<String> mod = getJavaModifiers();
    while (i > 1 && mod.contains(tok.get(i - 2))) i -= 2;
    return i;
  }

  static public boolean eqGet(List l, int i, Object o) {
    return eq(get(l, i), o);
  }

  static public <A, B> boolean eqGet(Map<A, B> map, A key, Object o) {
    return eq(mapGet(map, key), o);
  }

  static public String[] toStringArray(Collection<String> c) {
    String[] a = new String[l(c)];
    Iterator<String> it = c.iterator();
    for (int i = 0; i < l(a); i++) a[i] = it.next();
    return a;
  }

  static public String[] toStringArray(Object o) {
    if (o instanceof String[])
      return (String[]) o;
    else if (o instanceof Collection)
      return toStringArray((Collection<String>) o);
    else
      throw fail("Not a collection or array: " + getClassName(o));
  }

  static public List<String> codeTokensOnly(List<String> tok) {
    int n = tok.size();
    List<String> l = emptyList(n / 2);
    for (int i = 1; i < n; i += 2) l.add(tok.get(i));
    return l;
  }

  static public File makeTempDir() {
    return (File) call(getJavaX(), "TempDirMaker_make");
  }

  static public File linux_fileInRamDisk(String name) {
    if (!isLinux())
      return null;
    File dir = newFile("/dev/shm");
    if (dir.isDirectory())
      return newFile(dir, name);
    return null;
  }

  static public String aGlobalID() {
    return randomID(globalIDLength());
  }

  static public boolean isMarkedAsSrcLib(String snippetID) {
    if (snippetID == null)
      return false;
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return isJavaxCompilableSnippetType(rl.getSnippetType(snippetID));
    return fileExists(javaxCodeDir("srclibs/" + psI(snippetID)));
  }

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

  static public Object hotwire_onCompile;

  static public boolean hotwire_serially = false;

  static public Lock hotwire_overInternalBot_lock = lock();

  static public boolean hotwire_compileOnServer = false;

  static public Class<?> hotwire_overInternalBot(String progID) {
    return hotwire_overInternalBot(progID, "main");
  }

  static public Class<?> hotwire_overInternalBot(String progID, String mainClass) {
    try {
      Pair<File, String> p;
      try {
        p = hotwire_compile(progID);
      } catch (Throwable e) {
        throw rethrow("Error hotwiring " + progID, e);
      }
      File jar = p.a;
      assertTrue(jar.getAbsolutePath(), jar.isFile());
      List<File> files = hotwire_collectJars(jar);
      JavaXClassLoader classLoader = hotwire_makeClassLoader(files);
      classLoader.progID = progID;
      return hotwire_finish(classLoader, progID, p.b, mainClass);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Pair<File, String> hotwire_compile(String progID) {
    Pair<File, String> p = hotwire_compileOnServer && !isLocalSnippetID(progID) ? compileSnippetThroughServer(progID) : CompilerBot.compileSnippet2(progID);
    Lock __0 = hotwire_serially ? hotwire_overInternalBot_lock : null;
    lock(__0);
    try {
      callF(hotwire_onCompile, p);
      return p;
    } finally {
      unlock(__0);
    }
  }

  static public void markAsSrcLib(String snippetID) {
    saveTextFile(javaxCodeDir("srclibs/" + psI(snippetID)), "");
  }

  static public int latestInstalledJavaX() {
    File[] files = new File(userHome(), ".javax").listFiles();
    int v = 0;
    if (files != null)
      for (File f : files) {
        Matcher m = Pattern.compile("x(\\d\\d\\d?)\\.jar").matcher(f.getName());
        if (m.matches())
          v = Math.max(v, Integer.parseInt(m.group(1)));
      }
    return v;
  }

  static public String x30JarServerURL() {
    return "http://botcompany.de:8081/x30.jar";
  }

  static public String dropPrefixTrim(String prefix, String s) {
    return trim(dropPrefix(prefix, s));
  }

  static public String addSuffix(String s, String suffix) {
    return s == null || s.endsWith(suffix) ? s : s + suffix;
  }

  static public List<File> filesWithExtension(String ext, List<File> files) {
    return filesEndingWith(files, addPrefixIfNotEmpty2(".", ext));
  }

  static public List<File> findAllFiles_noDirs(List dirs) {
    return findAllFiles_noDirs(asObjectArray(dirs));
  }

  static public List<File> findAllFiles_noDirs(Object... dirs) {
    List<File> l = new ArrayList();
    for (Object dir : dirs) {
      if (dir instanceof String && ((String) dir).endsWith("/.")) {
        for (File f : listFiles(dropSuffix("/.", (String) dir))) if (f.isFile())
          l.add(f);
      } else
        findAllFiles_noDirs_impl(toFile(dir), l);
    }
    return l;
  }

  static public void findAllFiles_noDirs_impl(File dir, List<File> l) {
    for (File f : listFiles(dir)) {
      if (f.isDirectory())
        findAllFiles_noDirs_impl(f, l);
      else
        l.add(f);
    }
  }

  static public File[] listFiles(File dir) {
    File[] files = dir.listFiles();
    return files == null ? new File[0] : files;
  }

  static public File[] listFiles(String dir) {
    return listFiles(new File(dir));
  }

  static public List<File> sortFilesByName(List<File> l) {
    sort(l, new Comparator<File>() {

      public int compare(File a, File b) {
        return stdcompare(a.getName(), b.getName());
      }
    });
    return l;
  }

  static public int deleteAllFilesInDirectory_minPathLength = 10;

  static public void deleteAllFilesInDirectory(File dir) {
    deleteAllFilesInDirectory(dir, false, false);
  }

  static public void deleteAllFilesInDirectory(File dir, boolean verbose, boolean testRun) {
    dir = getCanonicalFile(dir);
    assertTrue(f2s(dir), l(f2s(dir)) >= deleteAllFilesInDirectory_minPathLength);
    File[] files = dir.listFiles();
    if (files == null)
      return;
    for (File f : files) {
      if (!isSymLink(f) && f.isDirectory())
        deleteDirectory(f, verbose, testRun);
      else {
        if (verbose)
          print((testRun ? "Would delete " : "Deleting ") + f.getAbsolutePath());
        if (!testRun)
          f.delete();
      }
    }
  }

  static public Object callJavaX(String method, Object... args) {
    return callOpt(getJavaX(), method, args);
  }

  static public ClassLoader getClassLoaderOrSame(Object o) {
    return o instanceof ClassLoader ? (ClassLoader) o : getClassLoader(o);
  }

  static public boolean java10OrHigher() {
    return parseFirstInt(javaVersion()) >= 10;
  }

  static public boolean addDefaultVMOption(String option) {
    String s = defaultVMArgs(), old = s;
    if (!s.contains(option))
      s = trim(s + " " + option);
    if (eq(old, s))
      return false;
    {
      setDefaultVMArgs(s);
      return true;
    }
  }

  static public byte[] intToBytes(int i) {
    return new byte[] { (byte) (i >>> 24), (byte) (i >>> 16), (byte) (i >>> 8), (byte) i };
  }

  static public void consoleClearInput() {
    consoleSetInput("");
  }

  static public AutoCloseable tempActivity(Object r) {
    return null;
  }

  static public long fixTimestamp(long timestamp) {
    return timestamp > now() ? 0 : timestamp;
  }

  static public int or0(Integer i) {
    return i == null ? 0 : i;
  }

  static public long or0(Long l) {
    return l == null ? 0L : l;
  }

  static public double or0(Double d) {
    return d == null ? 0.0 : d;
  }

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

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

  static public String getString(Object o, Object key) {
    if (o instanceof Map)
      return getString((Map) o, key);
    if (key instanceof String)
      return (String) getOpt(o, (String) key);
    throw fail("Not a string key: " + getClassName(key));
  }

  static public String getString(String key, Object o) {
    return getString(o, (Object) key);
  }

  static public Object evalInNewThread(final Object f) {
    final Flag flag = new Flag();
    final Var var = new Var();
    final Var<Throwable> exception = new Var();
    {
      startThread(new Runnable() {

        public void run() {
          try {
            try {
              var.set(callF(f));
            } catch (Throwable e) {
              exception.set(e);
            }
            flag.raise();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "try {\r\n      var.set(callF(f));\r\n    } catch (Throwable e) {\r\n      exception...";
        }
      });
    }
    flag.waitUntilUp();
    if (exception.has())
      throw rethrow(exception.get());
    return var.get();
  }

  static public String callStaticAnswerMethod(List bots, String s) {
    for (Object c : bots) try {
      String answer = callStaticAnswerMethod(c, s);
      if (!empty(answer))
        return answer;
    } catch (Throwable e) {
      print("Error calling " + getProgramID(c));
      e.printStackTrace();
    }
    return null;
  }

  static public String callStaticAnswerMethod(Object c, String s) {
    String answer = (String) callOpt(c, "answer", s, litlist(s));
    if (answer == null)
      answer = (String) callOpt(c, "answer", s);
    return emptyToNull(answer);
  }

  static public String callStaticAnswerMethod(String s) {
    return callStaticAnswerMethod(mc(), s);
  }

  static public String callStaticAnswerMethod(String s, List<String> history) {
    return callStaticAnswerMethod(mc(), s, history);
  }

  static public String callStaticAnswerMethod(Object c, String s, List<String> history) {
    String answer = (String) callOpt(c, "answer", s, history);
    if (answer == null)
      answer = (String) callOpt(c, "answer", s);
    return emptyToNull(answer);
  }

  static public String loadGZTextFile(File file) {
    try {
      if (!file.isFile())
        return null;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      InputStream fis = new FileInputStream(file);
      GZIPInputStream gis = newGZIPInputStream(fis);
      try {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = gis.read(buffer)) != -1) {
          baos.write(buffer, 0, len);
        }
      } finally {
        fis.close();
      }
      baos.close();
      return fromUtf8(baos.toByteArray());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public File getCodeProgramDir(String snippetID) {
    return new File(javaxCodeDir(), formatSnippetID(snippetID));
  }

  static public File getCodeProgramDir(long snippetID) {
    return getCodeProgramDir(formatSnippetID(snippetID));
  }

  static public String standardCredentialsUser() {
    return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username"))));
  }

  static public String standardCredentialsPass() {
    return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass"))));
  }

  static public void saveGZTextFile(File file, String contents) {
    try {
      File parentFile = file.getParentFile();
      if (parentFile != null)
        parentFile.mkdirs();
      String tempFileName = file.getPath() + "_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());
        GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, "UTF-8");
        PrintWriter printWriter = new PrintWriter(outputStreamWriter);
        printWriter.print(contents);
        printWriter.close();
        gos.close();
        fileOutputStream.close();
      }
      if (file.exists() && !file.delete())
        throw new IOException("Can't delete " + file.getPath());
      if (contents != null)
        if (!tempFile.renameTo(file))
          throw new IOException("Can't rename " + tempFile + " to " + file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public List<String> getJavaModifiers_list = litlist("static", "abstract", "public", "private", "protected", "final", "native", "volatile", "synchronized", "transient");

  static public List<String> getJavaModifiers() {
    return getJavaModifiers_list;
  }

  static public Cache<Boolean> isLinux_cache = new Cache("isLinux_load");

  static public boolean isLinux() {
    return isLinux_cache.get();
  }

  static public Boolean isLinux_load() {
    return !isWindows() && !isMac() && !isAndroid();
  }

  static public int randomID_defaultLength = 12;

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

  static public String randomID(Random r, int length) {
    return makeRandomID(r, length);
  }

  static public String randomID() {
    return randomID(randomID_defaultLength);
  }

  static public String randomID(Random r) {
    return randomID(r, randomID_defaultLength);
  }

  static public int globalIDLength() {
    return 16;
  }

  static public boolean isJavaxCompilableSnippetType(int type) {
    return isJavaxCompilableSnippetTypeExceptInclude(type) || type == javaxIncludeSnippetType();
  }

  static public List<File> hotwire_collectJars(File jar) {
    List<String> libIDs = hotwire_libraryIDsFromJar_deleteJarOnFail(jar);
    List<File> files = ll(jar);
    for (String libID : libIDs) files.add(loadLibraryOrSrcLib(libID));
    return files;
  }

  static public Pair<File, String> compileSnippetThroughServer(String progID) {
    String transpiledSrc = getServerTranspiled2(progID);
    String md5 = md5(transpiledSrc + "\n" + progID);
    File jar = CompilerBot.getJarFile(md5);
    if (jar == null || jar.length() <= 22) {
      byte[] jarData = null;
      boolean dontLoad = false;
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null) {
        dontLoad = true;
        File jar2 = rl.getSnippetJar(progID, transpiledSrc);
        if (jar2 != null)
          return pair(jar2, transpiledSrc);
      }
      if (!dontLoad) {
        try {
          jarData = loadBinaryPage("http://www.botcompany.de/jar/" + psI(progID) + "?md5=" + md5(transpiledSrc));
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
      if (!isJAR(jarData)) {
        if (jarData != null) {
          print(bytesToHex(takeFirstOfByteArray(8, jarData)));
          print("fallback to CompilerBot: " + fromUtf8(takeFirstOfByteArray(80, jarData)));
        }
        return CompilerBot.compileSnippet2(progID);
      }
      saveBinaryFile(jar, jarData);
    }
    return pair(jar, transpiledSrc);
  }

  static public List<File> filesEndingWith(File dir, String suffix) {
    return listFilesWithSuffix(dir, suffix);
  }

  static public List<File> filesEndingWith(List<File> l, String suffix) {
    List<File> out = new ArrayList();
    for (File f : unnull(l)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix)))
      out.add(f);
    return out;
  }

  static public String addPrefixIfNotEmpty2(String prefix, String s) {
    return empty(s) ? "" : addPrefix(prefix, s);
  }

  static public Object[] asObjectArray(Collection l) {
    return toObjectArray(l);
  }

  static public File toFile(Object o) {
    if (o instanceof File)
      return (File) o;
    if (o instanceof String)
      return new File((String) o);
    throw fail("Not a file: " + o);
  }

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

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

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

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

  static public File getCanonicalFile(File f) {
    try {
      return f == null ? null : f.getCanonicalFile();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isSymLink(File f) {
    return f != null && Files.isSymbolicLink(toPath(f));
  }

  static public ClassLoader getClassLoader(Object o) {
    return o == null ? null : _getClass(o).getClassLoader();
  }

  static public int parseFirstInt(String s) {
    return parseInt(jextract("<int>", s));
  }

  static public String javaVersion() {
    return System.getProperty("java.version");
  }

  static public String defaultVMArgs() {
    return javaxDefaultVMArgs();
  }

  static public void setDefaultVMArgs(String args) {
    String oldArgs = javaxDefaultVMArgs();
    args = trim(args);
    if (neq(unnull(oldArgs), unnull(args))) {
      print();
      print("Changing default VM arguments from");
      print("  " + oldArgs);
      print("to");
      print("  " + args);
      print();
      saveTextFile(javaxDataDir("default-vm-args"), nullIfEmpty(args));
    }
  }

  static public void consoleSetInput(final String text) {
    if (headless())
      return;
    setTextAndSelectAll(consoleInputField(), text);
    focusConsole();
  }

  static public String emptyToNull(String s) {
    return eq(s, "") ? null : s;
  }

  static public <A, B> Map<A, B> emptyToNull(Map<A, B> map) {
    return empty(map) ? null : map;
  }

  static public File oneOfTheFiles(String... paths) {
    if (paths != null)
      for (String path : paths) if (fileExists(path))
        return newFile(path);
    return null;
  }

  static public File oneOfTheFiles(File... files) {
    if (files != null)
      for (File f : files) if (fileExists(f))
        return f;
    return null;
  }

  public static boolean isWindows() {
    return System.getProperty("os.name").contains("Windows");
  }

  static public boolean isMac() {
    return System.getProperty("os.name").toLowerCase().contains("mac");
  }

  static public boolean isJavaxCompilableSnippetTypeExceptInclude(int type) {
    return isJavaxApplicationSnippetType(type) || isJavaxModuleSnippetType(type) || type == snippetType_dynModule();
  }

  static public int javaxIncludeSnippetType() {
    return 42;
  }

  static public List<String> hotwire_libraryIDsFromJar_deleteJarOnFail(File jar) {
    try {
      return hotwire_libraryIDsFromJar(jar);
    } catch (Throwable _e) {
      jar.delete();
      throw rethrow(_e);
    }
  }

  static public byte[] isJAR_magic = bytesFromHex("504B0304");

  static public boolean isJAR(byte[] data) {
    return byteArrayStartsWith(data, isJAR_magic);
  }

  static public boolean isJAR(File f) {
    return isJAR(loadBeginningOfBinaryFile(f, l(isJAR_magic)));
  }

  static public byte[] takeFirstOfByteArray(byte[] b, int n) {
    return subByteArray(b, 0, n);
  }

  static public byte[] takeFirstOfByteArray(int n, byte[] b) {
    return takeFirstOfByteArray(b, n);
  }

  static public List<File> listFilesWithSuffix(File dir, String suffix) {
    List<File> l = new ArrayList();
    for (File f : listFiles(dir)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix)))
      l.add(f);
    return l;
  }

  static public String addPrefix(String prefix, String s) {
    return s.startsWith(prefix) ? s : prefix + s;
  }

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

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

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

  static public Path toPath(File f) {
    return f == null ? null : f.toPath();
  }

  static public String jextract(String pat, String s) {
    return jextract(pat, javaTok(s));
  }

  static public String jextract(String pat, List<String> tok) {
    List<String> tokpat = javaTok(pat);
    jfind_preprocess(tokpat);
    int i = jfind(tok, tokpat);
    if (i < 0)
      return null;
    int j = i + l(tokpat) - 2;
    return joinSubList(tok, i, j);
  }

  static public String javaxDefaultVMArgs() {
    File fileNew, fileOld;
    String text = loadTextFile(fileNew = javaxDataDir("default-vm-args"));
    if (text == null) {
      text = loadTextFile(fileOld = programFile("#1005850", "default-vm-args"));
      if (text != null)
        moveFile(fileOld, fileNew);
    }
    return trim(unnull(text));
  }

  static public String nullIfEmpty(String s) {
    return isEmpty(s) ? null : s;
  }

  static public <A, B> Map<A, B> nullIfEmpty(Map<A, B> map) {
    return isEmpty(map) ? null : map;
  }

  static public <A> List<A> nullIfEmpty(List<A> l) {
    return isEmpty(l) ? null : l;
  }

  static public JTextField setTextAndSelectAll(final JTextField tf, final String text) {
    if (tf != null) {
      swing(new Runnable() {

        public void run() {
          try {
            tf.setText(text);
            tf.selectAll();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "tf.setText(text);\r\n    tf.selectAll();";
        }
      });
    }
    return tf;
  }

  static public JTextField consoleInputField() {
    Object console = get(getJavaX(), "console");
    return (JTextField) getOpt(console, "tfInput");
  }

  static public void focusConsole(String s) {
    setConsoleInput(s);
    focusConsole();
  }

  static public void focusConsole() {
    JComponent tf = consoleInputFieldOrComboBox();
    if (tf != null) {
      tf.requestFocus();
    }
  }

  static public boolean isJavaxApplicationSnippetType(int type) {
    return type == snippetType_javaxSource() || type == snippetType_JavaXDesktop();
  }

  static public boolean isJavaxModuleSnippetType(int type) {
    return type == snippetType_javaxModule() || type == snippetType_javaxDesktopModule();
  }

  static public int snippetType_dynModule() {
    return 57;
  }

  static public List<String> hotwire_libraryIDsFromJar(File jar) {
    String dehlibs = unnull(loadTextFileFromZip(jar, "libraries"));
    return regexpExtractAll("\\d+", dehlibs);
  }

  static public byte[] subByteArray(byte[] b, int start) {
    return subByteArray(b, start, l(b));
  }

  static public byte[] subByteArray(byte[] b, int start, int end) {
    start = max(start, 0);
    end = min(end, l(b));
    if (start == 0 && end == l(b))
      return b;
    if (start >= end)
      return new byte[0];
    byte[] x = new byte[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  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 moveFile(File a, File b) {
    if (!renameFile(a, b))
      throw fail("File move failed: " + a + " to " + b);
  }

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

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

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

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

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

  static public void setConsoleInput(String text) {
    consoleSetInput(text);
  }

  static public JComponent consoleInputFieldOrComboBox() {
    Object console = get(getJavaX(), "console");
    JComboBox cb = (JComboBox) (getOpt(console, "cbInput"));
    if (cb != null)
      return cb;
    return (JTextField) getOpt(console, "tfInput");
  }

  static public int snippetType_javaxSource() {
    return 34;
  }

  static public int snippetType_JavaXDesktop() {
    return 55;
  }

  static public int snippetType_javaxModule() {
    return 54;
  }

  static public int snippetType_javaxDesktopModule() {
    return 58;
  }

  static public List<String> regexpExtractAll(String pat, String s) {
    if (s == null)
      return null;
    Matcher m = regexpMatcher(pat, s);
    List<String> out = new ArrayList();
    while (m.find()) out.add(m.group());
    return out;
  }

  static public boolean renameFile(File a, File b) {
    mkdirsForFile(b);
    return a.renameTo(b);
  }

  static public boolean renameFile(File a, String newName) {
    return renameFile(a, fileInSameDir(a, newName));
  }

  static public File fileInSameDir(File f, String newName) {
    return newFile(parentFile(f), newName);
  }

  static public File parentFile(File f) {
    return dirOfFile(f);
  }

  static public File dirOfFile(File f) {
    return f == null ? null : f.getParentFile();
  }

  static public class Scored<A> extends Var<A> {

    public float score;

    public Scored() {
    }

    public Scored(A a, float score) {
      super(a);
      this.score = score;
    }

    public Scored(A a, double score) {
      super(a);
      this.score = (float) score;
    }

    public float score() {
      return score;
    }

    public String toString() {
      return toIntPercent(score) + "%: " + str(get());
    }
  }

  static public class FixedRateTimer extends java.util.Timer {

    public FixedRateTimer() {
      this(false);
    }

    public FixedRateTimer(boolean daemon) {
      this(defaultTimerName(), daemon);
    }

    public FixedRateTimer(String name) {
      this(name, false);
    }

    public FixedRateTimer(String name, boolean daemon) {
      super(name, daemon);
      _registerTimer(this);
    }

    public List<Entry> entries = synchroList();

    static public class Entry implements IFieldsToList {

      public TimerTask task;

      public long firstTime;

      public long period;

      public Entry() {
      }

      public Entry(TimerTask task, long firstTime, long period) {
        this.period = period;
        this.firstTime = firstTime;
        this.task = task;
      }

      public String toString() {
        return "Entry(" + task + ", " + firstTime + ", " + period + ")";
      }

      public Object[] _fieldsToList() {
        return new Object[] { task, firstTime, period };
      }
    }

    public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
      entries.add(new Entry(task, now() + delay, period));
      super.scheduleAtFixedRate(task, delay, period);
    }

    public void cancel() {
      entries.clear();
      super.cancel();
    }

    public int purge() {
      entries.clear();
      return super.purge();
    }

    public FixedRateTimer changeRate(int newPeriod) {
      Object r = ((SmartTimerTask) first(entries).task).r;
      cancel();
      return doEvery(newPeriod, r);
    }
  }

  static public class Flag implements Runnable {

    public boolean up = false;

    public synchronized boolean raise() {
      if (!up) {
        up = true;
        notifyAll();
        return true;
      } else
        return false;
    }

    public synchronized void waitUntilUp() {
      while (!up) {
        try {
          wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

    public synchronized void waitUntilUp(long timeout) {
      if (!up) {
        try {
          wait(timeout);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

    public synchronized boolean isUp() {
      return up;
    }

    public boolean get() {
      return isUp();
    }

    public String toString() {
      return isUp() ? "up" : "down";
    }

    public void waitForThisOr(Flag otherFlag) {
      try {
        while (!isUp() && !otherFlag.isUp()) Thread.sleep(50);
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void run() {
      raise();
    }
  }

  static public int toIntPercent(double ratio) {
    return roundToInt(ratio * 100);
  }

  static public int toIntPercent(float ratio) {
    return toIntPercent((double) ratio);
  }

  static public String defaultTimerName_name;

  static public String defaultTimerName() {
    if (defaultTimerName_name == null)
      defaultTimerName_name = "A timer by " + programID();
    return defaultTimerName_name;
  }

  static public Set<java.util.Timer> _registerTimer_list = newWeakHashSet();

  static public void _registerTimer(java.util.Timer timer) {
    _registerTimer_list.add(timer);
  }

  static public void cleanMeUp__registerTimer() {
    cancelTimers(getAndClearList(_registerTimer_list));
  }

  static public FixedRateTimer doEvery(long delay, final Object r) {
    return doEvery(delay, delay, r);
  }

  static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
    FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
    timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
    return vmBus_timerStarted(timer);
  }

  static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
    return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
  }

  static public FixedRateTimer doEvery(double delaySeconds, final Object r) {
    return doEvery(toMS(delaySeconds), r);
  }

  static public int roundToInt(double d) {
    return (int) Math.round(d);
  }

  static public void cancelTimers(Collection timers) {
    for (Object timer : timers) cancelTimer(timer);
  }

  static public <A> A vmBus_timerStarted(A timer) {
    vmBus_send("timerStarted", timer, costCenter());
    return timer;
  }

  static public void cancelTimer(javax.swing.Timer timer) {
    if (timer != null)
      timer.stop();
  }

  static public void cancelTimer(java.util.Timer timer) {
    if (timer != null)
      timer.cancel();
  }

  static public void cancelTimer(Object o) {
    if (o instanceof java.util.Timer)
      cancelTimer((java.util.Timer) o);
    else if (o instanceof javax.swing.Timer)
      cancelTimer((javax.swing.Timer) o);
    else if (o instanceof AutoCloseable) {
      try {
        ((AutoCloseable) o).close();
      } catch (Throwable __e) {
        _handleException(__e);
      }
    }
  }

  static public Object costCenter() {
    return mc();
  }
}