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.l;
import static x30_pkg.x30_util.empty;
import static x30_pkg.x30_util.nempty;
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.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
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 loadableUtils.utils;
import static loadableUtils.utils.print_byThread;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import net.sourceforge.lame.lowlevel.*;
import javax.sound.sampled.*;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import java.awt.datatransfer.StringSelection;

public class main {

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

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

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

  public static <A> A call(Object o, String method, Object... args) {
    return x30_util.call(o, method, args);
  }

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

  public static void wavToMP3_128k(File wav, File mp3) {
    javaLame_wavToMP3_mono(wav, mp3);
  }

  public static boolean _moduleClass_WitAILastRecording;

  public static class WitAILastRecording extends DynPrintLog {

    public boolean sendUnrecognized;

    public void start() {
      super.start();
      dm_onNewRecordingOrWAVOnClipboard(new VF1<File>() {

        public void get(File f) {
          try {
            print("Analyzing " + f.getName());
            final String text = witAI_recognizeWAV(f);
            {
              swing(new Runnable() {

                public void run() {
                  try {
                    String info = "wit.ai english";
                    if (empty(text)) {
                      print("Didn't recognize any text");
                      if (sendUnrecognized)
                        katze_userSaid(info, "?");
                    } else {
                      String corrected = dm_correctRecognizedSpeech(text);
                      if (neq(corrected, text)) {
                        print("Correcting " + quote(text) + " to " + quote(corrected));
                        vmBus_send("correctedRecognizedSpeech", text, corrected);
                      } else
                        print("Recognized: " + text);
                      if (!dm_osInForeground())
                        flatInfoBox(corrected);
                      print("Recognized: " + corrected);
                      dm_setAIBarTextAndFireWithInfo(corrected, info);
                    }
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "String info = \"wit.ai english\";\r\n        if (empty(text)) {\r\n          print(...";
                }
              });
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "print(\"Analyzing \" + f.getName());\r\n      fS text = witAI_recognizeWAV(f);\r\n ...";
        }
      });
    }
  }

  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 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 = print_byThread == null ? null : print_byThread.get();
    if (f == null)
      f = print_allThreads;
    if (f != null)
      if (isFalse(callF(f, s)))
        return;
    print_raw(s);
  }

  public static void print_raw(String 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 RuntimeException rethrow(Throwable t) {
    if (t instanceof Error)
      _handleError((Error) t);
    throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
  }

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

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

  public static List<String> _stickyLibs_javaLame_wavToMP3_mono = ll("#1400149");

  public static void javaLame_wavToMP3_mono(File wav, File mp3) {
    try {
      long time = sysNow();
      WAVDecoder decoder = new WAVDecoder(newFileInputStream(wav));
      try {
        long _startTime_9 = sysNow();
        byte[] pcm = byteArrayFromShorts_littleEndian(decodeWAVToMonoSamples(decoder, wav));
        done2_always("Decode WAV", _startTime_9);
        LameEncoder encoder = new LameEncoder(javaSound_pcmSignedLittleEndianMono(decoder.sampleRate));
        FileOutputStream out = new FileOutputStream(mp3);
        try {
          byte[] buffer = new byte[encoder.getPCMBufferSize()];
          int bytesToTransfer = min(l(buffer), l(pcm)), bytesWritten;
          int currentPcmPosition = 0;
          while (0 < (bytesWritten = encoder.encodeBuffer(pcm, currentPcmPosition, bytesToTransfer, buffer))) {
            currentPcmPosition += bytesToTransfer;
            bytesToTransfer = min(l(buffer), l(pcm) - currentPcmPosition);
            out.write(buffer, 0, bytesWritten);
          }
          encoder.close();
          done2_always_timeFirst(time, "Pure-Java-converted " + wav + " to " + mp3);
        } finally {
          _close(out);
        }
      } finally {
        _close(decoder);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static void dm_onNewRecordingOrWAVOnClipboard(final VF1<File> onFile) {
    dm_ownResource(vmBus_onMessage("newRecording", onFile));
    dm_ownResource(vmBus_onMessage("newClipboardContents", new VF1<Object>() {

      public void get(Object o) {
        try {
          if (o instanceof String && ewic((String) o, ".wav")) {
            File f = newFile((String) o);
            if (isAbsolutePath(f) && f.exists())
              callF(onFile, f);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "if (o instanceof S && ewic((S) o, \".wav\")) {\r\n      File f = newFile((S) o);\r...";
      }
    }));
  }

  public static Lock witAI_conversionLock = lock();

  public static String witAI_recognizeWAV(File wavFile) {
    return witAI_recognizeWAV(wavFile, "english");
  }

  public static String witAI_recognizeWAV(File wavFile, String language) {
    File mp3 = replaceExtension(wavFile, "mp3");
    {
      Lock __7 = witAI_conversionLock;
      lock(__7);
      try {
        if (!mp3.exists())
          javaLame_wavToMP3_mono(wavFile, mp3);
      } finally {
        unlock(__7);
      }
    }
    return witAI_recognizeMP3(mp3, language);
  }

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

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

  public static void katze_userSaid(String info, String s) {
    logQuoted(speechRecognitionLog(), now() + " [" + info + "] " + s);
  }

  public static String dm_correctRecognizedSpeech(String s) {
    return or((String) dm_findAndCallModule("#1020219/CorrectRecognizedSpeech", "getAutoCorrection", s), s);
  }

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

  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 void vmBus_send(String msg, Object... args) {
    Object arg = empty(args) ? null : l(args) == 1 ? args[0] : 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 boolean dm_osInForeground() {
    return isInForeground(dm_desktopPane());
  }

  public static boolean flatInfoBox_alwaysOnTop = true;

  public static double flatInfoBox_defaultTime = 2.0;

  public static int flatInfoBox_x = 28, flatInfoBox_y = 5;

  public static JWindow flatInfoBox(String text) {
    return flatInfoBox(text, flatInfoBox_defaultTime);
  }

  public static JWindow flatInfoBox(final String text, final double seconds) {
    if (empty(text))
      return null;
    print(text);
    return flatInfoBox_noprint(text, seconds);
  }

  public static JWindow flatInfoBox_noprint(String text) {
    return flatInfoBox_noprint(text, flatInfoBox_defaultTime);
  }

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

      public Object get() {
        try {
          final JWindow window = makeUnimportantWindow(flatInfoBox_makePanel(text));
          window.pack();
          window.setBounds(flatInfoBox_x, flatInfoBox_y, 300, window.getHeight());
          if (flatInfoBox_alwaysOnTop)
            window.setAlwaysOnTop(true);
          window.setVisible(true);
          disposeWindowAfter(iround(seconds * 1000), window);
          return window;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "final JWindow window = makeUnimportantWindow(flatInfoBox_makePanel(text));\r\n ...";
      }
    });
  }

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

  public static void dm_setAIBarTextAndFireWithInfo(String text, String info) {
    AutoCloseable __17 = dm_generalMap_tempPut("topInputInfo", info);
    try {
      dm_setAIBarTextAndFire(text);
    } finally {
      _close(__17);
    }
  }

  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 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 void _handleError(Error e) {
    call(javax(), "_handleError", e);
  }

  public static Class __javax;

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

  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 long sysNow() {
    ping();
    return System.nanoTime() / 1000000;
  }

  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 byte[] byteArrayFromShorts_littleEndian(short[] a) {
    return byteArrayFromShorts_littleEndian(a, 0, l(a));
  }

  public static byte[] byteArrayFromShorts_littleEndian(short[] a, int from, int to) {
    byte[] b = new byte[(to - from) * 2];
    for (int i = 0; i < a.length; i++) {
      short s = a[from + i];
      b[i * 2] = (byte) s;
      b[i * 2 + 1] = (byte) (s >> 8);
    }
    return b;
  }

  public static short[] decodeWAVToMonoSamples(File wavFile) {
    try {
      WAVDecoder decoder = new WAVDecoder(newFileInputStream(wavFile));
      try {
        return decodeWAVToMonoSamples(decoder, wavFile);
      } finally {
        _close(decoder);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static short[] decodeWAVToMonoSamples(WAVDecoder decoder, File wavFile) {
    try {
      List<short[]> chunks = new ArrayList();
      while (licensed()) {
        short[] buf = new short[4096];
        int n = decoder.readMonoSamples(buf);
        if (n <= 0)
          break;
        chunks.add(subArray(buf, 0, n));
      }
      return concatShortArrays(chunks);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

  public static AudioFormat javaSound_pcmSignedLittleEndianMono(float sampleRate) {
    return new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleRate, 16, 1, 2, 44100f, false);
  }

  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 long done2_always_timeFirst(long startTime, String desc) {
    long time = sysNow() - startTime;
    print(time + " ms: " + desc);
    return time;
  }

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

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

  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 AutoCloseable dm_ownResource(AutoCloseable resource) {
    dm_currentModuleMandatory().ownResource(resource);
    return resource;
  }

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

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

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

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

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

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

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

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

  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 boolean isAbsolutePath(String s) {
    return s != null && new File(s).isAbsolute();
  }

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

  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 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 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 String witAI_recognizeMP3(File mp3File) {
    return witAI_recognizeAudio(mp3File, "audio/mpeg3");
  }

  public static String witAI_recognizeMP3(File mp3File, String language) {
    return witAI_recognizeAudio(mp3File, "audio/mpeg3", language);
  }

  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 void logQuoted(String logFile, String line) {
    logQuoted(getProgramFile(logFile), line);
  }

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

  public static File speechRecognitionLog() {
    return new File(javaxDataDir(), "Speech Recognition/recognized.txt");
  }

  public static long now_virtualTime;

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

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

  public static <A> A dm_findAndCallModule(String moduleLibID, String method, Object... args) {
    return dm_callModule(dm_findModule(moduleLibID), method, args);
  }

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

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

  public static boolean isInForeground(Component c) {
    JFrame f = getFrame(c);
    return f != null && (f.isFocused() || f.isAlwaysOnTop());
  }

  public static JDesktopPane dm_desktopPane() {
    return dm_getOSOpt("desktop");
  }

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

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

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

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

  public static JWindow makeUnimportantWindow(final Component c) {
    return swing(new F0<JWindow>() {

      public JWindow get() {
        try {
          Map map = (Map) (vm_generalMap_get("unimportant windows"));
          if (map == null)
            vm_generalMap_put("unimportant windows", map = callJavaX("newWeakHashMap"));
          JWindow w = makeWindow(c);
          map.put(w, true);
          return w;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Map map = (Map) ( vm_generalMap_get(\"unimportant windows\"));\r\n    if (map == null...";
      }
    });
  }

  public static JLabel flatInfoBox_makePanel(String text) {
    return jlabel(text);
  }

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

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

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

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

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

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

  public static void showConsole() {
    callOpt(get(javax(), "console"), "showConsole");
  }

  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 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 AutoCloseable dm_generalMap_tempPut(final Object key, Object value) {
    final Object oldValue = ((Map) dm_getOSOpt("generalMap")).put(key, value);
    return new AutoCloseable() {

      public String toString() {
        return "mapPutOrRemove((Map) dm_getOSOpt(\"generalMap\"), key, oldValue);";
      }

      public void close() throws Exception {
        mapPutOrRemove((Map) dm_getOSOpt("generalMap"), key, oldValue);
      }
    };
  }

  public static void dm_setAIBarTextAndFire(String s) {
    dm_setAIBarText(s);
    JTextField tc = (JTextField) (dm_getOS("tfTopInput"));
    simulateEnter(tc);
  }

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

  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 int[] subArray(int[] b, int start, int end) {
    int[] x = new int[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  public static byte[] subArray(byte[] b, int start, int end) {
    start = max(start, 0);
    end = min(end, l(b));
    if (start >= end)
      return new byte[0];
    byte[] x = new byte[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  public static short[] subArray(short[] b, int start, int end) {
    if (start <= 0 && end >= l(b))
      return b;
    short[] x = new short[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  public static float[] subArray(float[] b, int start, int end) {
    float[] x = new float[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  public static Object[] subArray(Object[] b, int start) {
    return subArray(b, start, l(b));
  }

  public static Object[] subArray(Object[] b, int start, int end) {
    start = max(start, 0);
    end = min(end, l(b));
    if (start >= end)
      return new Object[0];
    Object[] x = new Object[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  public static short[] concatShortArrays(List<short[]> arrays) {
    int l = 0;
    for (short[] a : unnull(arrays)) l += l(a);
    short[] x = new short[l];
    int i = 0;
    for (short[] a : unnull(arrays)) if (a != null) {
      System.arraycopy(a, 0, x, i, l(a));
      i += l(a);
    }
    return x;
  }

  public static DynModule dm_currentModuleMandatory() {
    return dm_current_mandatory();
  }

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

  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 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(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 <A> A second(List<A> l) {
    return get(l, 1);
  }

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

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

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

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

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

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

      public String toString() {
        return "r.run()";
      }
    };
  }

  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 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 ReentrantLock fairLock() {
    return new ReentrantLock(true);
  }

  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 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 String witAI_recognizeAudio(File audioFile, String mimeType) {
    return witAI_recognizeAudio(audioFile, mimeType, "english");
  }

  public static String witAI_recognizeAudio(File audioFile, String mimeType, String language) {
    try {
      if (audioFile.length() == 0)
        throw fail("No file: " + audioFile);
      print("Calling wit.ai with " + toK(audioFile.length()) + " K " + mimeType + "...");
      long time = sysNow();
      String token = witAITokenForLanguage(language);
      URL url = new URL("https://api.wit.ai/speech?v=20160526");
      URLConnection con = url.openConnection();
      con.setRequestProperty("Authorization", "Bearer " + token);
      con.setRequestProperty("Content-Type", mimeType);
      con.setDoOutput(true);
      OutputStream out = con.getOutputStream();
      file2stream(audioFile, out);
      out.flush();
      String json = loadPage(con, url);
      out.close();
      done2_always("wit.ai", time);
      return getString(jsonDecodeMap(json), "_text");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 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 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 Lock appendToFile_lock = lock();

  public static boolean appendToFile_keepOpen;

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

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

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

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

  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 <A> A dm_callModule(Object moduleOrID, String method, Object... args) {
    Object mod = dm_getModule(moduleOrID);
    if (mod == null)
      return null;
    AutoCloseable __533 = dm_enter(mod);
    try {
      return call(mod, method, args);
    } finally {
      _close(__533);
    }
  }

  public static String dm_findModule(String moduleLibID) {
    return (String) callCreator("findModuleByLibID", moduleLibID);
  }

  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 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 Set vm_generalIdentityHashSet(Object name) {
    synchronized (get(javax(), "generalMap")) {
      Set set = (Set) (vm_generalMap_get(name));
      if (set == null)
        vm_generalMap_put(name, set = syncIdentityHashSet());
      return set;
    }
  }

  public static Map vm_generalHashMap(Object name) {
    synchronized (get(javax(), "generalMap")) {
      Map m = (Map) (vm_generalMap_get(name));
      if (m == null)
        vm_generalMap_put(name, m = syncHashMap());
      return m;
    }
  }

  public static JFrame getFrame(final Object _o) {
    return swing(new F0<JFrame>() {

      public JFrame get() {
        try {
          Object o = _o;
          if (o instanceof ButtonGroup)
            o = first(buttonsInGroup((ButtonGroup) o));
          if (!(o instanceof Component))
            return null;
          Component c = (Component) o;
          while (c != null) {
            if (c instanceof JFrame)
              return (JFrame) c;
            c = c.getParent();
          }
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "O o = _o;\r\n    if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button...";
      }
    });
  }

  public static <A> A dm_getOSOpt(String field) {
    return (A) getOpt(dm_os(), field);
  }

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

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

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

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

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

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

  public static <A> A callJavaX(String method, Object... args) {
    return (A) callOpt(getJavaX(), method, args);
  }

  public static JWindow makeWindow(final Component c) {
    return swing(new F0<JWindow>() {

      public JWindow get() {
        try {
          JWindow w = new JWindow();
          w.add(wrap(c));
          return w;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "new JWindow w;\r\n    w.add(wrap(c));\r\n    ret w;";
      }
    });
  }

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

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

  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 int toMS_int(double seconds) {
    return toInt_checked((long) (seconds * 1000));
  }

  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 Object callOpt(Object o) {
    return callF(o);
  }

  public static <A> A callOpt(Object o, String method, Object... args) {
    return (A) callOpt_cached(o, method, args);
  }

  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 volatile PersistableThrowable lastException_lastException;

  public static PersistableThrowable lastException() {
    return lastException_lastException;
  }

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

  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 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 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 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 <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 String dm_setAIBarText(String s) {
    setText((JTextComponent) dm_getOS("tfTopInput"), s);
    return s;
  }

  public static <A> A dm_getOS(String field) {
    return (A) get(dm_os(), field);
  }

  public static void simulateEnter(final JTextField tf) {
    if (tf != null) {
      swing(new Runnable() {

        public void run() {
          try {
            for (ActionListener a : tf.getActionListeners()) a.actionPerformed(new ActionEvent(tf, ActionEvent.ACTION_PERFORMED, null));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "for (ActionListener a : tf.getActionListeners())\r\n      a.actionPerformed(new...";
        }
      });
    }
  }

  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 void failIfUnlicensed() {
    assertTrue("license off", licensed());
  }

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

  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 <A> Set<A> synchronizedSet() {
    return synchroHashSet();
  }

  public static <A> Set<A> synchronizedSet(Set<A> set) {
    return Collections.synchronizedSet(set);
  }

  public static <A> Set<A> identityHashSet() {
    return Collections.newSetFromMap(new IdentityHashMap());
  }

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

  public static Object _get(Object o, String field) {
    return get(o, field);
  }

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

  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 substring(String s, int x) {
    return substring(s, x, l(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 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 addPrefixIfNotEmpty2(String prefix, String s) {
    return empty(s) ? "" : addPrefix(prefix, s);
  }

  public static long toK(long l) {
    return (l + 1023) / 1024;
  }

  public static String witAITokenForLanguage(String language) {
    return eqic(language, "german") ? witAIGermanToken() : witAIToken();
  }

  public static void file2stream(File src, OutputStream out) throws IOException {
    FileInputStream inputStream = new FileInputStream(src);
    try {
      copyStream(inputStream, out);
    } finally {
      inputStream.close();
    }
  }

  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 = con.getInputStream();
      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 String getString(Map map, Object key) {
    return map == null ? null : (String) map.get(key);
  }

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

  public static String getString(Object o, Object key) {
    if (o instanceof Map)
      return getString((Map) o, key);
    if (key instanceof String)
      return (String) getOpt(o, (String) key);
    throw fail("Not a string key: " + getClassName(key));
  }

  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 Runnable asRunnable(Object o) {
    return toRunnable(o);
  }

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

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

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

  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 String getCanonicalPath(String path) {
    try {
      return new File(path).getCanonicalPath();
    } 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 AutoCloseable tempCleaningUp() {
    return tempSetTL(ping_isCleanUpThread, true);
  }

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

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

  public static String _userHome;

  public static String userHome() {
    if (_userHome == null) {
      if (isAndroid())
        _userHome = "/storage/sdcard0/";
      else
        _userHome = System.getProperty("user.home");
    }
    return _userHome;
  }

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

  public static Object dm_getModule(Object moduleOrID) {
    if (eq(moduleOrID, ""))
      return null;
    if (isStringOrIntOrLong(moduleOrID))
      return dm_callOS("getDynModuleByID", str(moduleOrID));
    return moduleOrID;
  }

  public static AutoCloseable dm_enter(Object mod) {
    return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
  }

  public static <A> A callCreator(String functionName, Object... args) {
    return (A) call(creator(), functionName, args);
  }

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

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

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

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

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

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

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

  public static List<AbstractButton> buttonsInGroup(ButtonGroup g) {
    if (g == null)
      return ll();
    return asList(g.getElements());
  }

  public static Object dm_os() {
    return creator();
  }

  public static File standardLogFile() {
    return getProgramFile("log");
  }

  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 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 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 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 __160 = holdInstance(instanceToHold);
          try {
            callF(runnable);
          } finally {
            _close(__160);
          }
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

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

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

  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 PersistableThrowable persistableThrowable(Throwable e) {
    return e == null ? null : new PersistableThrowable(e);
  }

  public static Throwable getException(Runnable r) {
    try {
      callF(r);
      return null;
    } catch (Throwable e) {
      return 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 <A> ArrayList<A> emptyList(Class<A> c) {
    return new ArrayList();
  }

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

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

  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 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 <A> Set<A> synchroHashSet() {
    return Collections.synchronizedSet(new HashSet<A>());
  }

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

  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 String witAIGermanToken() {
    File f = javaxSecretDir("wit-ai-german-token.txt");
    if (empty(f))
      saveTextFile(f, mL_raw("wit.ai German client token"));
    return assertNempty("wit.ai german token", trim(loadTextFile(f)));
  }

  public static String witAIToken() {
    File f = javaxSecretDir("wit-ai-english-token.txt");
    if (empty(f))
      saveTextFile(f, mL_raw("wit.ai English client token"));
    return assertNempty("wit.ai token", trim(loadTextFile(f)));
  }

  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 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 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 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 <A> A printWithTime(A a) {
    print(hmsWithColons() + ": " + a);
    return a;
  }

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

  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, 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 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 GZIPInputStream newGZIPInputStream(File f) {
    return gzInputStream(f);
  }

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

  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 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 openConnection(URL url) {
    try {
      ping();
      callOpt(javax(), "recordOpenURLConnection", str(url));
      return url.openConnection();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  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 <A> List<A> concatLists(Collection<A>... lists) {
    List<A> l = new ArrayList();
    for (Collection<A> list : lists) if (list != null)
      l.addAll(list);
    return l;
  }

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

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

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

  public static boolean isStringOrIntOrLong(Object o) {
    return o instanceof String || o instanceof Integer || o instanceof Long;
  }

  public static <A> A dm_callOS(String functionName, Object... args) {
    return (A) call(dm_os(), functionName, args);
  }

  public static WeakReference<Object> creator_class;

  public static Object creator() {
    return creator_class == null ? null : creator_class.get();
  }

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

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

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

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

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

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

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

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

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

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

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

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

  public static <A extends Component> A _recordNewSwingComponent(A c) {
    if (c != null)
      callF(vm_generalMap_get("newSwingComponentRegistry"), 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 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 int parseInt(String s) {
    return empty(s) ? 0 : Integer.parseInt(s);
  }

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

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

  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 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 String mL_raw(String name) {
    return mechList_raw(name);
  }

  public static <A> A assertNempty(A a) {
    return assertNempty("empty", a);
  }

  public static <A> A assertNempty(String msg, A a) {
    if (empty(a))
      throw fail(msg + ": " + a);
    return a;
  }

  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 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 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 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 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 String getComputerID_quick() {
    return computerID();
  }

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

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

  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 boolean startsWith(String a, String b) {
    return a != null && a.startsWith(b);
  }

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

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

  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 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 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 <A> String join(String glue, Iterable<A> strings) {
    if (strings == null)
      return "";
    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 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 <A> AutoCloseable tempSetThreadLocal(final ThreadLocal<A> tl, A a) {
    final A prev = setThreadLocal(tl, a);
    return new AutoCloseable() {

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

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

  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 Throwable innerException(Throwable e) {
    return getInnerException(e);
  }

  public static Field getOpt_findField(Class<?> c, String field) {
    Class _c = c;
    do {
      for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
        return f;
      _c = _c.getSuperclass();
    } while (_c != null);
    return null;
  }

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

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

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

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

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

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

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

  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 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 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 __52 = mechList_raw_lock;
      lock(__52);
      try {
        if (empty(name))
          return "";
        String src = mechList_raw_cache.get(name);
        if (src != null)
          return src;
        AutoCloseable __53 = tempSetThreadLocal(loadPage_forcedTimeout_byThread, mechList_raw_timeout);
        try {
          src = mechList_raw_fresh(name);
          if (src != null)
            mechList_raw_cache.put(name, src);
          return src;
        } finally {
          _close(__53);
        }
      } finally {
        unlock(__52);
      }
    } 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 ThreadLocal<VF1<File>> checkFileNotTooBigToRead_tl = new ThreadLocal();

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

  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 String _computerID;

  public static Lock computerID_lock = lock();

  public static String computerID() {
    if (_computerID == null) {
      Lock __833 = computerID_lock;
      lock(__833);
      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(__833);
      }
    }
    return _computerID;
  }

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

  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 <A, B> Map<A, B> syncMRUCache(int size) {
    return synchroMap(new MRUCache(size));
  }

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

  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 <A> A popLast(List<A> l) {
    return liftLast(l);
  }

  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 boolean startsWithIgnoreCase(String a, String b) {
    return regionMatchesIC(a, 0, b, 0, b.length());
  }

  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 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 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 <A> TreeMap<String, A> ciMap() {
    return caseInsensitiveMap();
  }

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

  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> 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 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 File computerIDFile() {
    return javaxDataDir("Basic Info/computer-id.txt");
  }

  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 <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;
    startIndex = Math.max(0, startIndex);
    endIndex = Math.min(l(l), endIndex);
    if (startIndex >= endIndex)
      return ll();
    return l.subList(startIndex, endIndex);
  }

  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> 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 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 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 <A> TreeMap<String, A> caseInsensitiveMap() {
    return new TreeMap(caseInsensitiveComparator());
  }

  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 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 Random defaultRandomGenerator() {
    return ThreadLocalRandom.current();
  }

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

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

  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 __122 = downloadLock();
    lock(__122);
    try {
      if (serverMechList_raw_fresh_verbose)
        print("serverMechList_raw_fresh " + name);
      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);
      if (serverMechList_raw_fresh_verbose)
        print("Mech list " + name + ": " + (appended ? "appended" : same ? "same" : "downloaded"));
      saveTextFile(remoteMechListMirrorMetaFile(name), struct(getMultipleKeys(map, "Name", "Status")));
      if (same)
        return text;
      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);
      }
      vmBus_send("remoteMechListMirrorChanged", name);
      return text;
    } finally {
      unlock(__122);
    }
  }

  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 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 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 <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_791 = 0; _repeat_791 < n; _repeat_791++) {
      if (it.hasNext())
        l.add(it.next());
      else
        break;
    }
    return l;
  }

  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 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 fromUTF8(byte[] bytes) {
    return fromUtf8(bytes);
  }

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

  public static Lock downloadLock_lock = fairLock();

  public static Lock downloadLock() {
    return downloadLock_lock;
  }

  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 urlencode(String x) {
    try {
      return URLEncoder.encode(unnull(x), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

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

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

  public static String struct(Object o) {
    return structure(o);
  }

  public static String struct(Object o, structure_Data data) {
    return structure(o, data);
  }

  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 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 <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;
    startIndex = max(0, startIndex);
    endIndex = min(l(l), endIndex);
    if (startIndex >= endIndex)
      return ll();
    if (startIndex == 0 && endIndex == l(l))
      return l;
    return cloneList(l.subList(startIndex, endIndex));
  }

  public static String fromUtf8(byte[] bytes) {
    try {
      return 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 Object[] muricaCredentials() {
    String pass = muricaPassword();
    return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0];
  }

  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 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 boolean structure_showTiming, structure_checkTokenCount;

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

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

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

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

  public static boolean structure_allowShortening = false;

  public static class structure_Data {

    public PrintWriter out;

    public int stringSizeLimit;

    public int shareStringsLongerThan = 20;

    public boolean noStringSharing;

    public IdentityHashMap<Object, Integer> seen = new IdentityHashMap();

    public HashMap<String, Integer> strings = new HashMap();

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

    public HashMap<Class, List<Field>> fieldsByClass = new HashMap();

    public HashMap<Class, Field> persistenceInfo = new HashMap();

    public int n;

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

    public structure_Data append(String token) {
      out.print(token);
      ++n;
      return this;
    }

    public structure_Data append(int i) {
      out.print(i);
      ++n;
      return this;
    }

    public structure_Data append(String token, int tokCount) {
      out.print(token);
      n += tokCount;
      return this;
    }

    public structure_Data app(String token) {
      out.print(token);
      return this;
    }

    public structure_Data app(int i) {
      out.print(i);
      return this;
    }
  }

  public static void structure_1(final Object o, final structure_Data d) {
    try {
      if (o == null) {
        d.append("null");
        return;
      }
      Class c = o.getClass();
      boolean concept = false;
      List<Field> lFields = d.fieldsByClass.get(c);
      if (lFields == null) {
        if (o instanceof Number) {
          PrintWriter out = d.out;
          if (o instanceof Integer) {
            int i = ((Integer) o).intValue();
            out.print(i);
            d.n += i < 0 ? 2 : 1;
            return;
          }
          if (o instanceof Long) {
            long l = ((Long) o).longValue();
            out.print(l);
            out.print("L");
            d.n += l < 0 ? 2 : 1;
            return;
          }
          if (o instanceof Short) {
            short s = ((Short) o).shortValue();
            d.append("sh ", 2);
            out.print(s);
            d.n += s < 0 ? 2 : 1;
            return;
          }
          if (o instanceof Float) {
            d.append("fl ", 2);
            quoteToPrintWriter(str(o), out);
            return;
          }
          if (o instanceof Double) {
            d.append("d(", 3);
            quoteToPrintWriter(str(o), out);
            d.append(")");
            return;
          }
          if (o instanceof BigInteger) {
            out.print("bigint(");
            out.print(o);
            out.print(")");
            d.n += ((BigInteger) o).signum() < 0 ? 5 : 4;
            return;
          }
        }
        if (o instanceof Boolean) {
          d.append(((Boolean) o).booleanValue() ? "t" : "f");
          return;
        }
        if (o instanceof Character) {
          d.append(quoteCharacter((Character) o));
          return;
        }
        if (o instanceof File) {
          d.append("File ").append(quote(((File) o).getPath()));
          return;
        }
        Integer ref = d.seen.get(o);
        if (o instanceof String && ref == null)
          ref = d.strings.get((String) o);
        if (ref != null) {
          d.append("t").app(ref);
          return;
        }
        if (!(o instanceof String))
          d.seen.put(o, d.n);
        else {
          String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
          if (!d.noStringSharing) {
            if (d.shareStringsLongerThan == Integer.MAX_VALUE)
              d.seen.put(o, d.n);
            if (l(s) >= d.shareStringsLongerThan)
              d.strings.put(s, d.n);
          }
          quoteToPrintWriter(s, d.out);
          d.n++;
          return;
        }
        if (o instanceof HashSet) {
          d.append(o instanceof LinkedHashSet ? "lhs" : "hashset");
          structure_1(new ArrayList((Set) o), d);
          return;
        }
        if (o instanceof TreeSet) {
          d.append("treeset");
          structure_1(new ArrayList((Set) o), d);
          return;
        }
        String name = c.getName();
        if (o instanceof Collection && !startsWith(name, "main$")) {
          if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList"))
            d.append("sync");
          d.append("[");
          final int l = d.n;
          final Iterator it = ((Collection) o).iterator();
          d.stack.add(new Runnable() {

            public void run() {
              try {
                if (!it.hasNext())
                  d.append("]");
                else {
                  d.stack.add(this);
                  if (d.n != l)
                    d.append(", ");
                  structure_1(it.next(), d);
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "if (!it.hasNext())\r\n          d.append(\"]\");\r\n        else {\r\n          d.sta...";
            }
          });
          return;
        }
        if (o instanceof Map && !startsWith(name, "main$")) {
          if (o instanceof LinkedHashMap)
            d.append("lhm");
          else if (o instanceof HashMap)
            d.append("hm");
          else if (name.equals("java.util.Collections$SynchronizedMap"))
            d.append("sync");
          else if (name.equals("java.util.Collections$SynchronizedSortedMap")) {
            d.append("sync tm", 2);
          }
          d.append("{");
          final int l = d.n;
          final Iterator it = ((Map) o).entrySet().iterator();
          d.stack.add(new Runnable() {

            public boolean v;

            public Map.Entry e;

            public void run() {
              if (v) {
                d.append("=");
                v = false;
                d.stack.add(this);
                structure_1(e.getValue(), d);
              } else {
                if (!it.hasNext())
                  d.append("}");
                else {
                  e = (Map.Entry) it.next();
                  v = true;
                  d.stack.add(this);
                  if (d.n != l)
                    d.append(", ");
                  structure_1(e.getKey(), d);
                }
              }
            }
          });
          return;
        }
        if (c.isArray()) {
          if (o instanceof byte[]) {
            d.append("ba ").append(quote(bytesToHex((byte[]) o)));
            return;
          }
          final int n = Array.getLength(o);
          if (o instanceof boolean[]) {
            String hex = boolArrayToHex((boolean[]) o);
            int i = l(hex);
            while (i > 0 && hex.charAt(i - 1) == '0' && hex.charAt(i - 2) == '0') i -= 2;
            d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i)));
            return;
          }
          String atype = "array", sep = ", ";
          if (o instanceof int[]) {
            atype = "intarray";
            sep = " ";
          }
          d.append(atype).append("{");
          d.stack.add(new Runnable() {

            public int i;

            public void run() {
              if (i >= n)
                d.append("}");
              else {
                d.stack.add(this);
                if (i > 0)
                  d.append(", ");
                structure_1(Array.get(o, i++), d);
              }
            }
          });
          return;
        }
        if (o instanceof Class) {
          d.append("class(", 2).append(quote(((Class) o).getName())).append(")");
          return;
        }
        if (o instanceof Throwable) {
          d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")");
          return;
        }
        if (o instanceof BitSet) {
          BitSet bs = (BitSet) o;
          d.append("bitset{", 2);
          int l = d.n;
          for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
            if (d.n != l)
              d.append(", ");
            d.append(i);
          }
          d.append("}");
          return;
        }
        if (name.startsWith("java.") || name.startsWith("javax.")) {
          d.append("j ").append(quote(str(o)));
          return;
        }
        String dynName = shortDynamicClassName(o);
        if (concept && !d.concepts.contains(dynName)) {
          d.concepts.add(dynName);
          d.append("c ");
        }
        TreeSet<Field> fields = new TreeSet<Field>(new Comparator<Field>() {

          public int compare(Field a, Field b) {
            return stdcompare(a.getName(), b.getName());
          }
        });
        Class cc = c;
        while (cc != Object.class) {
          for (Field field : getDeclaredFields_cached(cc)) {
            String fieldName = field.getName();
            if (fieldName.equals("_persistenceInfo"))
              d.persistenceInfo.put(c, field);
            if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
              continue;
            fields.add(field);
          }
          cc = cc.getSuperclass();
        }
        lFields = asList(fields);
        for (int i = 0; i < l(lFields); i++) {
          Field f = lFields.get(i);
          if (f.getName().equals("this$1")) {
            lFields.remove(i);
            lFields.add(0, f);
            break;
          }
        }
        d.fieldsByClass.put(c, lFields);
      } else {
        Integer ref = d.seen.get(o);
        if (ref != null) {
          d.append("t").app(ref);
          return;
        }
        d.seen.put(o, d.n);
      }
      Field persistenceInfoField = (Field) (d.persistenceInfo.get(c));
      Map<String, Object> persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o);
      LinkedHashMap<String, Object> fv = new LinkedHashMap();
      for (Field f : lFields) {
        Object value;
        try {
          value = f.get(o);
        } catch (Exception e) {
          value = "?";
        }
        if (value != null && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
          fv.put(f.getName(), value);
      }
      String name = c.getName();
      String shortName = dropPrefix("main$", name);
      if (concept && eq(fv.get("className"), shortName))
        fv.remove("className");
      if (o instanceof DynamicObject) {
        fv.putAll((Map) fv.get("fieldValues"));
        fv.remove("fieldValues");
        shortName = shortDynamicClassName(o);
        fv.remove("className");
      }
      String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
      d.append(shortName);
      final int l = d.n;
      final Iterator it = fv.entrySet().iterator();
      d.stack.add(new Runnable() {

        public void run() {
          try {
            if (!it.hasNext()) {
              if (d.n != l)
                d.append(")");
            } else {
              Map.Entry e = (Map.Entry) it.next();
              d.append(d.n == l ? "(" : ", ");
              d.append((String) e.getKey()).append("=");
              d.stack.add(this);
              structure_1(e.getValue(), d);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (!it.hasNext()) {\r\n      if (d.n != l)\r\n        d.append(\")\");\r\n    } else...";
        }
      });
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 volatile boolean muricaPassword_pretendNotAuthed;

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

  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 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();
      loadPage_charset.set("UTF-8");
      String contents = loadPage(conn, url, false);
      writer.close();
      return contents;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  public static List<String> javaTokC(String s) {
    if (s == null)
      return null;
    int l = s.length();
    ArrayList<String> tok = new ArrayList();
    int i = 0;
    while (i < l) {
      int j = i;
      char c, d;
      while (j < l) {
        c = s.charAt(j);
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (c == '/' && d == '*') {
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
          j = Math.min(j + 2, l);
        } else if (c == '/' && d == '/') {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          if (s.charAt(j) == opener || s.charAt(j) == '\n') {
            ++j;
            break;
          } else if (s.charAt(j) == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else if (c == '[' && d == '[') {
        do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
        j = Math.min(j + 2, l);
      } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
        do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
        j = Math.min(j + 3, l);
      } else
        ++j;
      tok.add(javaTok_substringC(s, i, j));
      i = j;
    }
    return tok;
  }

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

  public static String quoteCharacter(char c) {
    if (c == '\'')
      return "'\\''";
    if (c == '\\')
      return "'\\\\'";
    if (c == '\r')
      return "'\\r'";
    if (c == '\n')
      return "'\\n'";
    if (c == '\t')
      return "'\\t'";
    return "'" + c + "'";
  }

  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 String boolArrayToHex(boolean[] a) {
    return bytesToHex(boolArrayToBytes(a));
  }

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

  public static String shortDynamicClassName(Object o) {
    if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
      return ((DynamicObject) o).className;
    return shortClassName(o);
  }

  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 Map<Class, Field[]> getDeclaredFields_cache = newDangerousWeakHashMap();

  public static Field[] getDeclaredFields_cached(Class c) {
    Field[] fields;
    synchronized (getDeclaredFields_cache) {
      fields = getDeclaredFields_cache.get(c);
      if (fields == null) {
        getDeclaredFields_cache.put(c, fields = c.getDeclaredFields());
        for (Field f : fields) f.setAccessible(true);
      }
    }
    return fields;
  }

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

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

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

  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) {
    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 <A> A optParam(Object[] opt, String name) {
    return optParam(opt, name, null);
  }

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

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

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

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

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

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

  public static String javaTok_substringC(String s, int i, int j) {
    return s.substring(i, j);
  }

  public static byte[] boolArrayToBytes(boolean[] a) {
    byte[] b = new byte[(l(a) + 7) / 8];
    for (int i = 0; i < l(a); i++) if (a[i])
      b[i / 8] |= 1 << (i & 7);
    return b;
  }

  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 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 <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 <A> A optPar(Object[] params, String name) {
    return optParam(params, name);
  }

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

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

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

  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 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 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()) {
          m.setAccessible(true);
          multiMapPut(cache, m.getName(), m);
        }
        _c = _c.getSuperclass();
      }
    }

    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 abstract static class VF1<A> {

    public abstract void get(A a);
  }

  public static class BetterLabel extends JLabel {

    public boolean autoToolTip = true;

    public BetterLabel() {
      final WeakReference<BetterLabel> me = new WeakReference(this);
      componentPopupMenu(this, BetterLabel_menuItems(me));
    }

    public BetterLabel(String text) {
      this();
      this.setText(text);
    }

    public void setText(String text) {
      super.setText(text);
      if (autoToolTip)
        if (!swic(text, "<html>"))
          setToolTipText(nullIfEmpty(text));
    }
  }

  public static VF1<JPopupMenu> BetterLabel_menuItems(final WeakReference<BetterLabel> me) {
    return new VF1<JPopupMenu>() {

      public void get(JPopupMenu menu) {
        try {
          addMenuItem(menu, "Copy text to clipboard", new Runnable() {

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

            public String toString() {
              return "copyTextToClipboard(me.get().getText());";
            }
          });
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n      copyTextToClipboard(me...";
      }
    };
  }

  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 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 ThreadLocal<Boolean> DynamicObject_loading = new ThreadLocal();

  public static class DynamicObject {

    public String className;

    public LinkedHashMap<String, Object> fieldValues = new LinkedHashMap();

    public DynamicObject() {
    }

    public DynamicObject(String className) {
      this.className = className;
    }
  }

  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 static class PersistableThrowable {

    public String className;

    public String msg;

    public String stacktrace;

    public PersistableThrowable() {
    }

    public PersistableThrowable(Throwable e) {
      if (e == null)
        className = "Crazy Null Error";
      else {
        className = getClassName(e).replace('/', '.');
        msg = e.getMessage();
        stacktrace = getStackTrace_noRecord(e);
      }
    }

    public String toString() {
      return nempty(msg) ? className + ": " + msg : className;
    }
  }

  public static class WAVDecoder implements AutoCloseable {

    public EndianDataInputStream in;

    public int channels;

    public float sampleRate;

    public boolean ignoreSampleRate = true;

    public boolean twentyFourBit;

    public int specifiedDataLength;

    public int remainingDataBytes;

    public WAVDecoder(InputStream stream) {
      try {
        in = new EndianDataInputStream(new BufferedInputStream(stream, 1024 * 1024));
        if (!in.read4ByteString().equals("RIFF"))
          throw new IllegalArgumentException("not a wav");
        in.readIntLittleEndian();
        if (!in.read4ByteString().equals("WAVE"))
          throw new IllegalArgumentException("expected WAVE tag");
        String s = in.read4ByteString();
        if (eq(s, "bext")) {
          in.skip(in.readIntLittleEndian());
          s = in.read4ByteString();
        }
        if (!s.equals("fmt "))
          throw new IllegalArgumentException("expected fmt tag, got: " + s);
        if (in.readIntLittleEndian() != 16)
          throw new IllegalArgumentException("expected wave chunk size to be 16");
        int format;
        if ((format = in.readShortLittleEndian()) != 1)
          throw new IllegalArgumentException("expected format to be 1, got: " + format);
        channels = in.readShortLittleEndian();
        sampleRate = in.readIntLittleEndian();
        if (sampleRate != 44100)
          if (ignoreSampleRate)
            print("Sample rate: " + sampleRate);
          else
            throw fail("Not 44100 sampling rate: " + sampleRate);
        in.readIntLittleEndian();
        in.readShortLittleEndian();
        int fmt = in.readShortLittleEndian();
        if (fmt == 24)
          twentyFourBit = true;
        else if (fmt != 16)
          throw fail("Only 16/24-bit samples supported: " + fmt);
        String tag;
        while (!(tag = in.read4ByteString()).equals("data")) {
          print("Skipping tag " + tag);
          int len = in.readIntLittleEndian();
          in.skip(len);
        }
        remainingDataBytes = specifiedDataLength = in.readIntLittleEndian();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public int readMonoSamples(short[] samples) {
      int readSamples = 0, n = samples.length;
      for (int i = 0; i < n && remainingDataBytes > 0; i++) {
        double sample = 0;
        try {
          for (int j = 0; j < channels; j++) sample += readSample();
          sample /= channels;
          samples[i] = (short) iround(max(-32768, min(32767, sample)));
          readSamples++;
        } catch (Exception ex) {
          break;
        }
      }
      return readSamples;
    }

    public int readStereoSamples(short[] samples) {
      int readSamples = 0, n = samples.length;
      for (int i = 0; i < n && remainingDataBytes > 0; i += 2) {
        double sample = 0;
        try {
          short left = readSample();
          short right;
          if (channels > 1)
            right = readSample();
          else
            right = left;
          samples[i] = left;
          samples[i + 1] = right;
          readSamples += 2;
        } catch (Exception ex) {
          break;
        }
      }
      return readSamples;
    }

    public short readSample() {
      try {
        if (twentyFourBit) {
          --remainingDataBytes;
          in.read();
        }
        remainingDataBytes -= 2;
        return in.readShortLittleEndian();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void close() {
      try {
        in.close();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }
  }

  public abstract static class F0<A> {

    public abstract A get();
  }

  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 class EndianDataInputStream extends DataInputStream {

    public EndianDataInputStream(InputStream in) {
      super(in);
    }

    public String read4ByteString() {
      try {
        byte[] bytes = new byte[4];
        readFully(bytes);
        return new String(bytes, "US-ASCII");
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public short readShortLittleEndian() {
      try {
        int result = readUnsignedByte();
        result |= readUnsignedByte() << 8;
        return (short) result;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public int readIntLittleEndian() {
      try {
        int result = readUnsignedByte();
        result |= readUnsignedByte() << 8;
        result |= readUnsignedByte() << 16;
        result |= readUnsignedByte() << 24;
        return result;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public int readInt24BitLittleEndian() {
      try {
        int result = readUnsignedByte();
        result |= readUnsignedByte() << 8;
        result |= readUnsignedByte() << 16;
        if ((result & (1 << 23)) == 8388608)
          result |= 0xff000000;
        return result;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public int readInt24Bit() {
      try {
        int result = readUnsignedByte() << 16;
        result |= readUnsignedByte() << 8;
        result |= readUnsignedByte();
        return result;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }
  }

  public static interface IVar<A> {

    public void set(A a);

    public A get();

    public boolean has();

    public void clear();
  }

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

  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 Method findMethod(Object o, String method, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        Method m = findMethod_static((Class) o, method, args, false);
        if (m == null)
          return null;
        m.setAccessible(true);
        return m;
      } else {
        Method m = findMethod_instance(o, method, args, false);
        if (m == null)
          return null;
        m.setAccessible(true);
        return m;
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static Method findMethod_static(Class c, String method, Object[] args, boolean debug) {
    Class _c = c;
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (debug)
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");
        ;
        if (!m.getName().equals(method)) {
          if (debug)
            System.out.println("Method name mismatch: " + method);
          continue;
        }
        if ((m.getModifiers() & Modifier.STATIC) == 0 || !findMethod_checkArgs(m, args, debug))
          continue;
        return m;
      }
      c = c.getSuperclass();
    }
    return null;
  }

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

  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)
        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 Map<JComponent, List> componentPopupMenu_map;

  public static ThreadLocal<MouseEvent> componentPopupMenu_mouseEvent;

  public static void componentPopupMenu_init() {
    {
      swing(new Runnable() {

        public void run() {
          try {
            if (componentPopupMenu_map == null)
              componentPopupMenu_map = or((Map<JComponent, List>) getOpt(creator(), "componentPopupMenu_map"), (Map<JComponent, List>) (Map) newWeakHashMap());
            if (componentPopupMenu_mouseEvent == null)
              componentPopupMenu_mouseEvent = or((ThreadLocal<MouseEvent>) getOpt(creator(), "componentPopupMenu_mouseEvent"), new ThreadLocal());
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (componentPopupMenu_map == null)\r\n      componentPopupMenu_map = or((Map<J...";
        }
      });
    }
  }

  public static void componentPopupMenu(final JComponent component, final Object menuMaker) {
    componentPopupMenu_init();
    if (component != null && menuMaker != null) {
      swing(new Runnable() {

        public void run() {
          try {
            List maker = componentPopupMenu_map.get(component);
            if (maker == null) {
              componentPopupMenu_map.put(component, maker = new ArrayList());
              if (!(component instanceof JInternalFrame))
                component.addMouseListener(new componentPopupMenu_Adapter(maker));
            }
            maker.add(menuMaker);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "List maker = componentPopupMenu_map.get(component);\r\n    if (maker == null) {...";
        }
      });
    }
  }

  public static class componentPopupMenu_Adapter extends MouseAdapter {

    public List maker;

    public componentPopupMenu_Adapter(List maker) {
      this.maker = maker;
    }

    public void mousePressed(MouseEvent e) {
      displayMenu(e);
    }

    public void mouseReleased(MouseEvent e) {
      displayMenu(e);
    }

    public void displayMenu(MouseEvent e) {
      if (e.isPopupTrigger())
        displayMenu2(e);
    }

    public void displayMenu2(MouseEvent e) {
      JPopupMenu menu = new JPopupMenu();
      int emptyCount = menu.getComponentCount();
      componentPopupMenu_mouseEvent.set(e);
      for (Object menuMaker : maker) pcallF(menuMaker, menu);
      if (menu.getComponentCount() != emptyCount)
        menu.show(e.getComponent(), e.getX(), e.getY());
    }
  }

  public static <A extends JComponent> A setToolTipText(final A c, final Object toolTip) {
    if (c == null)
      return null;
    {
      swing(new Runnable() {

        public void run() {
          try {
            String s = nullIfEmpty(str(toolTip));
            if (neq(s, c.getToolTipText()))
              c.setToolTipText(s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "String s = nullIfEmpty(str(toolTip));\r\n    if (neq(s, c.getToolTipText()))\r\n ...";
        }
      });
    }
    return c;
  }

  public static <A extends JComponent> A setToolTipText(Object toolTip, A c) {
    return setToolTipText(c, toolTip);
  }

  public static String nullIfEmpty(String s) {
    return isEmpty(s) ? null : s;
  }

  public static Map nullIfEmpty(Map map) {
    return isEmpty(map) ? null : map;
  }

  public static <A> List<A> nullIfEmpty(List<A> l) {
    return isEmpty(l) ? null : l;
  }

  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 String copyTextToClipboard(String text) {
    StringSelection selection = new StringSelection(text);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
    vmBus_send("newClipboardContents", text);
    return text;
  }

  public static long sysTime() {
    return sysNow();
  }

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

  public static <A, B> void put(Map<A, B> map, A a, B b) {
    if (map != null)
      map.put(a, b);
  }

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

  public static byte[] readFully(InputStream in) {
    return streamToBytes(in);
  }

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

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

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

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

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

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

  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(text);
          JMenuItem mi = new JMenuItem(p.a);
          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(text);\r\n    JMenuItem mi = new JMenuItem(...";
      }
    });
  }

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

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

  public static byte[] streamToBytes(InputStream in) {
    try {
      try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copyStream(in, baos);
        return baos.toByteArray();
      } finally {
        in.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static byte[] streamToBytes(InputStream in, int expectedSize) {
    try {
      try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(expectedSize);
        copyStream(in, baos);
        return baos.toByteArray();
      } finally {
        in.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 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 {
          {
            Thread _t_0 = new Thread("Action Listener") {

              public void run() {
                try {
                  AutoCloseable __1143 = holdInstance(instanceToHold);
                  try {
                    callF(runnable);
                  } finally {
                    _close(__1143);
                  }
                } catch (Throwable __e) {
                  _handleException(__e);
                }
              }
            };
            startThread(_t_0);
          }
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

  public static boolean isLetterOrDigit(char c) {
    return Character.isLetterOrDigit(c);
  }

  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 String defaultThreadName_name;

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

  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 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 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 Map vm_generalWeakSubMap(Object name) {
    synchronized (get(javax(), "generalMap")) {
      Map map = (Map) (vm_generalMap_get(name));
      if (map == null)
        vm_generalMap_put(name, map = newWeakMap());
      return map;
    }
  }

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

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

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