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_getEvent;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
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.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.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
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 java.text.NumberFormat;
import java.text.*;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.swing.undo.UndoManager;
import java.text.SimpleDateFormat;
import java.awt.datatransfer.StringSelection;

class main {

  public static class FactsBot extends DynAttractorBot {

    public Set<String> facts = ciSet();

    public AttractorBot makeBot() {
      return nu(AI_FactsBot.class, "facts", setWithNotify(facts, new Runnable() {

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

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

  public static boolean _moduleClass_FactsBot;

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

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

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

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

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

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

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

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

  public static 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...";
      }
    });
  }

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

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

  public static volatile StringBuffer local_log = new StringBuffer();

  public static volatile Appendable print_log = local_log;

  public static volatile int print_log_max = 1024 * 1024;

  public static volatile int local_log_max = 100 * 1024;

  public static boolean print_silent;

  public static Object print_byThread_lock = new Object();

  public static volatile ThreadLocal<Object> print_byThread;

  public static volatile Object print_allThreads;

  public static volatile Object print_preprocess;

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

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

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

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

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

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

  public static int makeBot(String greeting) {
    return makeAndroid3(greeting).port;
  }

  public static Android3 makeBot(Android3 a) {
    makeAndroid3(a);
    return a;
  }

  public static Android3 makeBot(String greeting, Object responder) {
    Android3 a = new Android3(greeting);
    a.responder = makeResponder(responder);
    makeBot(a);
    return a;
  }

  public static Android3 makeBot() {
    return makeAndroid3(defaultBotName());
  }

  public static <A> A nu(Class<A> c, Object... values) {
    A a = nuObject(c);
    setAll(a, values);
    return a;
  }

  public static <A> Set<A> setWithNotify(final Runnable onChange) {
    return setWithNotify(new HashSet(), onChange);
  }

  public static <A> Set<A> setWithNotify(Set<A> set, final Runnable onChange) {
    return new NotifyingSet<A>(set) {

      public void change() {
        onChange.run();
      }
    };
  }

  public static void change() {
    callOpt(getOptMC("mainConcepts"), "allChanged");
  }

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

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

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

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

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

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

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

  public static 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;
    }
  }

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

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

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

  public static 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;
  }

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

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

  public static Object _defaultClassFinder_value;

  public static Object _defaultClassFinder() {
    return _defaultClassFinder_value;
  }

  public static String programID;

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

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

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

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

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

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

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

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

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

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

  public static void print_append(Appendable _buf, String s, int max) {
    try {
      synchronized (_buf) {
        _buf.append(s);
        if (!(_buf instanceof StringBuilder))
          return;
        StringBuilder buf = (StringBuilder) _buf;
        max /= 2;
        if (buf.length() > max)
          try {
            int newLength = max / 2;
            int ofs = buf.length() - newLength;
            String newString = buf.substring(ofs);
            buf.setLength(0);
            buf.append("[...] ").append(newString);
          } catch (Exception e) {
            buf.setLength(0);
          }
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  public static boolean makeAndroid3_disable;

  public static class Android3 {

    public String greeting;

    public boolean publicOverride;

    public int startPort = 5000;

    public Responder responder;

    public boolean console = true;

    public boolean quiet;

    public boolean daemon = false;

    public boolean incomingSilent = false;

    public int incomingPrintLimit = 200;

    public boolean useMultiPort = true;

    public boolean recordHistory;

    public boolean verbose;

    public int answerPrintLimit = 500;

    public boolean newLineAboveAnswer, newLineBelowAnswer;

    public int port;

    public long vport;

    public DialogHandler handler;

    public ServerSocket server;

    public Android3(String greeting) {
      this.greeting = greeting;
    }

    public Android3() {
    }

    public synchronized void dispose() {
      if (server != null) {
        try {
          server.close();
        } catch (IOException e) {
          print("[internal] " + e);
        }
        server = null;
      }
      if (vport != 0) {
        try {
          print("Disposing " + this);
          removeFromMultiPort(vport);
          vport = 0;
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
    }

    public String toString() {
      return "Bot: " + greeting + " [vport " + vport + "]";
    }
  }

  public abstract static class Responder {

    public abstract String answer(String s, List<String> history);
  }

  public static Android3 makeAndroid3(final String greeting) {
    return makeAndroid3(new Android3(greeting));
  }

  public static Android3 makeAndroid3(final String greeting, Responder responder) {
    Android3 android = new Android3(greeting);
    android.responder = responder;
    return makeAndroid3(android);
  }

  public static Android3 makeAndroid3(final Android3 a) {
    if (makeAndroid3_disable)
      return a;
    if (a.responder == null)
      a.responder = new Responder() {

        public String answer(String s, List<String> history) {
          return callStaticAnswerMethod(s, history);
        }
      };
    if (!a.quiet)
      print("[bot] " + a.greeting);
    if (a.console && (readLine_noReadLine || makeAndroid3_consoleInUse()))
      a.console = false;
    record(a);
    if (a.useMultiPort)
      a.vport = addToMultiPort(a.greeting, makeAndroid3_verboseResponder(a));
    if (a.console)
      makeAndroid3_handleConsole(a);
    if (a.useMultiPort)
      return a;
    a.handler = makeAndroid3_makeDialogHandler(a);
    if (a.quiet)
      startDialogServer_quiet.set(true);
    try {
      a.port = a.daemon ? startDialogServerOnPortAboveDaemon(a.startPort, a.handler) : startDialogServerOnPortAbove(a.startPort, a.handler);
    } finally {
      startDialogServer_quiet.set(null);
    }
    a.server = startDialogServer_serverSocket;
    return a;
  }

  public static void makeAndroid3_handleConsole(final Android3 a) {
    if (!a.quiet)
      print("You may also type on this console.");
    startThread(new Runnable() {

      public void run() {
        try {
          List<String> history = new ArrayList();
          while (licensed()) {
            String line;
            try {
              line = readLine();
            } catch (Throwable e) {
              print(getInnerMessage(e));
              break;
            }
            if (line == null)
              break;
            {
              history.add(line);
              history.add(makeAndroid3_getAnswer(line, history, a));
            }
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "List<String> history = new ArrayList();\r\n    while (licensed()) {\r\n      Stri...";
      }
    });
  }

  public static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
    return new DialogHandler() {

      public void run(final DialogIO io) {
        if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
          io.sendLine("Sorry, not allowed");
          return;
        }
        String dialogID = randomID(8);
        io.sendLine(a.greeting + " / Your ID: " + dialogID);
        List<String> history = new ArrayList();
        while (io.isStillConnected()) {
          if (io.waitForLine()) {
            final String line = io.readLineNoBlock();
            String s = dialogID + " at " + now() + ": " + quote(line);
            if (!a.incomingSilent)
              print(shorten(s, a.incomingPrintLimit));
            if (eq(line, "bye")) {
              io.sendLine("bye stranger");
              return;
            }
            Matches m = new Matches();
            if (a.recordHistory)
              history.add(line);
            String answer;
            if (match3("this is a continuation of talk *", s, m) || match3("hello bot! this is a continuation of talk *", s, m)) {
              dialogID = unquote(m.m[0]);
              answer = "ok";
            } else
              try {
                makeAndroid3_io.set(io);
                answer = makeAndroid3_getAnswer(line, history, a);
              } finally {
                makeAndroid3_io.set(null);
              }
            if (a.recordHistory)
              history.add(answer);
            io.sendLine(answer);
          }
        }
      }
    };
  }

  public static String makeAndroid3_getAnswer(String line, List<String> history, Android3 a) {
    String answer, originalAnswer;
    try {
      originalAnswer = a.responder.answer(line, history);
      answer = makeAndroid3_fallback(line, history, originalAnswer);
    } catch (Throwable e) {
      e = getInnerException(e);
      printStackTrace(e);
      originalAnswer = answer = e.toString();
    }
    if (!a.incomingSilent) {
      if (originalAnswer == null)
        originalAnswer = "?";
      if (a.newLineAboveAnswer)
        print();
      print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit))));
      if (a.newLineBelowAnswer)
        print();
    }
    return answer;
  }

  public static String makeAndroid3_fallback(String s, List<String> history, String answer) {
    if (answer == null && match3("what is your pid", s))
      return getPID();
    if (answer == null && match3("what is your program id", s))
      return getProgramID();
    if (match3("get injection id", s))
      return getInjectionID();
    if (answer == null)
      answer = "?";
    if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
      answer = quote(answer);
    return answer;
  }

  public static boolean makeAndroid3_consoleInUse() {
    if (isTrue(vm_generalMap_get("consoleInUse")))
      return true;
    for (Object o : record_list) if (o instanceof Android3 && ((Android3) o).console)
      return true;
    return false;
  }

  public static Responder makeAndroid3_verboseResponder(final Android3 a) {
    return new Responder() {

      public String answer(String s, List<String> history) {
        if (a.verbose)
          print("> " + shorten(s, a.incomingPrintLimit));
        String answer = a.responder.answer(s, history);
        if (a.verbose)
          print("< " + shorten(answer, a.incomingPrintLimit));
        return answer;
      }
    };
  }

  public static ThreadLocal<DialogIO> makeAndroid3_io = new ThreadLocal();

  public static Android3 makeAndroid3() {
    return makeAndroid3(getProgramTitle() + ".");
  }

  public static String makeResponder_callAnswerMethod(Object bot, String s, List<String> history) {
    String answer = (String) callOpt(bot, "answer", s, history);
    if (answer == null)
      answer = (String) callOpt(bot, "answer", s);
    return answer;
  }

  public static Responder makeResponder(final Object bot) {
    if (bot instanceof Responder)
      return (Responder) bot;
    if (bot instanceof String) {
      String f = (String) bot;
      return new Responder() {

        public String answer(String s, List<String> history) {
          String answer = (String) callOptMC((String) bot, s, history);
          if (answer == null)
            answer = (String) callOptMC((String) bot, s);
          return answer;
        }
      };
    }
    return new Responder() {

      public String answer(String s, List<String> history) {
        return makeResponder_callAnswerMethod(bot, s, history);
      }
    };
  }

  public static String defaultBotName() {
    return getProgramTitle() + ".";
  }

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

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

  public static 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!" : ""));
  }

  public static 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;
  }

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

  public static <A> A setAll(A o, Object... values) {
    failIfOddCount(values);
    for (int i = 0; i + 1 < l(values); i += 2) {
      String field = (String) values[i];
      Object value = values[i + 1];
      set(o, field, value);
    }
    return o;
  }

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

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

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

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

  public static _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;
    }
  }

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

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

  public static 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;
  }

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

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

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

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

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

  public static Class __javax;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static volatile boolean ping_pauseAll;

  public static int ping_sleep = 100;

  public static volatile boolean ping_anyActions;

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

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

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

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

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

  public static Comparator<String> caseInsensitiveComparator() {
    return betterCIComparator();
  }

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

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

  public static void removeFromMultiPort(long vport) {
    if (vport == 0)
      return;
    for (Object port : getMultiPorts()) call(port, "removePort", vport);
  }

  public static volatile PersistableThrowable _handleException_lastException;

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

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

  public static 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;
  }

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

  public static String callStaticAnswerMethod(String s) {
    return callStaticAnswerMethod(mc(), s);
  }

  public static String callStaticAnswerMethod(String s, List<String> history) {
    return callStaticAnswerMethod(mc(), s, history);
  }

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

  public static List<Object> record_list = synchroList();

  public static void record(Object o) {
    record_list.add(o);
  }

  public static Object addToMultiPort_responder;

  public static long addToMultiPort(final String botName) {
    return addToMultiPort(botName, new Object() {

      public String answer(String s, List<String> history) {
        String answer = (String) (callOpt(getMainClass(), "answer", s, history));
        if (answer != null)
          return answer;
        answer = (String) callOpt(getMainClass(), "answer", s);
        if (answer != null)
          return answer;
        if (match3("get injection id", s))
          return getInjectionID();
        return null;
      }
    });
  }

  public static long addToMultiPort(final String botName, final Object responder) {
    addToMultiPort_responder = responder;
    startMultiPort();
    List ports = getMultiPorts();
    if (ports == null)
      return 0;
    if (ports.isEmpty())
      throw fail("No multiports!");
    if (ports.size() > 1)
      print("Multiple multi-ports. Using last one.");
    Object port = last(ports);
    Object responder2 = new Object() {

      public String answer(String s, List<String> history) {
        if (match3("get injection id", s))
          return getInjectionID();
        if (match3("your name", s))
          return botName;
        return (String) call(responder, "answer", s, history);
      }
    };
    record(responder2);
    return (Long) call(port, "addResponder", botName, responder2);
  }

  public static AtomicInteger dialogServer_clients = new AtomicInteger();

  public static boolean dialogServer_printConnects;

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

  public static Set<String> dialogServer_knownClients = synchroTreeSet();

  public static int startDialogServerOnPortAbove(int port, DialogHandler handler) {
    while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler)) ++port;
    return port;
  }

  public static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
    while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true)) ++port;
    return port;
  }

  public static void startDialogServer(int port, DialogHandler handler) {
    if (!startDialogServerIfPortAvailable(port, handler))
      throw fail("Can't start dialog server on port " + port);
  }

  public static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
    return startDialogServerIfPortAvailable(port, handler, false);
  }

  public static ServerSocket startDialogServer_serverSocket;

  public static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(port);
    } catch (IOException e) {
      return false;
    }
    final ServerSocket _serverSocket = serverSocket;
    startDialogServer_serverSocket = serverSocket;
    Thread thread = new Thread("Socket accept port " + port) {

      public void run() {
        try {
          while (true) {
            try {
              final Socket s = _serverSocket.accept();
              String client = s.getInetAddress().toString();
              if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) {
                print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet());
                dialogServer_knownClients.add(client);
              }
              String threadName = "Handling client " + s.getInetAddress();
              Thread t2 = new Thread(threadName) {

                public void run() {
                  try {
                    final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
                    final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
                    DialogIO io = new DialogIO() {

                      public boolean isLocalConnection() {
                        return s.getInetAddress().isLoopbackAddress();
                      }

                      public boolean isStillConnected() {
                        return !(eos || s.isClosed());
                      }

                      public void sendLine(String line) {
                        try {
                          w.write(line + "\n");
                          w.flush();
                        } catch (Exception __e) {
                          throw rethrow(__e);
                        }
                      }

                      public String readLineImpl() {
                        try {
                          return in.readLine();
                        } catch (Exception __e) {
                          throw rethrow(__e);
                        }
                      }

                      public void close() {
                        try {
                          s.close();
                        } catch (IOException e) {
                        }
                      }

                      public Socket getSocket() {
                        return s;
                      }
                    };
                    try {
                      handler.run(io);
                    } finally {
                      if (!io.noClose)
                        s.close();
                    }
                  } catch (IOException e) {
                    print("[internal] " + e);
                  } finally {
                  }
                }
              };
              t2.setDaemon(true);
              t2.start();
            } catch (SocketTimeoutException e) {
            }
          }
        } catch (IOException e) {
          print("[internal] " + e);
        }
      }
    };
    if (daemon)
      thread.setDaemon(true);
    thread.start();
    if (!isTrue(getAndClearThreadLocal(startDialogServer_quiet)))
      print("Dialog server on port " + port + " started.");
    return true;
  }

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

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

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

  public static volatile boolean licensed_yes = true;

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

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

  public static volatile boolean readLine_noReadLine;

  public static String readLine_lastInput;

  public static String readLine_prefix = "[] ";

  public static String readLine() {
    if (readLine_noReadLine)
      return null;
    String s = readLineHidden();
    if (s != null) {
      readLine_lastInput = s;
      print(readLine_prefix + s);
    }
    return s;
  }

  public static String getInnerMessage(Throwable e) {
    if (e == null)
      return null;
    return getInnerException(e).getMessage();
  }

  public static boolean publicCommOn() {
    return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
  }

  public static int randomID_defaultLength = 12;

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

  public static String randomID() {
    return randomID(randomID_defaultLength);
  }

  public static long now_virtualTime;

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

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

  public static String quote(String s) {
    if (s == null)
      return "null";
    StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
    quote_impl(s, out);
    return out.toString();
  }

  public static void quote_impl(String s, StringBuilder out) {
    out.append('"');
    int l = s.length();
    for (int i = 0; i < l; i++) {
      char c = s.charAt(i);
      if (c == '\\' || c == '"')
        out.append('\\').append(c);
      else if (c == '\r')
        out.append("\\r");
      else if (c == '\n')
        out.append("\\n");
      else if (c == '\0')
        out.append("\\0");
      else
        out.append(c);
    }
    out.append('"');
  }

  public static int shorten_default = 100;

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

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

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

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

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

  public static boolean match3(String pat, String s, Matches matches) {
    if (pat == null || s == null)
      return false;
    return match3(pat, parse3_cachedInput(s), matches);
  }

  public static boolean match3(String pat, List<String> toks, Matches matches) {
    List<String> tokpat = parse3_cachedPattern(pat);
    return match3(tokpat, toks, matches);
  }

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

  public static String unquote(String s) {
    if (s == null)
      return null;
    if (startsWith(s, '[')) {
      int i = 1;
      while (i < s.length() && s.charAt(i) == '=') ++i;
      if (i < s.length() && s.charAt(i) == '[') {
        String m = s.substring(1, i);
        if (s.endsWith("]" + m + "]"))
          return s.substring(i + 1, s.length() - i - 1);
      }
    }
    if (s.length() > 1) {
      char c = s.charAt(0);
      if (c == '\"' || c == '\'') {
        int l = endsWith(s, c) ? s.length() - 1 : s.length();
        StringBuilder sb = new StringBuilder(l - 1);
        for (int i = 1; i < l; i++) {
          char ch = s.charAt(i);
          if (ch == '\\') {
            char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
            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;
  }

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

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

  public static Throwable printStackTrace(Throwable e) {
    print(getStackTrace(e));
    return e;
  }

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

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

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

  public static String[] dropFirst(int n, String[] a) {
    return drop(n, a);
  }

  public static String[] dropFirst(String[] a) {
    return drop(1, a);
  }

  public static Object[] dropFirst(Object[] a) {
    return drop(1, a);
  }

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

  public static <A> List<A> dropFirst(int n, Iterable<A> i) {
    return dropFirst(n, toList(i));
  }

  public static <A> List<A> dropFirst(Iterable<A> i) {
    return dropFirst(toList(i));
  }

  public static <A> List<A> dropFirst(int n, List<A> l) {
    return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
  }

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

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

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

  public static String dropFirst(String s) {
    return substring(s, 1);
  }

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

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

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

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

  public static String processID_cached;

  public static String getPID() {
    if (processID_cached == null) {
      String name = ManagementFactory.getRuntimeMXBean().getName();
      processID_cached = name.replaceAll("@.*", "");
    }
    return processID_cached;
  }

  public static String getInjectionID() {
    return (String) call(getJavaX(), "getInjectionID", getMainClass());
  }

  public static Object vm_generalMap_get(Object key) {
    return vm_generalMap().get(key);
  }

  public static String getProgramTitle() {
    return getProgramName();
  }

  public static Object callOptMC(String method, Object... args) {
    return callOpt(mc(), method, args);
  }

  public static Map<String, Class> classForName_cache = synchroHashMap();

  public static Class classForName(String name) {
    try {
      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);
    }
  }

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

  public static Object nuObjectWithoutArguments(String className) {
    try {
      return nuObjectWithoutArguments(classForName(className));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  public static Constructor nuObjectWithoutArguments_findConstructor(Class c) {
    for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
      m.setAccessible(true);
      return m;
    }
    throw fail("No default constructor found in " + c.getName());
  }

  public static List<Class> getClasses(Object[] array) {
    List<Class> l = new ArrayList();
    for (Object o : array) l.add(_getClass(o));
    return l;
  }

  public static boolean isInstanceX(Class type, Object arg) {
    if (type == boolean.class)
      return arg instanceof Boolean;
    if (type == int.class)
      return arg instanceof Integer;
    if (type == long.class)
      return arg instanceof Long;
    if (type == float.class)
      return arg instanceof Float;
    if (type == short.class)
      return arg instanceof Short;
    if (type == char.class)
      return arg instanceof Character;
    if (type == byte.class)
      return arg instanceof Byte;
    if (type == double.class)
      return arg instanceof Double;
    return type.isInstance(arg);
  }

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

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

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

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

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

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

  public static void failIfOddCount(Object... list) {
    if (odd(l(list)))
      throw fail("Odd list size: " + list);
  }

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

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

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

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

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

  public static void arraycopy(Object[] a, Object[] b) {
    int n = min(a.length, b.length);
    for (int i = 0; i < n; i++) b[i] = a[i];
  }

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

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

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

  public static <A> String join(String glue, Iterable<A> strings) {
    if (strings == null)
      return "";
    if (strings instanceof Collection) {
      if (((Collection) strings).size() == 1)
        return str(first(((Collection) strings)));
    }
    StringBuilder buf = new StringBuilder();
    Iterator<A> i = strings.iterator();
    if (i.hasNext()) {
      buf.append(i.next());
      while (i.hasNext()) buf.append(glue).append(i.next());
    }
    return buf.toString();
  }

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

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

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

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

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

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

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

  public static List<String> getClassNames(Collection l) {
    List<String> out = new ArrayList();
    if (l != null)
      for (Object o : l) out.add(o == null ? null : getClassName(o));
    return out;
  }

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

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

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

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

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

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

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

  public static boolean empty(Object o) {
    if (o instanceof Collection)
      return empty((Collection) o);
    if (o instanceof String)
      return empty((String) o);
    if (o instanceof Map)
      return empty((Map) o);
    if (o instanceof Object[])
      return empty((Object[]) o);
    if (o instanceof byte[])
      return empty((byte[]) o);
    if (o == null)
      return true;
    throw fail("unknown type for 'empty': " + getType(o));
  }

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

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

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

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

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

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

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

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

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

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

  public static betterCIComparator_C betterCIComparator_instance;

  public static betterCIComparator_C betterCIComparator() {
    if (betterCIComparator_instance == null)
      betterCIComparator_instance = new betterCIComparator_C();
    return betterCIComparator_instance;
  }

  public static 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;
    }
  }

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

  public static <A, B extends A> void addAll(Collection<A> c, Iterable<B> b) {
    if (c != null && b != null)
      for (A a : b) c.add(a);
  }

  public static <A, B extends A> boolean addAll(Collection<A> c, Collection<B> b) {
    return c != null && b != null && c.addAll(b);
  }

  public static <A, B extends A> boolean addAll(Collection<A> c, B... b) {
    return c != null && c.addAll(Arrays.asList(b));
  }

  public static List<Object> getMultiPorts() {
    return (List) callOpt(getJavaX(), "getMultiPorts");
  }

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

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

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

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

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

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

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

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

  public static String emptyToNull(String s) {
    return eq(s, "") ? null : s;
  }

  public static <A, B> Map<A, B> emptyToNull(Map<A, B> map) {
    return empty(map) ? null : map;
  }

  public static void startMultiPort() {
    List mp = getMultiPorts();
    if (mp != null && mp.isEmpty()) {
      nohupJavax("#1001639");
      throw fail("Upgrading JavaX, please restart this program afterwards.");
    }
  }

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

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

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

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

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

  public static <A> Set<A> synchroTreeSet() {
    return Collections.synchronizedSet(new TreeSet<A>());
  }

  public static boolean forbiddenPort(int port) {
    return port == 5037;
  }

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

  public static String defaultThreadName_name;

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

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

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

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

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

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

  public static Map<Thread, Boolean> _registerThread_threads;

  public static Object _onRegisterThread;

  public static 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;
  }

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

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

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

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

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

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

  public static String _userHome;

  public static String userHome() {
    if (_userHome == null)
      return actualUserHome();
    return _userHome;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static Map<String, List<String>> parse3_cachedInput_cache = synchronizedMRUCache(1000);

  public static List<String> parse3_cachedInput(String s) {
    List<String> tok = parse3_cachedInput_cache.get(s);
    if (tok == null)
      parse3_cachedInput_cache.put(s, tok = parse3(s));
    return tok;
  }

  public static Map<String, List<String>> parse3_cachedPattern_cache = synchronizedMRUCache(1000);

  public static synchronized List<String> parse3_cachedPattern(String s) {
    List<String> tok = parse3_cachedPattern_cache.get(s);
    if (tok == null)
      parse3_cachedPattern_cache.put(s, tok = parse3(s));
    return tok;
  }

  public static String[] match2(List<String> pat, List<String> tok) {
    int i = pat.indexOf("...");
    if (i < 0)
      return match2_match(pat, tok);
    pat = new ArrayList<String>(pat);
    pat.set(i, "*");
    while (pat.size() < tok.size()) {
      pat.add(i, "*");
      pat.add(i + 1, "");
    }
    return match2_match(pat, tok);
  }

  public static String[] match2_match(List<String> pat, List<String> tok) {
    List<String> result = new ArrayList<String>();
    if (pat.size() != tok.size()) {
      return null;
    }
    for (int i = 1; i < pat.size(); i += 2) {
      String p = pat.get(i), t = tok.get(i);
      if (eq(p, "*"))
        result.add(t);
      else if (!equalsIgnoreCase(unquote(p), unquote(t)))
        return null;
    }
    return result.toArray(new String[result.size()]);
  }

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

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

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

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

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

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

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

  public static String[] drop(int n, String[] a) {
    n = Math.min(n, a.length);
    String[] b = new String[a.length - n];
    System.arraycopy(a, n, b, 0, b.length);
    return b;
  }

  public static Object[] drop(int n, Object[] a) {
    n = Math.min(n, a.length);
    Object[] b = new Object[a.length - n];
    System.arraycopy(a, n, b, 0, b.length);
    return b;
  }

  public static <A> ArrayList<A> toList(A[] a) {
    return asList(a);
  }

  public static ArrayList<Integer> toList(int[] a) {
    return asList(a);
  }

  public static <A> ArrayList<A> toList(Set<A> s) {
    return asList(s);
  }

  public static <A> ArrayList<A> toList(Iterable<A> s) {
    return asList(s);
  }

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

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

  public static <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;
  }

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

  public static int indent_default = 2;

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

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

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

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

  public static 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;
  }

  public static Map vm_generalMap_map;

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

  public static String getProgramName_cache;

  public static String getProgramName() {
    Lock __2418 = downloadLock();
    lock(__2418);
    try {
      if (getProgramName_cache == null)
        getProgramName_cache = getSnippetTitleOpt(programID());
      return getProgramName_cache;
    } finally {
      unlock(__2418);
    }
  }

  public static void _onLoad_getProgramName() {
    startThread(new Runnable() {

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

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

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

  public static Class<?> _getClass(String name) {
    try {
      return Class.forName(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  public static Class _getClass(Object o) {
    return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
  }

  public static Class _getClass(Object realm, String name) {
    try {
      return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  public static 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;
    }
  }

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

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

  public static boolean odd(BigInteger i) {
    return odd(toInt(i));
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static Object collectionMutex(Object 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;
  }

  public static void nohupJavax(final String javaxargs) {
    startThread(new Runnable() {

      public void run() {
        try {
          call(hotwireOnce("#1008562"), "nohupJavax", javaxargs);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs);";
      }
    });
  }

  public static void nohupJavax(final String javaxargs, final String vmArgs) {
    startThread(new Runnable() {

      public void run() {
        try {
          call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs, vmArgs);";
      }
    });
  }

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

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

  public static void consoleClearInput() {
    consoleSetInput("");
  }

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

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

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

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

  public static String actualUserHome_value;

  public static String actualUserHome() {
    if (actualUserHome_value == null) {
      if (isAndroid())
        actualUserHome_value = "/storage/emulated/0/";
      else
        actualUserHome_value = System.getProperty("user.home");
    }
    return actualUserHome_value;
  }

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

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

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

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

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

  public static List<String> parse3(String s) {
    return dropPunctuation(javaTokPlusPeriod(s));
  }

  public static boolean equalsIgnoreCase(String a, String b) {
    return eqic(a, b);
  }

  public static boolean equalsIgnoreCase(char a, char b) {
    return eqic(a, b);
  }

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

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

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

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

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

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

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

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

  public static volatile PersistableThrowable lastException_lastException;

  public static PersistableThrowable lastException() {
    return lastException_lastException;
  }

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

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

  public static String hideCredentials(String url) {
    return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=<hidden>");
  }

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

  public static Lock downloadLock_lock = fairLock();

  public static Lock downloadLock() {
    return downloadLock_lock;
  }

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

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

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

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

  public static String getSnippetTitleOpt(String s) {
    return isSnippetID(s) ? getSnippetTitle(s) : s;
  }

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

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

  public static Class<?> getClass(String name) {
    try {
      return Class.forName(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  public static Class getClass(Object o) {
    return o instanceof Class ? (Class) o : o.getClass();
  }

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

  public static String classNameToVM(String name) {
    return name.replace(".", "$");
  }

  public static <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;
  }

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

  public static int toInt(long l) {
    if (l != (int) l)
      throw fail("Too large for int: " + l);
    return (int) l;
  }

  public static 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;
  }

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

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

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

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

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

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

  public static Class hotwireOnce(String programID) {
    return hotwireCached(programID, false);
  }

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

  public static void consoleSetInput(final String text) {
    if (headless())
      return;
    setTextAndSelectAll(consoleInputField(), text);
    focusConsole();
  }

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

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

  public static List<String> dropPunctuation_keep = litlist("*", "<", ">");

  public static List<String> dropPunctuation(List<String> tok) {
    tok = new ArrayList<String>(tok);
    for (int i = 1; i < tok.size(); i += 2) {
      String t = tok.get(i);
      if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
        tok.set(i - 1, tok.get(i - 1) + tok.get(i + 1));
        tok.remove(i);
        tok.remove(i);
        i -= 2;
      }
    }
    return tok;
  }

  public static String dropPunctuation(String s) {
    return join(dropPunctuation(nlTok(s)));
  }

  public static List<String> javaTokPlusPeriod(String s) {
    List<String> tok = new ArrayList<String>();
    int l = s.length();
    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);
      cc = s.substring(i, Math.min(i + 2, l));
      if (c == (char) 0x201C || c == (char) 0x201D)
        c = '"';
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          char _c = s.charAt(j);
          if (_c == (char) 0x201C || _c == (char) 0x201D)
            _c = '"';
          if (_c == opener) {
            ++j;
            break;
          } else if (s.charAt(j) == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
        if (j - 1 >= i + 1) {
          tok.add(opener + s.substring(i + 1, j - 1) + opener);
          i = j;
          continue;
        }
      } 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)));
      else if (cc.equals("[[")) {
        do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
        j = Math.min(j + 2, l);
      } else if (cc.equals("[=") && 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 if (s.substring(j, Math.min(j + 3, l)).equals("..."))
        j += 3;
      else if (c == '$' || 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;
  }

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

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

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

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

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

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

  public static String getSnippetTitle(String id) {
    try {
      if (id == null)
        return null;
      if (!isSnippetID(id))
        return "?";
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.getSnippetTitle(id);
      if (isLocalSnippetID(id))
        return localSnippetTitle(id);
      long parsedID = parseSnippetID(id);
      String url;
      if (isImageServerSnippet(parsedID))
        url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery();
      else if (isGeneralFileServerSnippet(parsedID))
        url = "http://butter.botcompany.de:8080/files/name/" + parsedID;
      else
        url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies();
      String title = trim(loadPageSilently(url));
      if (title != null)
        try {
          saveTextFileIfChanged(snippetTitle_cacheFile(id), title);
        } catch (Throwable __e) {
          print(exceptionToStringShort(__e));
        }
      return or(title, "?");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String getSnippetTitle(long id) {
    return getSnippetTitle(fsI(id));
  }

  public static int parseInt(String s) {
    return empty(s) ? 0 : Integer.parseInt(s);
  }

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

  public static TreeMap<String, Class> hotwireCached_cache = new TreeMap();

  public static Lock hotwireCached_lock = lock();

  public static Class hotwireCached(String programID) {
    return hotwireCached(programID, true);
  }

  public static Class hotwireCached(String programID, boolean runMain) {
    return hotwireCached(programID, runMain, false);
  }

  public static Class hotwireCached(String programID, boolean runMain, boolean dependent) {
    Lock __2662 = hotwireCached_lock;
    lock(__2662);
    try {
      programID = formatSnippetID(programID);
      Class c = hotwireCached_cache.get(programID);
      if (c == null) {
        c = hotwire(programID);
        if (dependent)
          makeDependent(c);
        if (runMain)
          callMain(c);
        hotwireCached_cache.put(programID, c);
      }
      return c;
    } finally {
      unlock(__2662);
    }
  }

  public static boolean headless() {
    return isHeadless();
  }

  public static JTextField setTextAndSelectAll(final JTextField tf, final String text) {
    {
      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;
  }

  public static JTextField consoleInputField() {
    Object console = get(getJavaX(), "console");
    return (JTextField) getOpt(console, "tfInput");
  }

  public static void focusConsole(String s) {
    setConsoleInput(s);
    focusConsole();
  }

  public static void focusConsole() {
    JComponent tf = consoleInputFieldOrComboBox();
    if (tf != null) {
      tf.requestFocus();
    }
  }

  public static List<String> nlTok(String s) {
    return javaTokPlusPeriod(s);
  }

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

  public static IResourceLoader vm_getResourceLoader() {
    return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
  }

  public static boolean isLocalSnippetID(String snippetID) {
    return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
  }

  public static boolean isLocalSnippetID(long snippetID) {
    return snippetID >= 1000 && snippetID <= 9999;
  }

  public static String localSnippetTitle(String snippetID) {
    if (!isLocalSnippetID(snippetID))
      return null;
    File f = localSnippetFile(snippetID);
    if (!f.exists())
      return null;
    return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed");
  }

  public static boolean isImageServerSnippet(long id) {
    return id >= 1100000 && id < 1200000;
  }

  public static String imageServerURL() {
    return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
  }

  public static String muricaCredentialsQuery() {
    return htmlQuery(muricaCredentials());
  }

  public static boolean isGeneralFileServerSnippet(long id) {
    return id >= 1400000 && id < 1500000;
  }

  public static String tb_mainServer_default = "http://tinybrain.de:8080";

  public static Object tb_mainServer_override;

  public static String tb_mainServer() {
    if (tb_mainServer_override != null)
      return (String) callF(tb_mainServer_override);
    return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
  }

  public static File tb_mainServer_file() {
    return getProgramFile("#1001638", "mainserver.txt");
  }

  public static boolean tb_mainServer_isDefault() {
    return eq(tb_mainServer(), tb_mainServer_default);
  }

  public static String standardCredentials_noCookies() {
    return standardCredentials() + "&noCookies=1";
  }

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

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

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

  public static boolean saveTextFileIfChanged(File f, String contents) {
    return saveTextFileIfDifferent(f, contents);
  }

  public static File snippetTitle_cacheFile(String snippetID) {
    return javaxCachesDir("Snippet Titles/" + psI(snippetID));
  }

  public static 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;
  }

  public static <A> A or(A a, A b) {
    return a != null ? a : b;
  }

  public static String fsI(String id) {
    return formatSnippetID(id);
  }

  public static String fsI(long id) {
    return formatSnippetID(id);
  }

  public static 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;
    }
  }

  public static Object makeDependent_postProcess;

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

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

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

  public static Object swing(Object f) {
    return swingAndWait(f);
  }

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

  public static void setConsoleInput(String text) {
    consoleSetInput(text);
  }

  public static JComponent consoleInputFieldOrComboBox() {
    Object console = get(getJavaX(), "console");
    JComboBox cb = (JComboBox) (getOpt(console, "cbInput"));
    if (cb != null)
      return cb;
    return (JTextField) getOpt(console, "tfInput");
  }

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

  public static <A> A proxy(Object target, Class<A> intrface) {
    return proxy(intrface, target);
  }

  public static long psI(String snippetID) {
    return parseSnippetID(snippetID);
  }

  public static File localSnippetFile(long snippetID) {
    return localSnippetsDir(snippetID + ".text");
  }

  public static File localSnippetFile(String snippetID) {
    return localSnippetFile(parseSnippetID(snippetID));
  }

  public static String or2(String a, String b) {
    return nempty(a) ? a : b;
  }

  public static String or2(String a, String b, String c) {
    return or2(or2(a, b), c);
  }

  public static String getFileInfoField(File f, String field) {
    return getOneLineFileInfoField(f, field);
  }

  public static File dropExtension(File f) {
    return f == null ? null : fileInSameDir(f, dropExtension(f.getName()));
  }

  public static String dropExtension(String s) {
    return takeFirst(s, smartLastIndexOf(s, '.'));
  }

  public static File javaxDataDir_dir;

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

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

  public static String htmlQuery(Map params) {
    return params.isEmpty() ? "" : "?" + makePostData(params);
  }

  public static String htmlQuery(Object... data) {
    return htmlQuery(litmap(data));
  }

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

  public static File getProgramFile(String progID, String fileName) {
    if (new File(fileName).isAbsolute())
      return new File(fileName);
    return new File(getProgramDir(progID), fileName);
  }

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

  public static String standardCredentials() {
    String user = standardCredentialsUser();
    String pass = standardCredentialsPass();
    if (nempty(user) && nempty(pass))
      return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
    return "";
  }

  public static boolean saveTextFileIfDifferent(File f, String contents) {
    if (eq(loadTextFile(f), contents))
      return false;
    {
      saveTextFile(f, contents);
      return true;
    }
  }

  public static File javaxCachesDir_dir;

  public static File javaxCachesDir() {
    return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
  }

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

  public static String unnull(String s) {
    return s == null ? "" : s;
  }

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

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

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

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

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

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

  public static <A, B> Pair<A, B> unnull(Pair<A, B> p) {
    return p != null ? p : new Pair(null, null);
  }

  public static String baseClassName(String className) {
    return substring(className, className.lastIndexOf('.') + 1);
  }

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

  public static String prependIfNempty(String prefix, String s) {
    return empty(s) ? s : prefix + s;
  }

  public static void assertFalse(Object o) {
    if (!(eq(o, false)))
      throw fail(str(o));
  }

  public static boolean assertFalse(boolean b) {
    if (b)
      throw fail("oops");
    return b;
  }

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

  public static boolean _inCore() {
    return false;
  }

  public static List hotwire_copyOver_after = synchroList();

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

  public static List<Class> dependentClasses() {
    return cleanUpAndGetWeakReferencesList(hotwire_classes);
  }

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

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

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

  public static File localSnippetsDir() {
    return javaxDataDir("Personal Programs");
  }

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

  public static String getOneLineFileInfoField(File f, String field) {
    File infoFile = associatedInfosFile(f);
    List<String> lines = lines(loadTextFile(infoFile));
    return firstStartingWithIC_drop(lines, field + ": ");
  }

  public static File fileInSameDir(File f, String newName) {
    return newFile(parentFile(f), newName);
  }

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

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

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

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

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

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

  public static String makePostData(Map<Object, Object> map) {
    List<String> l = new ArrayList();
    for (Map.Entry<Object, Object> e : map.entrySet()) {
      String key = (String) (e.getKey());
      Object val = e.getValue();
      if (val != null) {
        String value = str(val);
        l.add(urlencode(key) + "=" + urlencode((value)));
      }
    }
    return join("&", l);
  }

  public static String makePostData(Object... params) {
    return makePostData(litorderedmap(params));
  }

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

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

  public static volatile boolean muricaPassword_pretendNotAuthed;

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

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

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

  public static String standardCredentialsUser() {
    return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username"))));
  }

  public static String standardCredentialsPass() {
    return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass"))));
  }

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

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

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

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

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

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

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

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

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

  public static List<WeakReference<Class>> hotwire_classes = synchroList();

  public static Class<?> hotwireDependent(String src) {
    Class c = hotwire(src);
    makeDependent(c);
    return c;
  }

  public static void setOptIfNotNull(Object o, String field, Object value) {
    if (value != null)
      setOpt(o, field, value);
  }

  public static Object mainBot;

  public static Object getMainBot() {
    return mainBot;
  }

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

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

  public static <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;
    }
  }

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

  public static File associatedInfosFile(File f) {
    return replaceExtension(f, ".infos");
  }

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

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

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

  public static String firstStartingWithIC_drop(Collection<String> l, final String prefix) {
    for (String s : unnull(l)) if (swic(s, prefix))
      return substring(s, l(prefix));
    return null;
  }

  public static String firstStartingWithIC_drop(String prefix, Collection<String> l) {
    return firstStartingWithIC_drop(l, prefix);
  }

  public static File parentFile(File f) {
    return dirOfFile(f);
  }

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

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

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

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

  public static File programDir_mine;

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

  public static 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;
  }

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

  public static File oneOfTheFiles(String... paths) {
    if (paths != null)
      for (String path : paths) if (fileExists(path))
        return newFile(path);
    return null;
  }

  public static File oneOfTheFiles(File... files) {
    if (files != null)
      for (File f : files) if (fileExists(f))
        return f;
    return null;
  }

  public static File javaxSecretDir_dir;

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

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

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

  public static class CriticalAction {

    public String description;

    public CriticalAction() {
    }

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

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

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

  public static 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;
  }

  public static void 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();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static File replaceExtension(File f, String extOld, String extNew) {
    return newFile(replaceExtension(f2s(f), extOld, extNew));
  }

  public static File replaceExtension(File f, String extNew) {
    return replaceExtension(f, fileExtension(f), extNew);
  }

  public static String replaceExtension(String s, String extOld, String extNew) {
    s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s);
    return s + addPrefixOptIfNempty(".", extNew);
  }

  public static String replaceExtension(String name, String extNew) {
    return replaceExtension(name, fileExtension(name), extNew);
  }

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

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

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

  public static 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;
  }

  public static 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;
  }

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

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

  public static File dirOfFile(File f) {
    return f == null ? null : f.getParentFile();
  }

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

  public static volatile String caseID_caseID;

  public static String caseID() {
    return caseID_caseID;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static Set vm_busListeners_live_cache;

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

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

  public static Map<String, Set> vm_busListenersByMessage_live_cache;

  public static 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;
  }

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

  public static Object pcallFunction(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable __e) {
      _handleException(__e);
    }
    return null;
  }

  public static String fileExtension(File f) {
    if (f == null)
      return null;
    return fileExtension(f.getName());
  }

  public static String fileExtension(String s) {
    return substring(s, smartLastIndexOf(s, '.'));
  }

  public static String dropSuffixIC(String suffix, String s) {
    return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

  public static String addPrefixOptIfNempty(String prefix, String s) {
    return addPrefixIfNotEmpty2(prefix, s);
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static String addPrefixIfNotEmpty2(String prefix, String s) {
    return empty(s) ? "" : addPrefix(prefix, s);
  }

  public static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {

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

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

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

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

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

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

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

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

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

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

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

  public static 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;
  }

  public static String addPrefix(String prefix, String s) {
    return s.startsWith(prefix) ? s : prefix + s;
  }

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

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

      public A a;

      public boolean done;

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

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

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

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

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

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

  public static int gzInputStream_defaultBufferSize = 65536;

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

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

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

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

  public static final class _MethodCache {

    public final Class c;

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

  public static 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 abstract static class CloseableIterableIterator<A> extends IterableIterator<A> implements AutoCloseable {

    public void close() throws Exception {
    }
  }

  public abstract static class DialogIO {

    public String line;

    public boolean eos, loud, noClose;

    public Lock lock = lock();

    public abstract String readLineImpl();

    public abstract boolean isStillConnected();

    public abstract void sendLine(String line);

    public abstract boolean isLocalConnection();

    public abstract Socket getSocket();

    public abstract void close();

    public int getPort() {
      Socket s = getSocket();
      return s == null ? 0 : s.getPort();
    }

    public boolean helloRead;

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

  public abstract static class DialogHandler {

    public abstract void run(DialogIO io);
  }

  public static class Var<A> implements IVar<A> {

    public A v;

    public Var() {
    }

    public Var(A v) {
      this.v = 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());
    }
  }

  public abstract static class DynAttractorBot extends DynPrintLog {

    public String input, dialogText;

    public transient AttractorBot bot;

    public void submitInput() {
      setField("input", trim(input));
      addToDialog("User: " + input);
      if (bot != null)
        bot.addInput(input);
    }

    public JComponent visualize() {
      return jtabs("Dialog", northCenterAndSouthWithMargins(rightAlignedButtons("New dialog", runnableThread(new Runnable() {

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

        public String toString() {
          return "startDialog();";
        }
      }), "Clear window", runnableThread(new Runnable() {

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

        public String toString() {
          return "clearDialogText();";
        }
      })), wordWrapTextArea(dm_textArea_scrollDown_readOnly("dialogText")), dm_textFieldAndSubmit_q("input", "submitInput", "focusOnShow", true)), "Log", super.visualize());
    }

    public void runBot(AttractorBot bot) {
      this.bot = bot;
      runBot();
    }

    public void addToDialog(String s) {
      setField("dialogText", appendWithNewLine(dialogText, print(s)));
    }

    public void runBot() {
      bot.say = new VF1<String>() {

        public void get(String s) {
          try {
            addToDialog("Bot: " + s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "addToDialog(\"Bot: \" + s)";
        }
      };
      startThread("Bot", new Runnable() {

        public void run() {
          try {
            bot.run_public();
            print("\n[end]");
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "bot.run_public();\r\n      print(\"\\n[end]\");";
        }
      });
    }

    public void clearDialogText() {
      setField("dialogText", "");
    }

    public abstract AttractorBot makeBot();

    public void startDialog() {
      clearDialogText();
      runBot(makeBot());
    }

    public void start() {
      super.start();
      logModuleOutput();
      startDialog();
    }
  }

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

  public static class AI_FactsBot extends AttractorBot {

    public Collection<String> facts = synchroCISet();

    public void run() {
      say("I can store facts. Just type them. " + n2(facts, "fact") + " stored.");
    }

    public class QuestionAttractor extends Attractor {

      public boolean matches(String s) {
        return ai_isQuestion_2(s);
      }

      public void run() {
        say("I cannot answer questions yet");
      }
    }

    public class StoreFactAttractor extends Attractor {

      public String category;

      public boolean matches(String s) {
        return true;
      }

      public void run() {
        if (facts.add(line))
          say("Fact stored");
        else
          say("I know");
      }
    }

    public AI_FactsBot() {
      standardAttractors(new QuestionAttractor(), new StoreFactAttractor());
    }
  }

  public static class Attractor implements IAttractor, Runnable {

    public F1<String, Boolean> tester;

    public Runnable action;

    public Attractor() {
    }

    public Attractor(F1<String, Boolean> tester, Runnable action) {
      this.action = action;
      this.tester = tester;
    }

    public Attractor(Runnable action) {
      this.action = action;
    }

    public boolean matches(String s) {
      return isTrue(callF(tester, s));
    }

    public void run() {
      callF(action);
    }

    public String toString() {
      return standard_toString(this);
    }
  }

  public static class DefaultAttractor extends Attractor {

    public DefaultAttractor() {
      this(null);
    }

    public DefaultAttractor(Runnable action) {
      this.action = action;
      tester = f1_true();
    }
  }

  public static class MatchAttractor extends Attractor {

    public String pattern;

    public MatchAttractor(String pattern) {
      this.pattern = pattern;
    }

    public MatchAttractor(String pattern, Runnable action) {
      this.action = action;
      this.pattern = pattern;
    }

    public boolean matches(String s) {
      return matchX2(pattern, s);
    }
  }

  public static class YesAttractor extends Attractor {

    public YesAttractor() {
      tester = new F1<String, Boolean>() {

        public Boolean get(String x) {
          try {
            return isYes_1(x);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "isYes_1(x)";
        }
      };
    }

    public YesAttractor(Runnable action) {
      this();
      this.action = action;
    }
  }

  public abstract static class AttractorBot extends AbstractSayAndInputBot implements Runnable {

    public List<String> inputQueue = synchroLinkedList();

    public Set<Thread> activeThreads = synchroSet();

    public List preprocessors = synchroList();

    public F1<String, Boolean> isYes = new F1<String, Boolean>() {

      public Boolean get(String x) {
        try {
          return isYes_1(x);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "isYes_1(x)";
      }
    };

    public LinkedHashSet<String> facts = new LinkedHashSet();

    public LinkedHashSet<String> assumptions = new LinkedHashSet();

    public List<Attractor> standardAttractors = synchroList();

    public List<Attractor> activeAttractors = synchroList();

    public List<Attractor> lowPrioAttractors = synchroList();

    public String line;

    public AttractorBot() {
      input = new F0<String>() {

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

        public String toString() {
          return "ret getInput();";
        }
      };
      standardPreprocessors();
    }

    public void remember(String fact) {
      if (facts.add(fact))
        print("[Bot learned:] " + fact);
    }

    public void assume(String fact) {
      if (assumptions.add(fact))
        print("[Bot assumes:] " + fact);
    }

    public String getInput() {
      while (empty(inputQueue)) sleep(10);
      return trim(popFirst(inputQueue));
    }

    public boolean yes() {
      return callF(isYes, input());
    }

    public void run_public() {
      AutoCloseable __8 = tempAddToCollection(activeThreads, currentThread());
      try {
        run();
      } finally {
        _close(__8);
      }
    }

    public void addInput(String s) {
      inputQueue.add(s);
      line = s;
      if (empty(activeThreads))
        attractorBattle();
    }

    public void attractorBattle() {
      if (empty(inputQueue))
        return;
      String input = getInput();
      print("Input: " + input);
      List<Attractor> attractors = getAndClearList(activeAttractors);
      addAll(attractors, standardAttractors);
      addAll(attractors, getAndClearList(lowPrioAttractors));
      if (empty(attractors)) {
        print("No attractors, ignoring input");
        return;
      }
      List<Attractor> matchingAttractors = new ArrayList();
      for (Attractor a : attractors) {
        try {
          if (a.matches(input))
            matchingAttractors.add(a);
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
      if (empty(matchingAttractors)) {
        print("No matching attractors, ignoring input");
        return;
      }
      print("Got " + n2(matchingAttractors, "matching attractor") + ": " + matchingAttractors);
      Attractor winner = first(matchingAttractors);
      if (l(matchingAttractors) > 1)
        print("Choosing first attractor");
      winner.run();
    }

    public void addAttractor(Attractor a) {
      addAttractors(a);
    }

    public void tempAttractor(Attractor a) {
      addAttractors(a);
    }

    public void addAttractors(Attractor... attractors) {
      addAll(activeAttractors, attractors);
    }

    public void addLowPrioAttractor(Attractor a) {
      add(lowPrioAttractors, a);
    }

    public void standardAttractors(Attractor... attractors) {
      addAll(standardAttractors, attractors);
    }

    public void addPreprocessors(Object... l) {
      addAll(preprocessors, l);
    }

    public void standardPreprocessors() {
      addPreprocessors("ai_dropLeadingAndTrailingAppellations_sortedByLength");
    }
  }

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

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

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

  public abstract static class NotifyingSet<A> extends NotifyingCollection<A> implements Set<A> {

    public Set<A> set;

    public NotifyingSet() {
    }

    public NotifyingSet(Set<A> set) {
      super(set);
      this.set = set;
    }
  }

  public static class AbstractSayAndInputBot {

    public VF1<String> say;

    public F0<String> input;

    public void say(String s) {
      callF(say, s);
    }

    public String input() {
      return callF(input);
    }
  }

  public abstract static class NotifyingCollection<E> extends AbstractCollection<E> implements Collection<E> {

    public Collection<E> c;

    public NotifyingCollection() {
    }

    public NotifyingCollection(Collection<E> c) {
      this.c = c;
    }

    public int size() {
      synchronized (this) {
        return c.size();
      }
    }

    public boolean isEmpty() {
      synchronized (this) {
        return c.isEmpty();
      }
    }

    public boolean contains(Object o) {
      synchronized (this) {
        return c.contains(o);
      }
    }

    public Object[] toArray() {
      synchronized (this) {
        return c.toArray();
      }
    }

    public <T> T[] toArray(T[] a) {
      synchronized (this) {
        return c.toArray(a);
      }
    }

    public Iterator<E> iterator() {
      return c.iterator();
    }

    public boolean add(E e) {
      synchronized (this) {
        if (!c.add(e))
          return false;
      }
      change();
      return true;
    }

    public boolean remove(Object o) {
      synchronized (this) {
        if (!c.remove(o))
          return false;
      }
      change();
      return true;
    }

    public boolean containsAll(Collection<?> coll) {
      synchronized (this) {
        return c.containsAll(coll);
      }
    }

    public boolean addAll(Collection<? extends E> coll) {
      synchronized (this) {
        if (!c.addAll(coll))
          return false;
      }
      change();
      return true;
    }

    public boolean removeAll(Collection<?> coll) {
      synchronized (this) {
        if (!c.removeAll(coll))
          return false;
      }
      change();
      return true;
    }

    public boolean retainAll(Collection<?> coll) {
      synchronized (this) {
        if (!c.retainAll(coll))
          return false;
      }
      change();
      return true;
    }

    public void clear() {
      synchronized (this) {
        c.clear();
      }
      change();
    }

    public String toString() {
      synchronized (this) {
        return c.toString();
      }
    }

    @Override
    public Spliterator<E> spliterator() {
      return c.spliterator();
    }

    public abstract void change();

    public Collection<E> unwrap() {
      return c;
    }
  }

  public static interface IVar<A> {

    public void set(A a);

    public A get();

    public boolean has();

    public void clear();
  }

  public static List<String> ai_dropLeadingAndTrailingAppellations_sortedByLength(String s) {
    return stringsSortedByLength(ai_dropLeadingAndTrailingAppellations_iterator(s));
  }

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

  public static <A, B> void multiMapPut(Map<A, List<B>> map, A a, B b) {
    List<B> l = map.get(a);
    if (l == null)
      map.put(a, l = new ArrayList());
    l.add(b);
  }

  public static Field makeAccessible(Field f) {
    f.setAccessible(true);
    return f;
  }

  public static Method makeAccessible(Method m) {
    m.setAccessible(true);
    return m;
  }

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

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

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

  public static 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;
  }

  public static 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;
  }

  public static 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;
  }

  public static 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;
  }

  public static JTabbedPane jtabs(Object... x) {
    return fillJTabs(swingNu(JTabbedPane.class), x);
  }

  public static JPanel northCenterAndSouthWithMargins(Component n, Component c, Component s) {
    return applyDefaultMargin(northCenterAndSouth(withBottomMargin(n), c, withTopMargin(s)));
  }

  public static JPanel rightAlignedButtons(Object... params) {
    return jRightAlignedButtons(params);
  }

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

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

  public static JTextArea wordWrapTextArea(JTextArea ta) {
    enableWordWrapForTextArea(ta);
    return ta;
  }

  public static JTextArea dm_textArea_scrollDown_readOnly(String field) {
    return jLiveValueTextArea_scrollDown(dm_fieldLiveValue(field));
  }

  public static JComponent dm_textFieldAndSubmit_q(String field, final String submitMethodName, Object... __) {
    final DynModule m = dm_current_mandatory();
    return dm_textFieldAndSubmit(field, r_dm_q(new Runnable() {

      public void run() {
        try {
          call(m, submitMethodName);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "call(m, submitMethodName)";
      }
    }), __);
  }

  public static String appendWithNewLine(String a, String b) {
    if (empty(b))
      return a;
    if (empty(a))
      return b;
    return addSuffix(a, "\n") + b;
  }

  public static boolean logModuleOutput_installed;

  public static void logModuleOutput() {
    if (logModuleOutput_installed)
      return;
    logModuleOutput_installed = true;
    final File logFile = getProgramFile("output.txt");
    final LineBuffer buf = new LineBuffer(new VF1<String>() {

      public void get(String line) {
        try {
          appendToTextFile(logFile, "[" + localDateWithMilliseconds() + "] " + line + "\n");
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "appendToTextFile(logFile, \"[\" + localDateWithMilliseconds() + \"] \" + line + \"...";
      }
    });
    print_forAllThreads(new VF1<String>() {

      public void get(String s) {
        try {
          buf.append(s);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "buf.append(s);";
      }
    });
  }

  public static File loadLibrary(String snippetID) {
    return loadBinarySnippet(snippetID);
  }

  public static Set<String> synchroCISet() {
    return synchroSet(caseInsensitiveSet());
  }

  public static void say(String s) {
    print(s);
  }

  public static boolean ai_isQuestion_2(String s) {
    return ai_isYesNoQuestion_1(s) || ai_questionWord_1(firstWord2(s));
  }

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

  public static <A> Set<A> synchroSet() {
    return synchroHashSet();
  }

  public static <A> Set<A> synchroSet(Set<A> set) {
    return Collections.synchronizedSet(set);
  }

  public static boolean isYes_1(String s) {
    return match_vbar("accept|except|save|definitely|and if it is|is if it is right|is this|right|enter|submit|send|you got it|close enough|that it is|bingo|confirm|confirming|confirmed|i said yes|it is|surely|is this the man|guess my man|just|sieve|yesterday's", s) || matchStart_vbar("yes|yeah|yep|yup|yo|yay|absolutely|correct|you can say that|chore|shore|shorts|sure|is yes|okay|ok|that's correct|you are right|you're right|you're correct|you just said it", s) || matchEnd_vbar("that's right|got it|could say that|could say so|that's it|couldn't be anything else", s);
  }

  public static volatile boolean sleep_noSleep;

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

  public static void sleep() {
    try {
      if (sleep_noSleep)
        throw fail("nosleep");
      print("Sleeping.");
      sleepQuietly();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static <A> A popFirst(List<A> l) {
    if (empty(l))
      return null;
    A a = first(l);
    l.remove(0);
    return a;
  }

  public static <A> A popFirst(Collection<A> l) {
    if (empty(l))
      return null;
    A a = first(l);
    l.remove(a);
    return a;
  }

  public static <A> AutoCloseable tempAddToCollection(Collection<A> l, A a) {
    return tempAdd(l, a);
  }

  public static Class run(String progID, String... args) {
    Class main = hotwire(progID);
    callMain(main, args);
    return main;
  }

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

  public static <A> List<A> getAndClearList(Collection<A> l) {
    if (l == null)
      return emptyList();
    synchronized (collectionMutex(l)) {
      List<A> out = cloneList(l);
      l.clear();
      return out;
    }
  }

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

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

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

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

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

  public static Object[] toArray(Collection c) {
    return toObjectArray(c);
  }

  public static <A> A[] toArray(Collection c, Class<A> type) {
    A[] a = arrayOfType(l(c), type);
    if (a.length == 0)
      return a;
    asList(c).toArray(a);
    return a;
  }

  public static JComponent unwrap(JComponent c) {
    return c instanceof JScrollPane ? unwrapScrollPane((JScrollPane) c) : c;
  }

  public static List<String> stringsSortedByLength(Iterable<String> l) {
    return sortedByCalculatedField(l, new F1<String, Integer>() {

      public Integer get(String s) {
        try {
          return l(s);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "l(s)";
      }
    });
  }

  public static IterableIterator<String> ai_dropLeadingAndTrailingAppellations_iterator(String s) {
    final Set<String> phrases = mechSetCI("Appellations");
    return repeatedInputModificationsIterator(s, new F1<String, List<IterableIterator<String>>>() {

      public List<IterableIterator<String>> get(String s) {
        try {
          return ai_dropLeadingAndTrailingPhrasesIterators(s, phrases);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ai_dropLeadingAndTrailingPhrasesIterators(s, phrases)";
      }
    });
  }

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

  public static JTabbedPane fillJTabs(final JTabbedPane tabs, final Object... _x) {
    if (tabs != null) {
      swing(new Runnable() {

        public void run() {
          try {
            clearTabs(tabs);
            Object[] x = flattenArray2(_x);
            int idx = 0;
            if (get(x, 0) instanceof Integer) {
              idx = asInt(get(x, 0));
              x = dropFirst(x);
              if (empty(x)) {
                x = arrayrep(null, idx);
                idx = 0;
              }
            }
            int n = 0;
            for (int i = 0; i < l(x); i++) {
              ++n;
              if (x[i] instanceof Component)
                tabs.addTab("Tab " + n, wrap((Component) x[i]));
              else {
                String name = str(or(x[i], "Tab " + n));
                Component c;
                if (get(x, i + 1) instanceof Component)
                  c = (Component) get(x, ++i);
                else
                  c = new JPanel();
                tabs.addTab(name, wrap(c));
              }
            }
            if (idx != 0)
              tabs.setSelectedIndex(min(tabs.getTabCount() - 1, idx));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "clearTabs(tabs);\r\n    Object[] x = flattenArray2(_x);\r\n    ifdef fillJTabs_de...";
        }
      });
    }
    return tabs;
  }

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

  public static <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;
  }

  public static JPanel northCenterAndSouth(Component n, Component c, Component s) {
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(BorderLayout.NORTH, wrap(n));
    panel.add(BorderLayout.CENTER, wrap(c));
    panel.add(BorderLayout.SOUTH, wrap(s));
    return panel;
  }

  public static int withBottomMargin_defaultWidth = 6;

  public static JPanel withBottomMargin(Component c) {
    return withBottomMargin(withBottomMargin_defaultWidth, c);
  }

  public static JPanel withBottomMargin(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(0, 0, w, 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...";
      }
    });
  }

  public static int withTopMargin_defaultWidth = 6;

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

  public static 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...";
      }
    });
  }

  public static JPanel jRightAlignedButtons(Object... params) {
    List<JComponent> l = new ArrayList();
    for (int i = 0; i < l(params); i += 2) if (params[i] != null)
      if (params[i] instanceof JComponent)
        l.add((JComponent) params[i--]);
      else
        l.add(jbutton((String) params[i], params[i + 1]));
    return jRightAlignedLine(l);
  }

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

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

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

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

  public static JTextArea jLiveValueTextArea_scrollDown(final SimpleLiveValue<String> lv) {
    final JTextArea ta = typeWriterTextArea();
    bindTextComponentToLiveValue_scrollDown(ta, lv);
    return ta;
  }

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

  public static SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
    Lock __84 = module.lock;
    lock(__84);
    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(__84);
    }
  }

  public static JComponent dm_textFieldAndSubmit(String field, final String submitMethodName, Object... __) {
    final DynModule m = dm_current_mandatory();
    return dm_textFieldAndSubmit(field, runnableThread(new Runnable() {

      public void run() {
        try {
          call(m, submitMethodName);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "call(m, submitMethodName)";
      }
    }), __);
  }

  public static JComponent dm_textFieldAndSubmit(String field, Runnable action, Object... __) {
    JTextField tf = boolPar("centered", __) ? dm_centeredTextField(field) : dm_textField(field);
    if (boolPar("focusOnShow", __))
      focusAndSelectAllOnShow(tf);
    return centerAndEastWithMargin(onEnter(tf, action), jbutton(optPar("buttonText", __, "Submit"), action));
  }

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

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

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

  public static String addSuffix(String s, String suffix) {
    return s == null || s.endsWith(suffix) ? s : s + suffix;
  }

  public static void appendToTextFile(File file, String contents) {
    try {
      File parentFile = file.getParentFile();
      if (parentFile != null)
        parentFile.mkdirs();
      if (contents != null) {
        FileOutputStream fileOutputStream = new FileOutputStream(file, true);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
        PrintWriter printWriter = new PrintWriter(outputStreamWriter);
        printWriter.print(contents);
        printWriter.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

  public static void print_forAllThreads(Object f) {
    assertNull("todo", print_allThreads);
    print_allThreads = f;
  }

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

  public static boolean ai_isYesNoQuestion_1(String s) {
    return ai_yesNoQuestionWord_1(firstWord(s));
  }

  public static Set<String> ai_questionWord_1_list = litciset("what", "who", "why", "when", "where", "how");

  public static boolean ai_questionWord_1(String s) {
    return containsNotNull(ai_questionWord_1_list, s);
  }

  public static String firstWord2(String s) {
    s = xltrim(s);
    if (empty(s))
      return "";
    if (isLetterOrDigit(first(s)))
      return takeCharsWhile(s, "isLetterOrDigit");
    else
      return "" + first(s);
  }

  public static <A> Set<A> synchroHashSet() {
    return Collections.synchronizedSet(new HashSet<A>());
  }

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

  public static boolean match_vbar(String pat, String s, Matches matches) {
    for (String pat2 : tok_splitAtVerticalBar(pat)) if (match3(pat2, s, matches))
      return true;
    return false;
  }

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

  public static boolean matchStart_vbar(String pat, String s, Matches matches) {
    for (String pat2 : splitAtTokens(pat, ll("|"))) if (matchStart(pat2, s, matches))
      return true;
    return false;
  }

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

  public static boolean matchEnd_vbar(String pat, String s, Matches matches) {
    for (String pat2 : splitAtTokens(pat, ll("|"))) if (matchEnd(pat2, s, matches))
      return true;
    return false;
  }

  public static Object sleepQuietly_monitor = new Object();

  public static void sleepQuietly() {
    try {
      assertFalse(isAWTThread());
      synchronized (sleepQuietly_monitor) {
        sleepQuietly_monitor.wait();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

  public static JComponent unwrapScrollPane(JScrollPane sp) {
    return sp == null ? null : (JComponent) sp.getViewport().getView();
  }

  public static int withMargin_defaultWidth = 6;

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

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

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

  public static 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...";
      }
    });
  }

  public static boolean isLetterOrDigit(char c) {
    return Character.isLetterOrDigit(c);
  }

  public static <A> List<A> sortedByCalculatedField(Iterable<A> c, Object f) {
    return sortByCalculatedField(c, f);
  }

  public static <A> List<A> sortedByCalculatedField(Object f, Iterable<A> c) {
    return sortedByCalculatedField(c, f);
  }

  public static TreeSet<String> mechSetCI(String name) {
    return mechCISet(name);
  }

  public static <A extends Iterator<String>> IterableIterator<String> repeatedInputModificationsIterator(String input, final F1<String, List<A>> makeIterators) {
    final HashSet<String> seen = lithashset(input);
    final LinkedList<Iterator<String>> pool = new LinkedList();
    addAll(pool, callF(makeIterators, input));
    return iteratorFromFunction(new F0<String>() {

      public String get() {
        try {
          while (!empty(pool)) {
            ping();
            Iterator<String> it = first(pool);
            if (!it.hasNext()) {
              removeFirst(pool);
              continue;
            }
            String entry = it.next();
            if (!seen.add(entry))
              continue;
            addAll(pool, callF(makeIterators, entry));
            return entry;
          }
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "while ping (!empty(pool)) {\r\n      Iterator<S> it = first(pool);\r\n      if (!...";
      }
    });
  }

  public static List<IterableIterator<String>> ai_dropLeadingAndTrailingPhrasesIterators(String s, Set<String> phrases) {
    return ll(ai_dropLeadingPhrases(s, phrases), ai_dropTrailingPhrases(s, phrases));
  }

  public static void clearTabs(final JTabbedPane tabs) {
    if (tabs != null) {
      swing(new Runnable() {

        public void run() {
          try {
            tabs.removeAll();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "tabs.removeAll();";
        }
      });
    }
  }

  public static Object[] flattenArray2(Object... a) {
    List l = new ArrayList();
    if (a != null)
      for (Object x : a) if (x instanceof Object[])
        l.addAll(asList((Object[]) x));
      else if (x instanceof Collection)
        l.addAll((Collection) x);
      else
        l.add(x);
    return asObjectArray(l);
  }

  public static int asInt(Object o) {
    return toInt(o);
  }

  public static Object[] arrayrep(Object a, int n) {
    return asArray(repeat(a, n));
  }

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

  public static Component wrap_2(Object swingable) {
    if (swingable == null)
      return null;
    Component c;
    if (swingable instanceof Component)
      c = (Component) swingable;
    else
      c = (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;
  }

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

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

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

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

  public static JPanel jRightAlignedLine(Component... components) {
    return jrightAlignedLine(components);
  }

  public static JPanel jRightAlignedLine(List<? extends Component> components) {
    return jrightAlignedLine(components);
  }

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

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

  public static boolean setText_opt = true;

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

  public static <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;
  }

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

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

  public static <A> 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;
  }

  public static JTextArea typeWriterTextArea() {
    return newTypeWriterTextArea();
  }

  public static JTextArea typeWriterTextArea(String text) {
    return newTypeWriterTextArea(text);
  }

  public static <A extends JTextComponent> A bindTextComponentToLiveValue_scrollDown(final A tc, final LiveValue lv) {
    return bindLiveValueListenerToComponent(tc, lv, new Runnable() {

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

      public String toString() {
        return "setTextAndMoveCaretToEnd(tc, strOrNull(lv.get()))";
      }
    });
  }

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

  public static boolean boolPar(ThreadLocal<Boolean> tl) {
    return boolOptParam(tl);
  }

  public static boolean boolPar(Object[] __, String name) {
    return boolOptParam(__, name);
  }

  public static boolean boolPar(String name, Object[] __) {
    return boolOptParam(__, name);
  }

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

  public static JTextField dm_centeredTextField(String field) {
    return centerTextField(dm_textField(field));
  }

  public static JTextField dm_textField(String field) {
    return dm_fieldTextField(field);
  }

  public static <A extends JComponent> A focusOnShow(final A a) {
    onFirstComponentShow(a, new Runnable() {

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

      public String toString() {
        return "focus(a)";
      }
    });
    return a;
  }

  public static <A extends JTextComponent> A focusAndSelectAllOnShow(final A a) {
    onFirstComponentShow(a, new Runnable() {

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

      public String toString() {
        return "focusAndSelectAll(a)";
      }
    });
    return a;
  }

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

  public static 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;
  }

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

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

  public static 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;
  }

  public static 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;
  }

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

  public static <A> A optPar(ThreadLocal<A> tl, A defaultValue) {
    A a = tl.get();
    if (a != null) {
      tl.set(null);
      return a;
    }
    return defaultValue;
  }

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

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

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

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

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

  public static Q dm_q() {
    return dm_current_mandatory().q();
  }

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

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

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

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

  public static SimpleDateFormat simpleDateFormat_local(String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    sdf.setTimeZone(localTimeZone());
    return sdf;
  }

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

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

  public static 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 dir = imageSnippetsCacheDir();
      if (loadBufferedImage_useImageCache) {
        dir.mkdirs();
        File file = new File(dir, snippetID + ".png");
        if (file.exists() && file.length() != 0)
          return file;
      }
      String imageURL = snippetImageURL_noHttps(snippetID);
      System.err.println("Loading image: " + imageURL);
      byte[] data = loadBinaryPage(imageURL);
      File file = new File(dir, snippetID + ".png");
      saveBinaryFile(file, data);
      return file;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  public static 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("http://data.tinybrain.de/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;
  }

  public static long fileSize(String path) {
    return getFileSize(path);
  }

  public static long fileSize(File f) {
    return getFileSize(f);
  }

  public static 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("http://data.tinybrain.de/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) {
        printStackTrace(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);
    }
  }

  public static Set<String> ai_yesNoQuestionWord_1_list = litciset("am", "are", "is", "can", "does", "do", "did", "would", "might", "will", "must", "should", "has", "have");

  public static boolean ai_yesNoQuestionWord_1(String s) {
    return containsNotNull(ai_yesNoQuestionWord_1_list, s);
  }

  public static String firstWord(String s) {
    return firstJavaToken(s);
  }

  public static TreeSet<String> litciset(String... items) {
    TreeSet<String> set = caseInsensitiveSet();
    for (String a : items) set.add(a);
    return set;
  }

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

  public static boolean containsNotNull(Object[] x, Object o) {
    return o != null && contains(x, o);
  }

  public static String xltrim(String s) {
    int i = 0;
    while (i < s.length() && contains(" \t\r\n", s.charAt(i))) ++i;
    return substr(s, i);
  }

  public static String takeCharsWhile(String s, Object pred) {
    int i = 0;
    while (i < l(s) && isTrue(callF(pred, s.charAt(i)))) ++i;
    return substring(s, 0, i);
  }

  public static List<String> tok_splitAtVerticalBar(String s) {
    if (!contains(s, '|'))
      return ll(s);
    return splitAtTokens(javaTokPlusBrackets2(s), tok_splitAtVerticalBar_list);
  }

  public static List<String> tok_splitAtVerticalBar_list = ll("|");

  public static List<String> splitAtTokens(String s, List<String> tokens) {
    return splitAtTokens(javaTok(s), tokens);
  }

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

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

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

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

  public static boolean matchStart(String pat, List<String> toks, Matches matches) {
    if (toks == null)
      return false;
    List<String> tokpat = parse3_cachedPattern(pat);
    if (toks.size() < tokpat.size())
      return false;
    String[] m = match2(tokpat, toks.subList(0, tokpat.size()));
    if (m == null)
      return false;
    if (matches != null) {
      matches.m = new String[m.length + 1];
      arraycopy(m, matches.m);
      matches.m[m.length] = join(toks.subList(tokpat.size(), toks.size()));
    }
    return true;
  }

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

  public static boolean matchEnd(String pat, String s, Matches matches) {
    if (s == null)
      return false;
    List<String> tokpat = parse3(pat), toks = parse3(s);
    if (toks.size() < tokpat.size())
      return false;
    String[] m = match2(tokpat, takeLast(l(tokpat), toks));
    if (m == null)
      return false;
    if (matches != null) {
      matches.m = new String[m.length + 1];
      arraycopy(m, matches.m);
      matches.m[m.length] = join(dropLast(l(tokpat), toks));
    }
    return true;
  }

  public static boolean loadBufferedImage_useImageCache = true;

  public static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) {
    try {
      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);
    }
  }

  public static BufferedImage loadBufferedImage(File file) {
    try {
      return file.isFile() ? ImageIO.read(file) : null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static <A> List<A> sortByCalculatedField(Iterable<A> c, final Object f) {
    List<A> l = cloneList(c);
    sort(l, new Comparator<A>() {

      public int compare(A a, A b) {
        return stdcompare(callF(f, a), callF(f, b));
      }
    });
    return l;
  }

  public static MechListDependentCaches<TreeSet<String>> mechCISet_cache = new MechListDependentCaches(new F1<String, TreeSet<String>>() {

    public TreeSet<String> get(String text) {
      try {
        return asCISet(tlft(text));
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public String toString() {
      return "asCISet(tlft(text))";
    }
  });

  public static TreeSet<String> mechCISet(String name) {
    return mechCISet_cache.get(name);
  }

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

  public static <A> IterableIterator<A> iteratorFromFunction(final Object f) {
    class IFF extends IterableIterator<A> {

      public A a;

      public boolean done;

      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 = (A) callF(f);
        done = a == null;
      }
    }
    ;
    return new IFF();
  }

  public static <A> IterableIterator<A> iteratorFromFunction(final F0<A> f) {
    return iteratorFromFunction_f0(f);
  }

  public static void removeFirst(List l) {
    if (nempty(l))
      l.remove(0);
  }

  public static IterableIterator<String> ai_dropLeadingPhrases(String s, Collection<String> phrases) {
    final Set<String> set = asCISet(phrases);
    List<String> tok = javaTokNPunctuation(s);
    return notNulls_iterator(mapIterator(allTokSplits_nOnLeft_iterator(tok), new F1<Pair<List<String>, List<String>>, String>() {

      public String get(Pair<List<String>, List<String>> p) {
        try {
          return set.contains(trimJoin(simpleSpaces(p.a))) ? join(p.b) : null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "set.contains(trimJoin(simpleSpaces(p.a))) ? join(p.b) : null";
      }
    }));
  }

  public static IterableIterator<String> ai_dropTrailingPhrases(String s, Collection<String> phrases) {
    final Set<String> set = asCISet(phrases);
    List<String> tok = javaTokNPunctuation(s);
    return notNulls_iterator(mapIterator(allTokSplits_nOnRight_iterator(tok), new F1<Pair<List<String>, List<String>>, String>() {

      public String get(Pair<List<String>, List<String>> p) {
        try {
          return set.contains(trimJoin(simpleSpaces(p.b))) ? join(p.a) : null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "set.contains(trimJoin(simpleSpaces(p.b))) ? join(p.a) : null";
      }
    }));
  }

  public static Object[] asObjectArray(List l) {
    return toObjectArray(l);
  }

  public static Object[] asArray(List l) {
    return toObjectArray(l);
  }

  public static <A> A[] asArray(Class<A> type, List l) {
    return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
  }

  public static <A extends Component> A _recordNewSwingComponent(A c) {
    if (c != null)
      callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
    return c;
  }

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

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

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

  public static boolean newButton_autoToolTip = true;

  public static 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...";
      }
    });
  }

  public static JPanel jrightAlignedLine(final Component... components) {
    return swing(new F0<RightAlignedLine>() {

      public RightAlignedLine get() {
        try {
          return new RightAlignedLine(components);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret RightAlignedLine(components);";
      }
    });
  }

  public static JPanel jrightAlignedLine(List<? extends Component> components) {
    return jrightAlignedLine(asArray(Component.class, components));
  }

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

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

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

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

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

  public static JTextArea newTypeWriterTextArea(String text) {
    return setFont(jTextArea(text), typeWriterFont());
  }

  public static <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;
  }

  public static <A extends JTextComponent> A setTextAndMoveCaretToEnd(final String text, final A c) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            setText(c, text);
            moveCaretToEnd(c);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "setText(c, text);\r\n    moveCaretToEnd(c);";
        }
      });
    }
    return c;
  }

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

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

  public static boolean boolOptParam(ThreadLocal<Boolean> tl) {
    return isTrue(optPar(tl));
  }

  public static boolean boolOptParam(Object[] __, String name) {
    return isTrue(optParam(__, name));
  }

  public static boolean boolOptParam(String name, Object[] __) {
    return boolOptParam(__, name);
  }

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

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

  public static <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;
  }

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

  public static <A extends JTextField> A centerTextField(A tf) {
    tf.setHorizontalAlignment(JTextField.CENTER);
    return tf;
  }

  public static JTextField dm_fieldTextField(String field) {
    return jLiveValueTextField_bothWays(dm_fieldLiveValue(field));
  }

  public static <A extends JComponent> A onFirstComponentShow(final A component, final Runnable onShow) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            component.addAncestorListener(new AncestorListener() {

              public void ancestorAdded(AncestorEvent event) {
                component.removeAncestorListener(this);
                pcallF(onShow);
              }

              public void ancestorRemoved(AncestorEvent event) {
              }

              public void ancestorMoved(AncestorEvent event) {
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "component.addAncestorListener(new AncestorListener {\r\n      public void ances...";
        }
      });
    }
    return component;
  }

  public static <A extends JComponent> A focus(final A a) {
    if (a != null)
      swingLater(new Runnable() {

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

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

  public static void focusAndSelectAll(final JTextComponent tf) {
    focus(tf);
    selectAll(tf);
  }

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

  public static 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...";
        }
      });
    }
  }

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

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

  public static 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 __878 = holdInstance(instanceToHold);
          try {
            callF(runnable);
          } finally {
            _close(__878);
          }
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

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

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

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

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

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

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

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

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

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

  public static boolean isURL(String s) {
    return startsWithOneOf(s, "http://", "https://", "file:");
  }

  public static File imageSnippetsCacheDir() {
    return javaxCachesDir("Image-Snippets");
  }

  public static String snippetImageURL_noHttps(String snippetID) {
    return snippetImageURL_noHttps(snippetID, "png");
  }

  public static 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/");
  }

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

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

  public static byte[] loadBinaryPage(String url) {
    try {
      print("Loading " + url);
      return loadBinaryPage(loadPage_openConnection(new URL(url)));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  public static byte[] saveBinaryFile(File fileName, byte[] contents) {
    return saveBinaryFile(fileName.getPath(), contents);
  }

  public static File getGlobalCache() {
    File file = new File(javaxCachesDir(), "Binary Snippets");
    file.mkdirs();
    return file;
  }

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

  public static <B, A extends B> A addAndReturn(Collection<B> c, A a) {
    if (c != null)
      c.add(a);
    return a;
  }

  public static void loadBinaryPageToFile(String url, File file) {
    try {
      print("Loading " + url);
      loadBinaryPageToFile(openConnection(new URL(url)), file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static void loadBinaryPageToFile(URLConnection con, File file) {
    try {
      setHeaders(con);
      loadBinaryPageToFile_noHeaders(con, file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  public static URLConnection openConnection(URL url) {
    try {
      ping();
      callOpt(javax(), "recordOpenURLConnection", str(url));
      return url.openConnection();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  public static String firstJavaToken(String s) {
    if (s == null)
      return null;
    int l = s.length();
    int j = 0;
    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 (j >= l)
      return null;
    int i = j;
    c = s.charAt(i);
    d = i + 1 >= l ? '\0' : s.charAt(i + 1);
    if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        if (s.charAt(j) == opener || s.charAt(j) == '\n') {
          ++j;
          break;
        } else if (s.charAt(j) == '\\' && j + 1 < l)
          j += 2;
        else
          ++j;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
    else if (Character.isDigit(c)) {
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      if (j < l && s.charAt(j) == 'L')
        ++j;
    } else if (c == '[' && d == '[') {
      do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
      j = Math.min(j + 2, l);
    } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
      do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
      j = Math.min(j + 3, l);
    } else
      ++j;
    return quickSubstring(s, i, j);
  }

  public static <A> TreeSet<A> treeSet() {
    return new TreeSet();
  }

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

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

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

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

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

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

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

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

  public static int javaTok_n, javaTok_elements;

  public static boolean javaTok_opt;

  public static 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)) || "'".indexOf(s.charAt(j)) >= 0));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else if (c == '[' && d == '[') {
        do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
        j = Math.min(j + 2, l);
      } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
        do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
        j = Math.min(j + 3, l);
      } else
        ++j;
      tok.add(javaTok_substringC(s, i, j));
      ++n;
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    javaTok_elements += tok.size();
    return tok;
  }

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

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

  public static <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;
  }

  public static <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;
  }

  public static String trimJoin(List<String> s) {
    return trim(join(s));
  }

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

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

  public static String takeLast(int n, String s) {
    return substring(s, l(s) - n);
  }

  public static String takeLast(String s, int n) {
    return substring(s, l(s) - n);
  }

  public static BufferedImage imageIO_readURL(String url) {
    try {
      if (startsWith(url, "https:"))
        disableCertificateValidation();
      return ImageIO.read(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static boolean isAbsolutePath(String s) {
    return s != null && new File(s).isAbsolute();
  }

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

  public static String snippetImageURL_http(String snippetID) {
    return snippetImageURL_http(snippetID, "png");
  }

  public static String snippetImageURL_http(String snippetID, String contentType) {
    return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
  }

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

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

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

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

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

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

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

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

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

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

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

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

  public static <A> IterableIterator<A> iteratorFromFunction_f0(final F0<A> f) {
    class IFF2 extends IterableIterator<A> {

      public A a;

      public boolean done;

      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;
      }
    }
    ;
    return new IFF2();
  }

  public static List<String> javaTokNPunctuation(String s) {
    List<String> tok = javaTok(s);
    for (int i = 1; i < l(tok); i += 2) {
      int j = i;
      String t;
      while (j < l(tok) && l(t = tok.get(j)) == 1 && !Character.isLetterOrDigit(t.charAt(0))) j += 2;
      if (j > i)
        replaceSubList(tok, i - 1, j, ll(joinSubList(tok, i - 1, j)));
    }
    return tok;
  }

  public static <A> IterableIterator<A> notNulls_iterator(Iterator<A> it) {
    return filterIterator(it, new F1<A, Boolean>() {

      public Boolean get(A a) {
        try {
          return a != null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "a != null";
      }
    });
  }

  public static IterableIterator mapIterator(Object f, Iterator i) {
    return mapI(f, i);
  }

  public static IterableIterator mapIterator(Iterator i, Object f) {
    return mapI(i, f);
  }

  public static IterableIterator mapIterator(Iterable i, Object f) {
    return mapI(iterator(i), f);
  }

  public static IterableIterator mapIterator(Object f, Iterable i) {
    return mapI(iterator(i), f);
  }

  public static IterableIterator mapIterator(IterableIterator i, Object f) {
    return mapIterator((Iterator) i, f);
  }

  public static IterableIterator mapIterator(Object f, IterableIterator i) {
    return mapIterator((Iterator) i, f);
  }

  public static IterableIterator<Pair<List<String>, List<String>>> allTokSplits_nOnLeft_iterator(final List<String> tok) {
    return mapIterator(countIterator_exclusive_step(3, l(tok) - 1, 2), new F1<Integer, Object>() {

      public Object get(Integer i) {
        try {
          return pair(subList(tok, 0, i), subList(tok, i));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pair(subList(tok, 0, i), subList(tok, i))";
      }
    });
  }

  public static List<String> simpleSpaces(List<String> tok) {
    tok = cloneList(tok);
    for (int i = 0; i < l(tok); i += 2) tok.set(i, tok.get(i).equals("") ? "" : " ");
    return tok;
  }

  public static String simpleSpaces(String s) {
    return join(simpleSpaces(nlTok(s)));
  }

  public static IterableIterator<Pair<List<String>, List<String>>> allTokSplits_nOnRight_iterator(final List<String> tok) {
    return mapIterator(countIterator_exclusive_step(2, l(tok) - 2, 2), new F1<Integer, Object>() {

      public Object get(Integer i) {
        try {
          return pair(subList(tok, 0, i), subList(tok, i));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pair(subList(tok, 0, i), subList(tok, i))";
      }
    });
  }

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

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

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

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

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

  public static <A extends JComponent> A setFont(final Font font, final A a) {
    if (a != null) {
      swing(new Runnable() {

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

        public String toString() {
          return "a.setFont(font);";
        }
      });
    }
    return a;
  }

  public static <A extends JComponent> A setFont(A a, Font font) {
    return setFont(font, a);
  }

  public static <A extends JComponent> A setFont(final String fontID, float fontSize, final A a) {
    return setFont(loadFont_cached(fontID, fontSize), a);
  }

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

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

  public static <A extends JTextComponent> A moveCaretToEnd(A ta) {
    setCaretPosition(ta, textAreaTextLength(ta));
    return ta;
  }

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

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

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

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

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

  public static void selectAll(final JTextComponent tf) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            tf.selectAll();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "tf.selectAll();";
        }
      });
    }
  }

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

      public Object 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...";
      }
    });
  }

  public static int withLeftMargin_defaultWidth = 6;

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

  public static 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...";
      }
    });
  }

  public static ThreadLocal<List<Object>> holdInstance_l = new ThreadLocal();

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

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

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

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

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

  public static String standardTimeZone_name = "Europe/Berlin";

  public static String standardTimeZone() {
    return standardTimeZone_name;
  }

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

  public static String snippetImageURL(String snippetID) {
    return snippetImageURL(snippetID, "png");
  }

  public static 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;
  }

  public static int loadPage_defaultTimeout = 60000;

  public static ThreadLocal<String> loadPage_charset = new ThreadLocal();

  public static boolean loadPage_allowGzip = true, loadPage_debug;

  public static boolean loadPage_anonymous;

  public static int loadPage_verboseness = 100000;

  public static int loadPage_retries = 1;

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

  public static volatile int loadPage_forcedTimeout;

  public static ThreadLocal<Integer> loadPage_forcedTimeout_byThread = new ThreadLocal();

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

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

  public static String loadPage_preprocess(String url) {
    if (url.startsWith("tb/"))
      url = tb_mainServer() + "/" + url;
    if (url.indexOf("://") < 0)
      url = "http://" + url;
    return url;
  }

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

  public static String loadPage(URL url) {
    return loadPage(url.toExternalForm());
  }

  public static String loadPage(URLConnection con, URL url) throws IOException {
    return loadPage(con, url, true);
  }

  public static 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;
      }
      StringBuilder buf = new StringBuilder();
      int n = 0;
      while (true) {
        int ch = r.read();
        if (ch < 0)
          break;
        buf.append((char) ch);
        ++n;
        if ((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();
    }
  }

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

  public static 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;
  }

  public static 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) {
      }
  }

  public static <A> A println(A a) {
    return print(a);
  }

  public static File mkdirsFor(File file) {
    return mkdirsForFile(file);
  }

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

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

  public static String quickSubstring(String s, int i, int j) {
    if (i == j)
      return "";
    return s.substring(i, j);
  }

  public static List<String> tok_combineRoundCurlySquareBrackets_keep(List<String> tok) {
    List<String> l = new ArrayList();
    for (int i = 0; i < l(tok); i++) {
      String t = tok.get(i);
      if (odd(i) && eqOneOf(t, "{", "(", "[")) {
        int j = findEndOfBracketPart2(tok, i);
        l.add(joinSubList(tok, i, j));
        i = j - 1;
      } else
        l.add(t);
    }
    return l;
  }

  public static String javaTok_substringN(String s, int i, int j) {
    if (i == j)
      return "";
    if (j == i + 1 && s.charAt(i) == ' ')
      return " ";
    return s.substring(i, j);
  }

  public static String javaTok_substringC(String s, int i, int j) {
    return s.substring(i, j);
  }

  public static 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;
  }

  public static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
    return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
  }

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

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

  public static volatile boolean disableCertificateValidation_attempted;

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

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

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

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

  public static 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;
  }

  public static 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;
  }

  public static List<String> replaceSubList(List<String> l, List<String> x, List<String> y) {
    return replaceSublist(l, x, y);
  }

  public static <A> List<A> replaceSubList(List<A> l, int fromIndex, int toIndex, List<A> y) {
    return replaceSublist(l, fromIndex, toIndex, y);
  }

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

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

  public static <A> IterableIterator<A> filterIterator(final Iterator<A> it, final F1<A, Boolean> f) {
    if (it == null)
      return null;
    return iff(new F0<Object>() {

      public Object get() {
        try {
          while (it.hasNext()) {
            A a = it.next();
            if (callF(f, a))
              return a;
          }
          return endMarker();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "while (it.hasNext()) {\r\n      A a = it.next();\r\n      if (callF(f, a))\r\n     ...";
      }
    });
  }

  public static <A> IterableIterator<A> filterIterator(final F1<A, Boolean> f, final Iterator<A> it) {
    return filterIterator(it, f);
  }

  public static class mapI_It extends IterableIterator {

    public Object f;

    public Iterator i;

    public mapI_It() {
    }

    public mapI_It(Object f, Iterator i) {
      this.i = i;
      this.f = f;
    }

    public boolean hasNext() {
      return i.hasNext();
    }

    public Object next() {
      return callF(f, i.next());
    }

    public String toString() {
      return formatFunctionCall("mapI", f, i);
    }
  }

  public static IterableIterator mapI(final Object f, final Iterator i) {
    return new mapI_It(f, i);
  }

  public static IterableIterator mapI(IterableIterator i, Object f) {
    return mapI((Iterator) i, f);
  }

  public static IterableIterator mapI(Object f, IterableIterator i) {
    return mapI((Iterator) i, f);
  }

  public static IterableIterator mapI(Iterator i, Object f) {
    return mapI(f, i);
  }

  public static <A, B> IterableIterator<B> mapI(Iterable<A> i, IF1<A, B> f) {
    return mapI(i, (Object) f);
  }

  public static IterableIterator mapI(Iterable i, Object f) {
    return mapI(f, i.iterator());
  }

  public static IterableIterator mapI(Object f, Iterable i) {
    return mapI(i, f);
  }

  public static IterableIterator<Integer> countIterator_exclusive_step(final int a, final int b, final int step) {
    return new IterableIterator<Integer>() {

      public int i = a;

      public boolean hasNext() {
        return i < b;
      }

      public Integer next() {
        i += step;
        return i - step;
      }
    };
  }

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

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

  public static <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;
  }

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

  public static <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;
  }

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

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

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

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

  public static Map<String, Font> loadFont_cached_cache = new HashMap();

  public static synchronized Font loadFont_cached(String snippetID) {
    try {
      snippetID = formatSnippetID(snippetID);
      Font f = loadFont_cached_cache.get(snippetID);
      if (f == null)
        loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f));
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static synchronized Font loadFont_cached(String snippetID, float size) {
    try {
      return loadFont_cached(snippetID).deriveFont(size);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

  public static 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...";
        }
      });
    }
  }

  public static int textAreaTextLength(JTextComponent ta) {
    return l(getText(ta));
  }

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

  public static 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...";
      }
    });
  }

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

  public static <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;
  }

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

  public static <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;
  }

  public static String imageServerLink(String md5OrID) {
    if (possibleMD5(md5OrID))
      return "https://botcompany.de/images/md5/" + md5OrID;
    return imageServerLink(parseSnippetID(md5OrID));
  }

  public static String imageServerLink(long id) {
    return "https://botcompany.de/images/" + id;
  }

  public static boolean networkAllowanceTest(String url) {
    return isAllowed("networkAllowanceTest", url);
  }

  public static final boolean loadPageThroughProxy_enabled = false;

  public static String loadPageThroughProxy(String url) {
    return null;
  }

  public static void sleepSeconds(double s) {
    if (s > 0)
      sleep(round(s * 1000));
  }

  public static <A> A printWithTime(A a) {
    print(hmsWithColons() + ": " + a);
    return a;
  }

  public static 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;
    }
  }

  public static InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
    UnknownHostException lastException = null;
    for (int _repeat_572 = 0; _repeat_572 < 2; _repeat_572++) {
      try {
        return con.getInputStream();
      } catch (UnknownHostException e) {
        lastException = e;
        print("Retrying because of: " + e);
        continue;
      }
    }
    throw lastException;
  }

  public static String toHex(byte[] bytes) {
    return bytesToHex(bytes);
  }

  public static String toHex(byte[] bytes, int ofs, int len) {
    return bytesToHex(bytes, ofs, len);
  }

  public static byte[] utf8(String s) {
    return toUtf8(s);
  }

  public static Matcher regexpMatcher(String pat, String s) {
    return compileRegexp(pat).matcher(unnull(s));
  }

  public static 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;
  }

  public static 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;
  }

  public static String getComputerID_quick() {
    return computerID();
  }

  public static int roundDownTo(int x, int n) {
    return x / n * n;
  }

  public static long roundDownTo(long x, long n) {
    return x / n * n;
  }

  public static int findEndOfBracketPart2(List<String> cnc, int i) {
    int j = i + 2, level = 1;
    while (j < cnc.size()) {
      if (eqOneOf(cnc.get(j), "{", "(", "["))
        ++level;
      else if (eqOneOf(cnc.get(j), "}", ")", "]"))
        --level;
      if (level == 0)
        return j + 1;
      ++j;
    }
    return cnc.size();
  }

  public static <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;
      removeSubList(l, i, i + l(x));
      l.addAll(i, y);
      i += l(y);
    }
    return l;
  }

  public static <A> List<A> replaceSublist(List<A> l, int fromIndex, int toIndex, List<A> y) {
    removeSubList(l, fromIndex, toIndex);
    l.addAll(fromIndex, y);
    return l;
  }

  public static <A> IterableIterator<A> iff(Object f) {
    return iteratorFromFunction_withEndMarker(f);
  }

  public static <A> IterableIterator<A> iff(F0 f) {
    return iteratorFromFunction_withEndMarker(f);
  }

  public static Object endMarker() {
    return iteratorFromFunction_endMarker;
  }

  public static String formatFunctionCall(String fname, Object... args) {
    return fname + "(" + joinWithComma(allToString(args)) + ")";
  }

  public static 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;
    }
  }

  public static Font loadFont(String snippetID) {
    try {
      return loadFont(snippetID, 12f);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static Font loadFont(InputStream in) {
    try {
      return Font.createFont(Font.TRUETYPE_FONT, in);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static Font loadFont(String snippetID, float fontSize) {
    return loadFont(loadLibrary(snippetID), fontSize);
  }

  public static Font loadFont(File f, float fontSize) {
    try {
      return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static Font loadFont(InputStream in, float fontSize) {
    try {
      return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  public static 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();";
      }
    });
  }

  public static 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();";
      }
    });
  }

  public static 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();";
      }
    });
  }

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

  public static 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;
  }

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

  public static <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;
  }

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

  public static void onChange(JSpinner spinner, Object r) {
    spinner.addChangeListener(changeListener(r));
  }

  public static <A extends AbstractButton> A onChange(A b, Object r) {
    b.addItemListener(itemListener(r));
    return b;
  }

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

  public static void onChange(final JSlider 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));";
        }
      });
    }
  }

  public static void 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)";
        }
      });
  }

  public static <A> A popLast(List<A> l) {
    return liftLast(l);
  }

  public static boolean possibleMD5(String s) {
    return isMD5(s);
  }

  public static volatile Object isAllowed_function;

  public static volatile boolean isAllowed_all = true;

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

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

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

  public static String hmsWithColons(long time) {
    return new SimpleDateFormat("HH:mm:ss").format(time);
  }

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

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

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

  public static Map<String, java.util.regex.Pattern> compileRegexp_cache = syncMRUCache(10);

  public static 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;
  }

  public static String _computerID;

  public static Lock computerID_lock = lock();

  public static String computerID() {
    if (_computerID == null) {
      Lock __870 = computerID_lock;
      lock(__870);
      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(__870);
      }
    }
    return _computerID;
  }

  public static Object iteratorFromFunction_endMarker = new Object();

  public static <A> IterableIterator<A> iteratorFromFunction_withEndMarker(final Object f) {
    class IFF extends IterableIterator<A> {

      public A a;

      public boolean done;

      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 = (A) callF(f);
        if (a == iteratorFromFunction_endMarker)
          done = true;
      }
    }
    ;
    return new IFF();
  }

  public static <A> IterableIterator<A> iteratorFromFunction_withEndMarker(final F0 f) {
    return iteratorFromFunction_withEndMarker_f0(f);
  }

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

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

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

  public static 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();";
      }
    });
  }

  public static <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;
  }

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

  public static 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;
  }

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

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

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

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

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

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

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

  public static 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;
  }

  public static <A> A liftLast(List<A> l) {
    if (l.isEmpty())
      return null;
    int i = l(l) - 1;
    A a = l.get(i);
    l.remove(i);
    return a;
  }

  public static boolean isMD5(String s) {
    return l(s) == 32 && isLowerHexString(s);
  }

  public static <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;
  }

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

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

  public static <A> IterableIterator<A> iteratorFromFunction_withEndMarker_f0(final F0<A> f) {
    class IFF2 extends IterableIterator<A> {

      public A a;

      public boolean have, done;

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

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

      public void getNext() {
        if (done || have)
          return;
        a = f.get();
        have = true;
        if (a == iteratorFromFunction_endMarker)
          done = true;
      }
    }
    ;
    return new IFF2();
  }

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

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

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

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

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

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

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

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

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

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

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

  public static 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;
  }

  public static boolean jmenuItem_newThreads;

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

  public static 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...";
      }
    });
  }

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

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

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

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

  public static 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;
  }

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

  public static 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 __2271 = holdInstance(instanceToHold);
                try {
                  callF(runnable);
                } finally {
                  _close(__2271);
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

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

  public static interface IAttractor {

    public boolean matches(String s);
  }

  public static class SimpleLiveValue<A> extends LiveValue<A> {

    public Class<A> type;

    public volatile A value;

    public transient 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();
      }
    }
  }

  public static class LineBuffer {

    public VF1<String> onLine;

    public StringBuilder currentLine = new StringBuilder();

    public LineBuffer() {
    }

    public LineBuffer(VF1<String> onLine) {
      this.onLine = onLine;
    }

    public void append(String s) {
      append(s, onLine);
    }

    public void append(String s, VF1<String> onLine) {
      currentLine.append(s);
      if (contains(s, '\n')) {
        int i = 0, j;
        s = str(currentLine);
        while ((j = indexOf(s, i, '\n')) >= 0) {
          String line = dropTrailingBackslashR(substring(s, i, j));
          callF(onLine, line);
          i = j + 1;
        }
        currentLine = new StringBuilder(substring(s, i));
      }
    }

    public int size() {
      return l(currentLine);
    }
  }

  public static interface IF1<A, B> {

    public B get(A a);
  }

  public abstract static class LiveValue<A> {

    public abstract Class<A> getType();

    public abstract A get();

    public abstract void onChange(Runnable l);

    public abstract void removeOnChangeListener(Runnable l);

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }
  }

  public static class RightAlignedLine extends JPanel {

    public RightAlignedLine(Component... components) {
      setLayout(LetterLayout.rightAlignedRow());
      for (Component component : components) add(component);
    }

    public void add(String text) {
      add(new JLabel(text));
    }
  }

  public static class MechListDependentCaches<A> {

    public Map<String, MechListDependentCache<A>> byList = ciMap();

    public Object maker;

    public transient Lock lock = lock();

    public MechListDependentCaches(Object maker) {
      this.maker = maker;
    }

    public A get(String name) {
      MechListDependentCache<A> listCache;
      {
        Lock __235 = lock;
        lock(__235);
        try {
          listCache = byList.get(name);
          if (listCache == null)
            byList.put(name, listCache = new MechListDependentCache(name, maker));
        } finally {
          unlock(__235);
        }
      }
      return listCache.get();
    }
  }

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

  public static 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 __238 = lock;
        lock(__238);
        try {
          if (!eqOrSame(listContents, lastListContents))
            clear();
          lastListContents = listContents;
        } finally {
          unlock(__238);
        }
      }
      return super.get();
    }
  }

  public static class LetterLayout implements LayoutManager {

    public String[] lines;

    public Map<String, Component> map = new TreeMap<String, Component>();

    public RC[] rows;

    public RC[] cols;

    public Cell[][] cells;

    public int spacingX = 10, spacingY = 10;

    public int insetTop, insetBottom, insetLeft, insetRight;

    public int template;

    public boolean formWideLeftSide, formWideRightSide;

    public static final int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5;

    public boolean debug;

    public void setLeftBorder(int border) {
      insetLeft = border;
    }

    public void setRightBorder(int border) {
      insetRight = border;
    }

    public static JComponent withBorder(JComponent component, int border) {
      JPanel panel = new JPanel(new LetterLayout("C").setBorder(border));
      panel.add("C", component);
      return panel;
    }

    public static JPanel panel(String... lines) {
      return new JPanel(new LetterLayout(lines));
    }

    public static JPanel stalactitePanel() {
      return new JPanel(stalactite());
    }

    public static class DummyComponent extends JComponent {
    }

    public static class Cell {

      public boolean aux;

      public int minWidth, minHeight;

      public Component component;

      public int colspan, rowspan;

      public double weightX, weightY;
    }

    public static class RC {

      public int min;

      public double weightSum;

      public int start;

      public int minEnd;
    }

    public LetterLayout(int template) {
      this.template = template;
    }

    public LetterLayout(String... lines) {
      this.lines = lines;
    }

    public void removeLayoutComponent(Component component) {
      map.values().remove(component);
    }

    public void layoutContainer(Container container) {
      prepareLayout(container);
      if (debug)
        System.out.println("Container size: " + container.getSize());
      Insets insets = getInsets(container);
      for (int r = 0; r < rows.length; r++) {
        for (int i = 0; i < cols.length; ) {
          Cell cell = cells[i][r];
          if (cell.aux)
            ++i;
          else {
            if (cell.component != null) {
              int x1 = cols[i].start;
              int y1 = rows[r].start;
              int x2 = i + cell.colspan < cols.length ? cols[i + cell.colspan].start - spacingX : container.getWidth() - insets.right;
              int y2 = r + cell.rowspan < rows.length ? rows[r + cell.rowspan].start - spacingY : container.getHeight() - insets.bottom;
              if (debug)
                System.out.println("Layouting (" + i + ", " + r + ", " + cell.component.getClass().getName() + "): " + x1 + " " + y1 + " " + x2 + " " + y2);
              cell.component.setBounds(x1, y1, x2 - x1, y2 - y1);
            }
            i += cells[i][r].colspan;
          }
        }
      }
    }

    public final void prepareLayout(Container container) {
      applyTemplate(container);
      int numRows = lines.length, numCols = lines[0].length();
      for (int i = 1; i < numRows; i++) if (lines[i].length() != numCols)
        throw new IllegalArgumentException("Lines have varying length");
      cells = new Cell[numCols][numRows];
      rows = new RC[numRows];
      cols = new RC[numCols];
      for (int r = 0; r < numRows; r++) rows[r] = new RC();
      for (int i = 0; i < numCols; i++) cols[i] = new RC();
      for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r] = new Cell();
      for (int r = 0; r < numRows; r++) {
        String line = lines[r];
        for (int i = 0; i < numCols; ) {
          Cell cell = cells[i][r];
          if (cell.aux) {
            ++i;
            continue;
          }
          char ch = line.charAt(i);
          int iNext = i;
          do ++iNext; while (iNext < numCols && ch == line.charAt(iNext));
          int rNext = r;
          do ++rNext; while (rNext < numRows && ch == lines[rNext].charAt(i));
          cell.weightX = numCols == 1 || iNext > i + 1 ? 1.0 : 0.0;
          cell.weightY = numRows == 1 || rNext > r + 1 ? 1.0 : 0.0;
          Component c = map.get(String.valueOf(ch));
          cell.component = c;
          if (c != null) {
            cell.minWidth = c.getMinimumSize().width + spacingX;
            cell.minHeight = getMinimumHeight(c) + spacingY;
          }
          cell.colspan = iNext - i;
          cell.rowspan = rNext - r;
          if (cell.colspan == 1)
            cols[i].min = Math.max(cols[i].min, cell.minWidth);
          if (cell.rowspan == 1)
            rows[r].min = Math.max(rows[r].min, cell.minHeight);
          for (int r2 = r; r2 < rNext; r2++) for (int i2 = i; i2 < iNext; i2++) if (r2 != r || i2 != i)
            cells[i2][r2].aux = true;
          i = iNext;
        }
      }
      while (true) {
        for (int i = 0; i < numCols; i++) {
          int minStart = i == 0 ? 0 : cols[i - 1].minEnd;
          double weightStart = i == 0 ? 0.0 : cols[i - 1].weightSum;
          for (int r = 0; r < numRows; r++) {
            Cell cell = cells[i][r];
            if (!cell.aux) {
              RC rc = cols[i + cell.colspan - 1];
              rc.minEnd = Math.max(rc.minEnd, minStart + cell.minWidth);
              rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightX);
            }
          }
        }
        for (int r = 0; r < numRows; r++) {
          int minStart = r == 0 ? 0 : rows[r - 1].minEnd;
          double weightStart = r == 0 ? 0.0 : rows[r - 1].weightSum;
          for (int i = 0; i < numCols; i++) {
            Cell cell = cells[i][r];
            if (!cell.aux) {
              RC rc = rows[r + cell.rowspan - 1];
              rc.minEnd = Math.max(rc.minEnd, minStart + cell.minHeight);
              rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightY);
            }
          }
        }
        if (allWeightsZero(cols)) {
          for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightX = 1.0;
          continue;
        }
        if (allWeightsZero(rows)) {
          for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightY = 1.0;
          continue;
        }
        break;
      }
      Insets insets = getInsets(container);
      determineStarts(cols, insets.left, container.getWidth() - insets.left - insets.right + spacingX, spacingX);
      determineStarts(rows, insets.top, container.getHeight() - insets.top - insets.bottom + spacingY, spacingY);
    }

    public final boolean allWeightsZero(RC[] rcs) {
      for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0)
        return false;
      return true;
    }

    public static int getMinimumHeight(Component c) {
      return c.getMinimumSize().height;
    }

    public final void applyTemplate(Container container) {
      if (template == STALACTITE) {
        Component[] components = container.getComponents();
        lines = new String[components.length + 2];
        map.clear();
        for (int i = 0; i < components.length; i++) {
          String s = String.valueOf(makeIndexChar(i));
          map.put(s, components[i]);
          lines[i] = s;
        }
        lines[components.length] = lines[components.length + 1] = " ";
      } else if (template == FORM) {
        Component[] components = container.getComponents();
        int numRows = components.length / 2;
        lines = new String[numRows + 2];
        map.clear();
        for (int row = 0; row < numRows; row++) {
          String lower = String.valueOf(makeIndexChar(row));
          String upper = String.valueOf(makeAlternateIndexChar(row));
          Component rightComponent = components[row * 2 + 1];
          if (rightComponent instanceof DummyComponent)
            upper = lower;
          lines[row] = (formWideLeftSide ? lower + lower : lower) + (formWideRightSide ? upper + upper : upper);
          map.put(lower, components[row * 2]);
          if (!(rightComponent instanceof DummyComponent))
            map.put(upper, rightComponent);
        }
        lines[numRows] = lines[numRows + 1] = (formWideLeftSide ? "  " : " ") + (formWideRightSide ? "  " : " ");
      } else if (template == LEFT_ALIGNED_ROW) {
        lines = new String[] { makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
      } else if (template == CENTERED_ROW) {
        lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
      } else if (template == RIGHT_ALIGNED_ROW) {
        lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) };
      }
    }

    public final String makeSingleRow(Container container) {
      Component[] components = container.getComponents();
      StringBuffer buf = new StringBuffer();
      map.clear();
      for (int i = 0; i < components.length; i++) {
        String s = String.valueOf(makeAlternateIndexChar(i));
        map.put(s, components[i]);
        buf.append(s);
      }
      return buf.toString();
    }

    public static void determineStarts(RC[] rcs, int start, int totalSize, int spacing) {
      int minTotal = rcs[rcs.length - 1].minEnd;
      double weightSum = rcs[rcs.length - 1].weightSum;
      int spare = (int) ((totalSize - minTotal) / (weightSum == 0.0 ? 1.0 : weightSum));
      int x = start, minSum = 0;
      double prevWeightSum = 0.0;
      for (int i = 0; i < rcs.length; i++) {
        int width = rcs[i].minEnd - minSum + (int) ((rcs[i].weightSum - prevWeightSum) * spare) - spacing;
        rcs[i].start = x;
        x += width + spacing;
        prevWeightSum = rcs[i].weightSum;
        minSum = rcs[i].minEnd;
      }
    }

    public void addLayoutComponent(String s, Component component) {
      map.put(s, component);
    }

    public Dimension minimumLayoutSize(Container container) {
      prepareLayout(container);
      Insets insets = getInsets(container);
      Dimension result = new Dimension(insets.left + cols[cols.length - 1].minEnd + insets.right - spacingX, insets.top + rows[rows.length - 1].minEnd + insets.bottom - spacingY);
      return result;
    }

    public final Insets getInsets(Container container) {
      Insets insets = container.getInsets();
      return new Insets(insets.top + insetTop, insets.left + insetLeft, insets.bottom + insetBottom, insets.right + insetRight);
    }

    public Dimension preferredLayoutSize(Container container) {
      return minimumLayoutSize(container);
    }

    public LetterLayout setSpacing(int x, int y) {
      spacingX = x;
      spacingY = y;
      return this;
    }

    public LetterLayout setSpacing(int spacing) {
      return setSpacing(spacing, spacing);
    }

    public LetterLayout setBorder(int top, int left, int bottom, int right) {
      insetTop = top;
      insetLeft = left;
      insetBottom = bottom;
      insetRight = right;
      return this;
    }

    public LetterLayout setBorder(int inset) {
      return setBorder(inset, inset, inset, inset);
    }

    public LetterLayout setTopBorder(int inset) {
      insetTop = inset;
      return this;
    }

    public static LetterLayout stalactite() {
      return new LetterLayout(STALACTITE);
    }

    public static LetterLayout leftAlignedRow() {
      return new LetterLayout(LEFT_ALIGNED_ROW);
    }

    public static LetterLayout leftAlignedRow(int spacing) {
      return leftAlignedRow().setSpacing(spacing);
    }

    public static LetterLayout centeredRow() {
      return new LetterLayout(CENTERED_ROW);
    }

    public static LetterLayout rightAlignedRow() {
      return new LetterLayout(RIGHT_ALIGNED_ROW);
    }

    public static JPanel rightAlignedRowPanel(JComponent... components) {
      return makePanel(new LetterLayout(RIGHT_ALIGNED_ROW), components);
    }

    public static JPanel makePanel(LetterLayout letterLayout, JComponent[] components) {
      JPanel panel = new JPanel(letterLayout);
      for (JComponent component : components) {
        panel.add(component);
      }
      return panel;
    }

    public static LetterLayout form() {
      LetterLayout letterLayout = new LetterLayout(FORM);
      letterLayout.formWideLeftSide = true;
      letterLayout.formWideRightSide = true;
      return letterLayout;
    }

    public static LetterLayout formWideRightSide() {
      LetterLayout letterLayout = new LetterLayout(FORM);
      letterLayout.formWideRightSide = true;
      return letterLayout;
    }

    public static Component getDummyComponent() {
      return new DummyComponent();
    }

    public static JPanel newPanel(String... lines) {
      return new JPanel(new LetterLayout(lines));
    }

    public boolean isDebug() {
      return debug;
    }

    public void setDebug(boolean debug) {
      this.debug = debug;
    }

    public static char makeIndexChar(int idx) {
      return (char) ('a' + idx * 2);
    }

    public static char makeAlternateIndexChar(int idx) {
      return (char) ('b' + idx * 2);
    }

    public static char LEFT_CHAR = ',', RIGHT_CHAR = '.';

    public static void main(String[] args) {
      System.out.println((int) makeIndexChar(0));
      System.out.println((int) makeAlternateIndexChar(0));
      System.out.println((int) makeIndexChar(32000));
      System.out.println((int) makeAlternateIndexChar(32000));
      System.out.println((int) LEFT_CHAR);
      System.out.println((int) RIGHT_CHAR);
    }
  }

  public static class Cache<A> {

    public Object maker;

    public A value;

    public long loaded;

    public static boolean debug;

    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 __1613 = lock;
      lock(__1613);
      try {
        if (loaded == 0) {
          value = make();
          changeCount++;
          loaded = sysNow();
        }
        return value;
      } finally {
        unlock(__1613);
      }
    }

    public void clear() {
      Lock __1614 = lock;
      lock(__1614);
      try {
        if (debug && loaded != 0)
          print("Clearing cache");
        value = null;
        changeCount++;
        loaded = 0;
      } finally {
        unlock(__1614);
      }
    }

    public void clear(double seconds) {
      Lock __1615 = lock;
      lock(__1615);
      try {
        if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000)
          clear();
      } finally {
        unlock(__1615);
      }
    }

    public void set(A a) {
      Lock __1616 = lock;
      lock(__1616);
      try {
        value = a;
        ++changeCount;
        loaded = sysNow();
      } finally {
        unlock(__1616);
      }
    }

    public A make() {
      return (A) callF(maker);
    }
  }

  public static String standard_toString(Object o) {
    if (o == null)
      return "null";
    String name = shortClassName(o);
    Set<String> fields = fieldNames(o);
    if (empty(fields))
      return name;
    return name + "(" + joinWithComma(mapNonNulls(fields, field -> {
      Object value = get(o, field);
      if (value == null)
        return null;
      return field + "=" + str(value);
    })) + ")";
  }

  public static <A> F1<A, Boolean> f1_true() {
    return f1_const(true);
  }

  public static boolean matchX2(String pat, String s) {
    return matchX_vbar(pat, s);
  }

  public static boolean matchX2(String pat, String s, Matches matches) {
    return matchX_vbar(pat, s, matches);
  }

  public static String dropTrailingBackslashR(String s) {
    int i = l(s);
    while (i > 0 && s.charAt(i - 1) == '\r') --i;
    return substring(s, 0, i);
  }

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

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

  public static boolean hasLock(Lock lock) {
    return ((ReentrantLock) lock).isHeldByCurrentThread();
  }

  public static String mL_raw(String name) {
    return mechList_raw(name);
  }

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

  public static void clear(Collection c) {
    if (c != null)
      c.clear();
  }

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

  public static String shortClassName(Object o) {
    if (o == null)
      return null;
    Class c = o instanceof Class ? (Class) o : o.getClass();
    String name = c.getName();
    return shortenClassName(name);
  }

  public static Set<String> fieldNames(Object o) {
    return allFields(o);
  }

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

  public static List mapNonNulls(Object f, Iterable l) {
    List x = new ArrayList();
    if (l != null)
      for (Object o : l) addIfNotNull(x, callF(f, o));
    return x;
  }

  public static List mapNonNulls(Object f, Object[] l) {
    List x = new ArrayList();
    if (l != null)
      for (Object o : l) addIfNotNull(x, callF(f, o));
    return x;
  }

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

  public static <A, B> List<B> mapNonNulls(F1<A, B> f, Iterable<A> l) {
    List x = new ArrayList();
    if (l != null)
      for (Object o : l) addIfNotNull(x, callF(f, o));
    return x;
  }

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

  public static <A, B> F1<A, B> f1_const(final B b) {
    return new F1<A, B>() {

      public B get(A a) {
        return b;
      }
    };
  }

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

  public static boolean matchX_vbar(String pat, String s, Matches matches) {
    for (String pat2 : tok_splitAtVerticalBar(pat)) if (matchX(pat2, s, matches))
      return true;
    return false;
  }

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

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

  public static Lock mechList_raw_lock = lock();

  public static int mechList_raw_timeout = 60000;

  public static String mechList_raw(String name) {
    try {
      Lock __79 = mechList_raw_lock;
      lock(__79);
      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(__79);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

  public static String shortenClassName(String name) {
    if (name == null)
      return null;
    int i = lastIndexOf(name, "$");
    if (i < 0)
      i = lastIndexOf(name, ".");
    return i < 0 ? name : substring(name, i + 1);
  }

  public static Set<String> allFields(Object o) {
    TreeSet<String> fields = new TreeSet();
    Class _c = _getClass(o);
    do {
      for (Field f : _c.getDeclaredFields()) fields.add(f.getName());
      _c = _c.getSuperclass();
    } while (_c != null);
    return fields;
  }

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

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

  public static boolean matchX(String pat, String s, Matches m) {
    if (endsWith(pat, "..."))
      return matchStartX(pat, s, m);
    if (startsWith(pat, "..."))
      return matchEndX(pat, s, m);
    return match(pat, s, m);
  }

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

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

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

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

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

  public static boolean matchStartX(String pat, String s, Matches matches) {
    return matchStart(dropSuffix("...", pat), s, matches);
  }

  public static boolean matchEndX(String pat, String s, Matches matches) {
    return matchEnd(dropPrefix("...", pat), s, matches);
  }

  public static 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;
  }

  public static MechMode mechMode_value = new MechMode();

  public static MechMode mechMode() {
    return mechMode_value;
  }

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

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

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

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

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

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

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

  public static boolean serverMechList_raw_fresh_verbose;

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

  public static String serverMechList_raw_fresh(String name, boolean opt) {
    Lock __327 = downloadLock();
    lock(__327);
    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(__327);
    }
  }

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

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

  public static String md5(String text) {
    try {
      if (text == null)
        return "-";
      return bytesToHex(md5_impl(toUtf8(text)));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  public static MessageDigest md5_md;

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

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

  public static String fileNameEncode_safeChars = " ()[]#,!";

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

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

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

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

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

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

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

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

  public static <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;
  }

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

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

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

  public static boolean md5OfFile_verbose;

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

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

  public static String fromUtf8(byte[] bytes) {
    try {
      return bytes == null ? null : new String(bytes, "UTF-8");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static 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;
  }

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

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

  public static boolean jsonDecode_useOrderedMaps = true;

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

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

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

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

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

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

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

  public static String doPost(String urlParameters, URLConnection conn, URL url) {
    try {
      boolean silently = isTrue(optParam(doPost_silently));
      Long timeout = optParam(doPost_timeout);
      setHeaders(conn);
      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);
    }
  }

  public static 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;
  }

  public static 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;
  }

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

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

  public static 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;
    }

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

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

    public synchronized 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;
    }

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

    public synchronized Set<Map.Entry<A, B>> entrySet() {
      clean();
      return synchronizedSet(mapValues("pairB", byKey).entrySet());
    }

    public synchronized Set<A> keySet() {
      clean();
      return synchronizedSet(byKey.keySet());
    }

    public synchronized int size() {
      clean();
      return byKey.size();
    }

    public void setStandardExpiryTime(long ms) {
      standardExpiryTime = ms;
    }

    public synchronized ExpiringMap2<A, B> setMap(Map innerMap) {
      byKey = innerMap;
      return this;
    }
  }

  public abstract static class VF2<A, B> {

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

  public static class MechMode {

    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 = h * 2 + _hashCode(readMode);
      h = h * 2 + _hashCode(writeMode);
      return h;
    }
  }

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

  public static long sysTime() {
    return sysNow();
  }

  public static <A, B> void put(Map<A, B> map, A a, B b) {
    if (map != null)
      map.put(a, b);
  }

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

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

  public static <A> Set<A> synchronizedSet(Set<A> set) {
    return Collections.synchronizedSet(set);
  }

  public static 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;
  }

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

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

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

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