import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.match;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_mouseEvent;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.rethrow;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.IterableIterator;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import static loadableUtils.utils.getExceptionCause;
import static loadableUtils.utils.joinWithSpace;
import static loadableUtils.utils.callF;
import static loadableUtils.utils.jlabel;
import static loadableUtils.utils.multiMapPut;
import static loadableUtils.utils.join;
import static loadableUtils.utils.isAWTThread;
import static loadableUtils.utils.set;
import static loadableUtils.utils.call;
import static loadableUtils.utils.fail;
import static loadableUtils.utils.print;
import static loadableUtils.utils.call_checkArgs;
import static loadableUtils.utils.db;
import loadableUtils.utils.IntRange;
import loadableUtils.utils.JE_RepElement;
import loadableUtils.utils.ICachedJavaXExpr;
import loadableUtils.utils.PingSource;
import loadableUtils.utils.SimpleLiveValue;
import loadableUtils.utils.Matrix;
import loadableUtils.utils.IProbabilisticScheduler;
import loadableUtils.utils.Producer;
import loadableUtils.utils.IntBuffer;
import loadableUtils.utils.DynPrintLogAndEnabled;
import loadableUtils.utils.OKOrError;
import loadableUtils.utils.WithTimestamp;
import loadableUtils.utils.AbstractJavaXExpr;
import loadableUtils.utils.Timestamp;
import loadableUtils.utils.DoubleRect;
import loadableUtils.utils.Complex;
import loadableUtils.utils.JavaCodec;
import loadableUtils.utils.JECompressionSearch;
import loadableUtils.utils.CompressionSearch_AnyType;
import loadableUtils.utils.RestartableCountdown;
import loadableUtils.utils.Either;
import loadableUtils.utils.FunctionCall;
import loadableUtils.utils.T3;
import loadableUtils.utils.Swingable;
import loadableUtils.utils.AbstractCompressor_AnyType;
import loadableUtils.utils.Average;
import loadableUtils.utils.BWIntegralImage;
import loadableUtils.utils.DoubleRange;
import loadableUtils.utils.CompressionRegime_AnyType;
import loadableUtils.utils.Seconds;
import static loadableUtils.utils.withTimestamp;
import static loadableUtils.utils.javaObjectToIJavaExpr;
import static loadableUtils.utils.lambdaMapMethod;
import static loadableUtils.utils.score;
import static loadableUtils.utils.withBorder;
import static loadableUtils.utils.childrenOfType;
import static loadableUtils.utils.nanoTime;
import static loadableUtils.utils.activateFrame_v3;
import static loadableUtils.utils.b;
import static loadableUtils.utils.ewicOneOf;
import static loadableUtils.utils.jCenteredSection;
import static loadableUtils.utils.n;
import static loadableUtils.utils.ivf1WithToString;
import static loadableUtils.utils.intMatrixToImage;
import static loadableUtils.utils.area;
import static loadableUtils.utils.add;
import static loadableUtils.utils.withMargin;
import static loadableUtils.utils.addActionListener;
import static loadableUtils.utils.imageToMatrix;
import static loadableUtils.utils.hasMethod;
import static loadableUtils.utils.countIteratorToList;
import static loadableUtils.utils.containsOneOf;
import static loadableUtils.utils.dm_registerAs_direct;
import static loadableUtils.utils.hideWindow;
import static loadableUtils.utils.ymdMinusHMS;
import static loadableUtils.utils.jPopDownButton_noText;
import static loadableUtils.utils.swingLater;
import static loadableUtils.utils.matrixToList;
import static loadableUtils.utils.setImage;
import static loadableUtils.utils.gridLOLToImage;
import static loadableUtils.utils.getScreenWidth;
import static loadableUtils.utils.tsNow;
import static loadableUtils.utils.dm_reload;
import static loadableUtils.utils.getDBProgramID;
import static loadableUtils.utils.setFrameIcon;
import static loadableUtils.utils.getSnippetTitle;
import static loadableUtils.utils.jFullCenter;
import static loadableUtils.utils.quickEval;
import static loadableUtils.utils.isAlwaysOnTop;
import static loadableUtils.utils.infoBox;
import static loadableUtils.utils.toSeconds;
import static loadableUtils.utils.rect;
import static loadableUtils.utils.forEach;
import static loadableUtils.utils.disposeWindow;
import static loadableUtils.utils.formatColonProperties_noNulls;
import static loadableUtils.utils.centerAndEast;
import static loadableUtils.utils.makeFrame;
import static loadableUtils.utils.okOrError;
import static loadableUtils.utils.setDoubleBuffered;
import static loadableUtils.utils.dm_doEvery;
import static loadableUtils.utils.mergeBufferedImagesHorizontally;
import static loadableUtils.utils.partialSums_firstIs0;
import static loadableUtils.utils.hgrid;
import static loadableUtils.utils.screenshot;
import static loadableUtils.utils.ping_v3;
import static loadableUtils.utils.flattenArray2;
import static loadableUtils.utils.formatDouble;
import static loadableUtils.utils.getParent;
import static loadableUtils.utils.strOrEmpty;
import static loadableUtils.utils.pqO;
import static loadableUtils.utils.javaExpr;
import static loadableUtils.utils.shorten_str;
import static loadableUtils.utils.run;
import static loadableUtils.utils.indexAsSideValue;
import static loadableUtils.utils.has;
import static loadableUtils.utils.dm_moduleIsPoppedOut;
import static loadableUtils.utils.toRect;
import static loadableUtils.utils.installWindowDragger;
import static loadableUtils.utils.jeCompressionSearch;
import static loadableUtils.utils.clipBufferedImage;
import static loadableUtils.utils.setText;
import static loadableUtils.utils.findButton;
import static loadableUtils.utils.toJava;
import static loadableUtils.utils.getBounds;
import static loadableUtils.utils.northAndCenterWithMargin;
import static loadableUtils.utils.renderUserThreadsWithStackTraces;
import static loadableUtils.utils.newConceptsWithClassFinder;
import static loadableUtils.utils.defaultScreenshot;
import static loadableUtils.utils.activateFrame;
import static loadableUtils.utils.awtLater;
import static loadableUtils.utils.replace;
import static loadableUtils.utils.functionCall_list;
import static loadableUtils.utils.profileToConsole;
import static loadableUtils.utils.printWithMS;
import static loadableUtils.utils.format;
import static loadableUtils.utils.onEnter;
import static loadableUtils.utils.hsplit;
import static loadableUtils.utils.getFrame;
import static loadableUtils.utils.jscroll_center;
import static loadableUtils.utils.dm_fieldLiveValue;
import static loadableUtils.utils.percentRatioStrOneDigit;
import static loadableUtils.utils.toObjectArray;
import static loadableUtils.utils.rectFromPoints;
import static loadableUtils.utils.runnableThread;
import static loadableUtils.utils.allScreenBounds;
import static loadableUtils.utils.findClass_fullName;
import static loadableUtils.utils.copyLocalLog;
import static loadableUtils.utils.jscroll_centered;
import static loadableUtils.utils.parentFile;
import static loadableUtils.utils.listSet;
import static loadableUtils.utils.gazelle_wavySpacer;
import static loadableUtils.utils.callOnLoadMethods;
import static loadableUtils.utils.toString;
import static loadableUtils.utils.colToList;
import static loadableUtils.utils.removeFromParent;
import static loadableUtils.utils.renameFile;
import static loadableUtils.utils.mapQuickEval_javaExpr;
import static loadableUtils.utils.regionMatches;
import static loadableUtils.utils.printFileInfo;
import static loadableUtils.utils.screenBounds;
import static loadableUtils.utils.metaSet;
import static loadableUtils.utils.calculateLengthOfFunctionCall;
import static loadableUtils.utils.toRectangle;
import static loadableUtils.utils.javaxCodeDir;
import static loadableUtils.utils.minimizeWindow;
import static loadableUtils.utils.jbutton;
import static loadableUtils.utils.setEnabled;
import static loadableUtils.utils.functionCall;
import static loadableUtils.utils.northAndCenter;
import static loadableUtils.utils.matrixToMNGrid_rows;
import static loadableUtils.utils.jline;
import static loadableUtils.utils.forward;
import static loadableUtils.utils.vmBus_query;
import static loadableUtils.utils.getPreferredSize;
import static loadableUtils.utils.onClick;
import static loadableUtils.utils.rowToList;
import static loadableUtils.utils.jCheckBoxMenuItem;
import static loadableUtils.utils.jenableUndoRedo;
import static loadableUtils.utils.setFont;
import static loadableUtils.utils.isEditableComboBox;
import static loadableUtils.utils.numberOfCores;
import static loadableUtils.utils.showWindow;
import static loadableUtils.utils.dm_watchField;
import static loadableUtils.utils.ifloor;
import static loadableUtils.utils.hmsWithColonsAndMS;
import static loadableUtils.utils.dm_calculatedCenteredLabel;
import static loadableUtils.utils.nohup;
import static loadableUtils.utils.onWindowClosing;
import static loadableUtils.utils.asArray;
import static loadableUtils.utils.showText;
import static loadableUtils.utils.setDefaultClassFinder;
import static loadableUtils.utils.getBytecodePathForClass;
import static loadableUtils.utils.rCallF;
import static loadableUtils.utils.installWindowResizeDraggerOnBorder;
import static loadableUtils.utils.stepForNSeconds;
import static loadableUtils.utils.singular;
import static loadableUtils.utils.syncAddOrCreate;
import static loadableUtils.utils.getScreenHeight;
import static loadableUtils.utils.ratio;
import static loadableUtils.utils.fillRect;
import static loadableUtils.utils.westCenterAndEastWithMargin;
import static loadableUtils.utils.getSelectedItem;
import static loadableUtils.utils.loadAllClassesInByteCodePath;
import static loadableUtils.utils.dm_centeredFieldLabel;
import static loadableUtils.utils.similarEmptyMap;
import static loadableUtils.utils.toFile;
import static loadableUtils.utils.drop;
import static loadableUtils.utils.pixelCount;
import static loadableUtils.utils.appendToBaseName;
import static loadableUtils.utils.nClasses;
import static loadableUtils.utils.mod;
import static loadableUtils.utils.makeUndecoratedFrame;
import static loadableUtils.utils.nanosToSeconds;
import static loadableUtils.utils.dm_toggleAlwaysOnTop;
import static loadableUtils.utils.humanizeFormLabel;
import static loadableUtils.utils.countPred;
import static loadableUtils.utils.wrapForSmartAdd;
import static loadableUtils.utils.asSet;
import static loadableUtils.utils.autoFrameTitle;
import static loadableUtils.utils.autoFrameTitle_value;
import static loadableUtils.utils.scaffoldCalled;
import static loadableUtils.utils.installTrayIcon;
import static loadableUtils.utils.filter;
import static loadableUtils.utils.onChange;
import static loadableUtils.utils.pingSource;
import static loadableUtils.utils.dm_popInModule;
import static loadableUtils.utils.isNonEmptySingleZip_byMagicHeader;
import static loadableUtils.utils.dm_vis;
import static loadableUtils.utils.probabilisticForEach;
import static loadableUtils.utils.setBackground;
import static loadableUtils.utils.renderVars;
import static loadableUtils.utils.sysNow;
import static loadableUtils.utils.elapsedSeconds;
import static loadableUtils.utils.hotwire;
import static loadableUtils.utils.matrixOfMatricesToListOfLists;
import static loadableUtils.utils.metaGet;
import static loadableUtils.utils.heldInstance;
import static loadableUtils.utils.getProgramName;
import static loadableUtils.utils.trayIcon_imageAutoSize;
import java.awt.geom.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;

class main {

  static public String windowTitle = "Gazelle V 2020-10-28 .10";

  static public String downloadURL = "https://botcompany.de/jar/1033411?withLibs=1&noCompiler=1";

  static public String trayIconImageID = "#1103047";

  static public int borderSize = 5;

  static public Color color1 = awtColor("ADD8E6");

  static public Color color2 = awtColor("EEEEEE");

  static public Color color3 = awtColor("A3C0AA");

  static public IF0<PingSource> ping_v3_pingSourceMaker() {
    return () -> new PingSource();
  }

  static public class Stem {

    public JFrame window;

    public Rect getFrameRect() {
      return toRect(getBounds(window));
    }
  }

  static public Stem stem;

  static public GazelleV gazelle;

  static public TrayIcon trayIcon;

  static public JFrame mainWindow;

  static public Set<String> argsSet;

  static public void trayIconLeftClick() {
    activateFrame_v3(mainWindow);
  }

  static public void makeTrayIcon() {
    try {
      trayIcon_imageAutoSize = false;
      trayIcon = installTrayIcon(trayIconImageID, windowTitle, new Runnable() {

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

        public String toString() {
          return "trayIconLeftClick();";
        }
      }, "Show Gazelle", new Runnable() {

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

        public String toString() {
          return "activateFrame(mainWindow)";
        }
      }, "Exit Gazelle", new Runnable() {

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

        public String toString() {
          return "cleanExit();";
        }
      });
    } catch (Throwable __e) {
      print(exceptionToStringShort(__e));
    }
  }

  public static void main(final String[] args) throws Exception {
    __javax = x30.class;
    loadableUtils.utils.__setJavaX(x30.class);
    vm_generalMap_put("stefansOS", mc());
    __javax = x30.class;
    x30.__javax = x30.class;
    x30_pkg.x30_util.__setJavaX(x30.class);
    x30.cleanKillMsg = "";
    callOnLoadMethods(mc());
    argsSet = asSet(args);
    if (!argsSet.contains("noflatlaf"))
      com.formdev.flatlaf.FlatLightLaf.setup();
    if (contains(args, "profile"))
      profileToConsole(() -> actualMain(args));
    else
      actualMain(args);
    if (argsSet.contains("brexit"))
      System.exit(0);
    AutoCloseable __8 = gazelle.enter();
    try {
      gazelle.start();
    } finally {
      _close(__8);
    }
  }

  static public void actualMain(String... args) {
    System.out.println(hmsWithColonsAndMS() + ": Init");
    if (containsOneOf(argsSet, "upgrade", "update")) {
      upgradeGazelle();
      return;
    }
    makeTrayIcon();
    printWithMS("new GazelleV");
    gazelle = new GazelleV();
    stem = new Stem();
    gazelle._host = stem;
    copyLocalLog(gazelle, mc());
    AutoCloseable __9 = gazelle.enter();
    try {
      printWithMS("Visualize");
      var vis = swing(() -> gazelle.visualize());
      vis = makeWindowBorderAndTitle(vis, windowTitle);
      printWithMS("Show frame");
      JFrame frame = makeUndecoratedFrame(windowTitle, vis);
      setFrameIcon(frame, trayIconImageID);
      stem.window = mainWindow = frame;
      onWindowClosing(stem.window, new Runnable() {

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

        public String toString() {
          return "cleanExit();";
        }
      });
      showWindow(stem.window);
      printWithMS("Dudadoneski");
    } finally {
      _close(__9);
    }
  }

  static public void minimize() {
    if (trayIcon == null)
      minimizeWindow(mainWindow);
    else
      hideWindow(mainWindow);
  }

  static public JComponent makeWindowBorderAndTitle(JComponent contents, String title) {
    var icons = jline();
    icons.add(jbutton("Minimize", new Runnable() {

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

      public String toString() {
        return "minimize();";
      }
    }));
    icons.add(jbutton("Close", new Runnable() {

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

      public String toString() {
        return "disposeWindow(icons)";
      }
    }));
    icons.add(jPopDownButton_noText("Update Gazelle", runnableThread(new Runnable() {

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

      public String toString() {
        return "upgradeGazelle();";
      }
    }), "Dump threads", runnableThread(new Runnable() {

      public void run() {
        try {
          showText("User threads", renderUserThreadsWithStackTraces());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "showText(\"User threads\", renderUserThreadsWithStackTraces());";
      }
    })));
    var actualTitle = fontSizePlus(7, jCenteredLabel(title));
    var spacer = gazelle_wavySpacer();
    var titleBarMain = setOpaqueBackground(color1, westCenterAndEastWithMargin(jImage_scaledToHeight(24, trayIconImageID), actualTitle, setOpaqueBackground(color2, spacer)));
    installWindowDragger(actualTitle);
    installWindowDragger(spacer);
    var titleBar = setBackground(color2, centerAndEast(titleBarMain, icons));
    var border = BorderFactory.createLineBorder(color1, borderSize);
    var outerPanel = withBorder(border, northAndCenter(titleBar, contents));
    installWindowResizeDraggerOnBorder(outerPanel);
    return outerPanel;
  }

  static public Object dm_getStem(Object moduleOrID) {
    return stem;
  }

  static public Object resolveModule(Object moduleOrID) {
    return moduleOrID == stem ? gazelle : moduleOrID;
  }

  static public void cleanExit() {
    System.exit(0);
  }

  static public void upgradeGazelle() {
    File myJar = getBytecodePathForClass(mc());
    print("myJar", myJar);
    String javaCmd = or2(currentProcessCommand(), "java");
    String date = ymdMinusHMS();
    File f = javaxCodeDir("Downloaded Updates/" + "gazelle-" + date + ".jar");
    infoBox("Downloading Update...");
    loadBinaryPageToFile(downloadURL, f);
    printFileInfo(f);
    if (!isNonEmptySingleZip_byMagicHeader(f)) {
      infoBox("Bad file downloaded... :(");
      return;
    }
    boolean replaced = false;
    if (isFile(myJar)) {
      print("Loaded " + nClasses(loadAllClassesInByteCodePath(myJar)));
      print("Replacing with new version: " + myJar);
      renameFile(myJar, appendToBaseName(myJar, ".bak." + date));
      copyFile(f, myJar);
      printFileInfo(myJar);
      replaced = true;
    }
    infoBox(replaced ? "Installed update, replaced " + f2s(myJar) + " - now starting" : "Starting update, but could not replace originally downloaded jar");
    String cmd = pqO(javaCmd) + " -jar " + pqO(replaced ? myJar : f);
    print(cmd);
    nohup(cmd);
    cleanExit();
  }

  static public String programID;

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

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

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

  static public ThreadLocal<Boolean> dynamicObjectIsLoading_threadLocal() {
    return DynamicObject_loading;
  }

  static public class GazelleV extends DynPrintLogAndEnabled {

    static public boolean _switchableField_maxFPS = true;

    public double maxFPS = 10;

    static public boolean _switchableField_previewWidth = true;

    public int previewWidth = 200;

    static public boolean _switchableField_statsEvery = true;

    public double statsEvery = 5;

    static public boolean _switchableField_brokenMethod = true;

    volatile public boolean brokenMethod = false;

    public int lookAtScreen;

    public String previewMode;

    public int gridRows = 20;

    public PersistableThrowable lastProcessingError;

    transient public WithTimestamp<OKOrError<BufferedImage>> lastScreen;

    transient public Average screenShotTime = new Average();

    transient public Average iiTime = new Average();

    transient public Timestamp loopStarted;

    transient public RestartableCountdown screenShotCountdown = new RestartableCountdown();

    transient public IIImageSurface imageSurface;

    transient public Throwable currentProcessingError;

    transient public BufferedImage previewImage;

    transient public JButton popDownButton;

    transient public JComponent topControls;

    transient public long screenShotsTaken;

    transient public double fps;

    transient public Compression ongoingCompression, completedCompression;

    transient public String longTermCompressionProbability;

    transient public String longTermCompressionScore;

    transient public JComponent topControls2;

    public Rect area() {
      return screenBounds(min(lookAtScreen, screenCount() - 1));
    }

    public class Compression {

      final public Compression setImage(BufferedImage image) {
        return image(image);
      }

      public Compression image(BufferedImage image) {
        this.image = image;
        return this;
      }

      final public BufferedImage getImage() {
        return image();
      }

      public BufferedImage image() {
        return image;
      }

      public BufferedImage image;

      final public Compression setIi(BWIntegralImage ii) {
        return ii(ii);
      }

      public Compression ii(BWIntegralImage ii) {
        this.ii = ii;
        return this;
      }

      final public BWIntegralImage getIi() {
        return ii();
      }

      public BWIntegralImage ii() {
        return ii;
      }

      public BWIntegralImage ii;

      public CompressionSearch_AnyType search;

      public int baseLineLength;

      public GridCodec1 codec;

      public double compressionPercentage;

      public String score() {
        var submission = search == null ? null : search.bestSubmission();
        Integer compressedSize = or(submission.compressedSize(), baseLineLength);
        compressionPercentage = doubleRatio(compressedSize, baseLineLength) * 100;
        return formatDouble(compressionPercentage, 3) + "%";
      }

      public IProbabilisticScheduler scheduler() {
        return search == null ? null : search.scheduler();
      }

      public String probability() {
        var scheduler = scheduler();
        if (scheduler == null)
          return "-";
        var prob = scheduler.lastExecutedProbability();
        return formatDouble(prob, 3);
      }

      transient public List<Runnable> onCompressionDone;

      public Compression onCompressionDone(Runnable r) {
        onCompressionDone = syncAddOrCreate(onCompressionDone, r);
        return this;
      }

      public void compressionDone() {
        pcallFAll(onCompressionDone);
      }

      public void run() {
        try {
          int lHex = pixelCount(image) * 8;
          baseLineLength = calculateLengthOfFunctionCall("imageFromHex", lHex + 2);
          print("baseLineLength", baseLineLength);
          codec = new GridCodec1(image);
          codec.rows = gridRows;
          search = codec.forward();
          startThread("Gazelle Visual", new Runnable() {

            public void run() {
              try {
                for (int _repeat_6 = 0; _repeat_6 < 60; _repeat_6++) {
                  stepForNSeconds(1, search);
                  setFields("longTermCompressionProbability", probability(), "longTermCompressionScore", score());
                }
                try {
                  compressionDone();
                  List<ICachedJavaXExpr> cellCompressions = codec.strat.codeForElements();
                } catch (Throwable e) {
                  printStackTrace(e);
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "for (int _repeat_6 = 0; _repeat_6 < 60; _repeat_6++)  {\r\n          stepForNSe...";
            }
          });
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public void drawOverlay(ImageSurface is, Graphics2D g) {
        try {
          codec.drawOverlay(is, g);
        } catch (Throwable __e) {
          printStackTrace(__e);
        }
      }
    }

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

          public void run() {
            try {
              AutoCloseable __10 = enter();
              try {
                try {
                  dm_registerAs_direct("gazelleV");
                  dm_watchField("enabled", new Runnable() {

                    public void run() {
                      try {
                        if (enabled)
                          dm_reload();
                      } catch (Exception __e) {
                        throw rethrow(__e);
                      }
                    }

                    public String toString() {
                      return "if (enabled) dm_reload();";
                    }
                  });
                  dm_doEvery(1.0, new Runnable() {

                    public void run() {
                      try {
                        if (dm_moduleIsPoppedOut())
                          adjustUIForPoppedOutWindow();
                      } catch (Exception __e) {
                        throw rethrow(__e);
                      }
                    }

                    public String toString() {
                      return "if (dm_moduleIsPoppedOut()) adjustUIForPoppedOutWindow();";
                    }
                  });
                  print("Screen bounds: " + allScreenBounds());
                  dm_doEvery(min(statsEvery, 10.0), statsEvery, new Runnable() {

                    public void run() {
                      try {
                        if (enabled)
                          printStats();
                      } catch (Exception __e) {
                        throw rethrow(__e);
                      }
                    }

                    public String toString() {
                      return "if (enabled) printStats();";
                    }
                  });
                  loopStarted = tsNow();
                  shoot();
                } catch (Throwable __e) {
                  printStackTrace(__e);
                }
              } finally {
                _close(__10);
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

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

    public void shoot() {
      AutoCloseable __11 = enter();
      try {
        if (!enabled)
          return;
        long targetTime = sysNow() + iround(1000 / maxFPS);
        long time = nanoTime();
        try {
          lastScreen = withTimestamp(okOrError(() -> screenshot(area())));
          ++screenShotsTaken;
          setField("fps", doubleRatio(screenShotsTaken, elapsedSeconds(loopStarted)));
          screenShotTime.add(nanosToSeconds(nanoTime() - time));
          time = nanoTime();
          if (lastScreen.get().isOK()) {
            var img = lastScreen.get().get();
            var ii = new BWIntegralImage(img);
            iiTime.add(nanosToSeconds(nanoTime() - time));
            if (eq(previewMode, "showLatestGrabbed")) {
              if (imageSurface != null)
                imageSurface.setImage(ii, img);
            }
            if (ongoingCompression == null)
              startCompression(ii);
          }
          cpuTotal();
          currentProcessingError = null;
        } catch (Throwable e) {
          printStackTrace(e);
          setField("lastProcessingError", currentProcessingError = e);
          sleepSeconds(60);
        }
        screenShotCountdown.setTargetTime(targetTime, new Runnable() {

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

          public String toString() {
            return "shoot();";
          }
        });
      } finally {
        _close(__11);
      }
    }

    public void startCompression(BWIntegralImage ii) {
      if (ongoingCompression == null) {
        ongoingCompression = new Compression().image(lastScreen.get().get()).ii(ii);
        ongoingCompression.onCompressionDone(() -> {
          completedCompression = ongoingCompression;
          ongoingCompression = null;
          {
            if (imageSurface != null)
              imageSurface.setImage(completedCompression.ii, completedCompression.image);
          }
          imageSurface.setOverlay(g -> completedCompression.drawOverlay(imageSurface, g));
        });
        ongoingCompression.run();
      }
    }

    public void printStats() {
      print(stats());
    }

    public String stats() {
      var screen = lastScreen == null ? null : lastScreen.get();
      return formatColonProperties_noNulls("Monitored area", area(), "Error", screen == null ? null : screen.getError(), "Last screenshot taken", lastScreen == null ? null : lastScreen.timeStamp(), "Average time to take a screenshot", screenShotTime, "Average time to make integral image", iiTime, "Capacity left in first core", percentRatioStrOneDigit(freeInCore()), "Total CPU used", cpuTotal());
    }

    public String cpuTotal() {
      return setFieldAndReturn("cpuTotal", percentRatioStrOneDigit((1 - freeInCore()) / numberOfCores()));
    }

    public double freeInCore() {
      return ratio(toSeconds(screenShotCountdown.totalSleepTime), elapsedSeconds(loopStarted));
    }

    {
    }

    public JComponent visualize() {
      imageSurface = new IIImageSurface();
      setDoubleBuffered(imageSurface, true);
      imageSurface.noAlpha = true;
      var screenSelectors = jRadioButtons(countIteratorAsList(screenCount(), i -> "Screen " + (i + 1)));
      onRadioButtonChange(screenSelectors, i -> {
        lookAtScreen = i;
      });
      return hsplit(northAndCenterWithMargin(topControls = hgrid(jCenteredSection("FPS", dm_calculatedCenteredLabel(() -> iround(fps))), jCenteredSection("Compression", dm_centeredFieldLabel("longTermCompressionScore")), jCenteredSection("Probability", dm_centeredFieldLabel("longTermCompressionProbability")), jCenteredSection("CPU (" + numberOfCores() + ")", dm_centeredFieldLabel("cpuTotal"))), super.visualize()), northAndCenterWithMargin(topControls2 = jCenteredLine(listPlus(wideningListCast(Component.class, buttonsInGroup(screenSelectors)), dm_spinnerWithLabel("gridRows", 1, 500))), jscroll_center(imageSurface)));
    }

    public BufferedImage lastScreenImage() {
      return getVar(getVar(lastScreen));
    }

    public void adjustUIForPoppedOutWindow() {
      swing(new Runnable() {

        public void run() {
          try {
            if (popDownButton == null) {
              Window window = (Window) (getWindow(dm_vis()));
              var popBackInButton = findButton(window, "Pop Back In");
              var parent = getParent(popBackInButton);
              print("parent", parent);
              removeFromParent(parent);
              popDownButton = jPopDownButton_noText("Pop Back In", new Runnable() {

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

                public String toString() {
                  return "dm_popInModule(me())";
                }
              }, jCheckBoxMenuItem("Always On Top", isAlwaysOnTop(window), new Runnable() {

                public void run() {
                  try {
                    AutoCloseable __13 = enter();
                    try {
                      dm_toggleAlwaysOnTop();
                    } finally {
                      _close(__13);
                    }
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "temp enter();  dm_toggleAlwaysOnTop();";
                }
              }));
              addControl(popDownButton);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (popDownButton == null) {\r\n      Window window =  (Window) (getWindow(dm_v...";
        }
      });
    }
  }

  static public boolean _moduleClass_GazelleV = true;

  static volatile public Concepts mainConcepts;

  static public Concepts db_mainConcepts() {
    if (mainConcepts == null)
      mainConcepts = newConceptsWithClassFinder(getDBProgramID());
    return mainConcepts;
  }

  static public void cleanMeUp_concepts() {
    if (db_mainConcepts() != null)
      db_mainConcepts().cleanMeUp();
  }

  static public java.awt.Color awtColor(String hex) {
    byte[] b = bytesFromHex(dropPrefix("#", hex));
    return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2]));
  }

  static public String exceptionToStringShort(Throwable e) {
    lastException(e);
    e = getInnerException(e);
    String msg = hideCredentials(unnull(e.getMessage()));
    if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
      return baseClassName(e) + prependIfNempty(": ", msg);
    else
      return msg;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public <A extends JComponent> A fontSizePlus(final int delta, final A c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            Font font = c.getFont();
            c.setFont(font.deriveFont(font.getSize2D() + delta));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Font font = c.getFont();\r\n    c.setFont(font.deriveFont(font.getSize2D()+delt...";
        }
      });
    }
    return c;
  }

  static public JLabel jCenteredLabel(String text) {
    return jcenteredLabel(text);
  }

  static public JLabel jCenteredLabel() {
    return jcenteredLabel();
  }

  static public <A extends JComponent> A setOpaqueBackground(final Color color, final A a) {
    if (a != null) {
      swing(new Runnable() {

        public void run() {
          try {
            a.setBackground(color);
            a.setOpaque(true);
            a.putClientProperty("substancelaf.colorizationFactor", 1.0);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "a.setBackground(color);\r\n    a.setOpaque(true);\r\n    a.putClientProperty(\"sub...";
        }
      });
    }
    return a;
  }

  static public JLabel jImage_scaledToHeight(String imageID, int height) {
    return jImage(resizeImageToHeight_bilinear(loadImage2(imageID), height));
  }

  static public JLabel jImage_scaledToHeight(int height, String imageID) {
    return jImage_scaledToHeight(imageID, height);
  }

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

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

  static public String currentProcessCommand() {
    ProcessHandle processHandle = ProcessHandle.current();
    return getVar(processHandle.info().command());
  }

  static public void loadBinaryPageToFile(String url, File file) {
    try {
      print("Loading " + url);
      loadBinaryPageToFile(openConnection(new URL(url)), file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void loadBinaryPageToFile(URLConnection con, File file) {
    try {
      setHeaders(con);
      loadBinaryPageToFile_noHeaders(con, file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void loadBinaryPageToFile_noHeaders(URLConnection con, File file) {
    try {
      File ftemp = new File(f2s(file) + "_temp");
      FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
      try {
        InputStream inputStream = con.getInputStream();
        long len = 0;
        try {
          len = con.getContentLength();
        } catch (Throwable e) {
          printStackTrace(e);
        }
        String pat = "  {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
        copyStreamWithPrints(inputStream, buf, pat);
        inputStream.close();
        buf.close();
        file.delete();
        renameFile_assertTrue(ftemp, file);
      } finally {
        if (buf != null)
          buf.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public boolean isFile(String path) {
    return isFile(newFile(path));
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public int screenCount() {
    return l(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices());
  }

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

  static public double doubleRatio(double x, double y) {
    return y == 0 ? 0 : x / y;
  }

  static public double doubleRatio(Seconds x, Seconds y) {
    return doubleRatio(x.get(), y.get());
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public boolean eq(Symbol a, String b) {
    return eq(str(a), b);
  }

  static public void sleepSeconds(double s) {
    if (s > 0)
      sleep(round(s * 1000));
  }

  static public ButtonGroup jRadioButtons(Collection<String> strings) {
    return jradiobuttons(strings);
  }

  static public ButtonGroup jRadioButtons(String... strings) {
    return jradiobuttons(strings);
  }

  static public List<Integer> countIteratorAsList(int b) {
    return countIteratorAsList(0, b);
  }

  static public List<Integer> countIteratorAsList(int a, int b) {
    return countIteratorToList(a, b);
  }

  static public <A> List<A> countIteratorAsList(int b, IF1<Integer, A> f) {
    return countIteratorAsList(0, b, f);
  }

  static public <A> List<A> countIteratorAsList(int a, int b, IF1<Integer, A> f) {
    return countIteratorToList(a, b, f);
  }

  static public List<Integer> countIteratorAsList(int a, int b, int step) {
    return countIteratorToList(a, b, step);
  }

  static public <A> List<A> countIteratorAsList(double a, double b, double step, IF1<Double, A> f) {
    return countIteratorToList(a, b, step, f);
  }

  static public <A> List<Double> countIteratorAsList(double a, double b, double step) {
    return countIteratorToList(a, b, step);
  }

  static public <A> List<A> countIteratorAsList(IF1<Double, A> f, double a, double b, double step) {
    return countIteratorToList(f, a, b, step);
  }

  static public <A> List<A> countIteratorAsList(IF1<Integer, A> f, int b) {
    return countIteratorAsList(f, 0, b);
  }

  static public <A> List<A> countIteratorAsList(IF1<Integer, A> f, int a, int b) {
    return countIteratorToList(f, a, b);
  }

  static public void onRadioButtonChange(final ButtonGroup group, final Object f) {
    final Var<Integer> idx = new Var(selectedButtonIdx(group));
    Runnable r = new Runnable() {

      public void run() {
        try {
          int idx2 = selectedButtonIdx(group);
          if (idx2 >= 0 && idx2 != idx.get()) {
            idx.set(idx2);
            pcallF(f, idx2);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "int idx2 = selectedButtonIdx(group);\r\n    if (idx2 >= 0 && idx2 != idx.get())...";
      }
    };
    for (AbstractButton b : buttonsInGroup(group)) onChange(b, r);
  }

  static public void onRadioButtonChange(ButtonGroup group, IVF1<Integer> f) {
    onRadioButtonChange(group, (Object) f);
  }

  static public JPanel jCenteredLine(Component... components) {
    return jcenteredline(components);
  }

  static public JPanel jCenteredLine(List<? extends Component> components) {
    return jcenteredline(components);
  }

  static public <A> List<A> listPlus(Collection<A> l, A... more) {
    return concatLists(l, asList(more));
  }

  static public <A extends B, B> List<B> wideningListCast(Class<B> c, List<A> l) {
    return (List) l;
  }

  static public <A extends B, B> Collection<B> wideningListCast(Class<B> c, Collection<A> l) {
    return (Collection) l;
  }

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

  static public JComponent dm_spinnerWithLabel(String field, int min, int max) {
    return withLabel(humanizeLabel(field), dm_spinner(field, min, max));
  }

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

  static public <A> A getVar(Optional<A> v) {
    return v == null ? null : v.orElse(null);
  }

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

  static public byte[] bytesFromHex(String s) {
    return hexToBytes(s);
  }

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

  static public int ubyteToInt(byte b) {
    return b & 0x0FF;
  }

  static public int ubyteToInt(char c) {
    return c & 0x0FF;
  }

  static volatile public PersistableThrowable lastException_lastException;

  static public PersistableThrowable lastException() {
    return lastException_lastException;
  }

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

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

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

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

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

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

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

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

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

  static public int[] unnull(int[] l) {
    return l == null ? emptyIntArray() : l;
  }

  static public char[] unnull(char[] l) {
    return l == null ? emptyCharArray() : l;
  }

  static public double[] unnull(double[] l) {
    return l == null ? emptyDoubleArray() : l;
  }

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

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

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

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

  static public Pt unnull(Pt p) {
    return p == null ? new Pt() : p;
  }

  static public Symbol unnull(Symbol s) {
    return s == null ? emptySymbol() : s;
  }

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

  static public int unnull(Integer i) {
    return i == null ? 0 : i;
  }

  static public long unnull(Long l) {
    return l == null ? 0L : l;
  }

  static public double unnull(Double l) {
    return l == null ? 0.0 : l;
  }

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

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

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

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

  static public Map vm_generalMap_map;

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

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

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

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

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

  static public JLabel jcenteredLabel(String text) {
    return setHorizontalAlignment(JLabel.CENTER, jLabel(text));
  }

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

  static public JLabel jImage(Image img) {
    return jimage(img);
  }

  static public JLabel jImage(String imageID) {
    return jimage(imageID);
  }

  static public BufferedImage resizeImageToHeight_bilinear(BufferedImage img, int newH) {
    return scaleImage_bilinear(doubleRatio(newH, img.getHeight()), img);
  }

  static public BufferedImage loadImage2(String snippetIDOrURL) {
    return loadBufferedImage(snippetIDOrURL);
  }

  static public BufferedImage loadImage2(File file) {
    return loadBufferedImage(file);
  }

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

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

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

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

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

  static public boolean nempty(BitSet bs) {
    return !empty(bs);
  }

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

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

  static public boolean nempty(MultiMap mm) {
    return mm != null && !mm.isEmpty();
  }

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

  static public boolean nempty(IntRange r) {
    return !empty(r);
  }

  static public boolean nempty(IntBuffer b) {
    return b != null && !b.isEmpty();
  }

  static public boolean nempty(Rect r) {
    return r != null && r.w != 0 && r.h != 0;
  }

  static public boolean nempty(MultiSet ms) {
    return ms != null && !ms.isEmpty();
  }

  static public URLConnection openConnection(String url) {
    try {
      return openConnection(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public URLConnection openConnection(URL url) {
    try {
      ping();
      callOpt(javax(), "recordOpenURLConnection", str(url));
      return url.openConnection();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

  public static File mkdirsFor(File file) {
    return mkdirsForFile(file);
  }

  static public void copyStreamWithPrints(InputStream in, OutputStream out, String pat) {
    try {
      byte[] buf = new byte[65536];
      int total = 0;
      while (true) {
        int n = in.read(buf);
        if (n <= 0)
          return;
        out.write(buf, 0, n);
        if ((total + n) / 100000 > total / 100000)
          print(pat.replace("{*}", str(roundDownTo(100000, total))));
        total += n;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File renameFile_assertTrue(File a, File b) {
    try {
      if (a.equals(b))
        return b;
      if (!a.exists())
        throw fail("Source file not found: " + f2s(a));
      if (b.exists())
        throw fail("Target file exists: " + f2s(b));
      mkdirsForFile(b);
      if (!a.renameTo(b))
        throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
      return b;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

  static public Class __javax;

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

  static public void __setJavaX(Class j) {
    __javax = j;
    _onJavaXSet();
  }

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

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

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

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

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

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

  static public Object pcallF(Runnable r) {
    try {
      {
        if (r != null)
          r.run();
      }
      return null;
    } catch (Throwable __e) {
      return null;
    }
  }

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

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

  static public String defaultThreadName_name;

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

  static public Runnable wrapAsActivity(Object r) {
    if (r == null)
      return null;
    Runnable r2 = toRunnable(r);
    Object mod = dm_current_generic();
    if (mod == null)
      return r2;
    return new Runnable() {

      public void run() {
        try {
          AutoCloseable c = (AutoCloseable) (rcall("enter", mod));
          AutoCloseable __1 = c;
          try {
            r2.run();
          } finally {
            _close(__1);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "AutoCloseable c =  (AutoCloseable) (rcall enter(mod));\r\n    temp c;\r\n    r2.r...";
      }
    };
  }

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

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

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

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

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

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

  static public Map<Thread, Boolean> _registerThread_threads;

  static public Object _onRegisterThread;

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

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

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

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

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

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

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

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

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

  static volatile public boolean sleep_noSleep = false;

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

  static public void sleep() {
    try {
      if (sleep_noSleep)
        throw fail("nosleep");
      print("Sleeping.");
      sleepQuietly();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public String round(String s) {
    return roundBracket(s);
  }

  static public Complex round(Complex c) {
    return new Complex(round(c.re), round(c.im));
  }

  static public ButtonGroup jradiobuttons(Collection<String> strings) {
    return selectFirstRadioButton(jUnselectedRadioButtons(strings));
  }

  static public ButtonGroup jradiobuttons(String... strings) {
    return jradiobuttons(asList(strings));
  }

  static public int selectedButtonIdx(ButtonGroup g) {
    List<AbstractButton> l = buttonsInGroup(g);
    for (int i = 0; i < l(l); i++) if (l.get(i).isSelected())
      return i;
    return -1;
  }

  static public JPanel jcenteredline(final Component... components) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          return jFullCenter(hstackWithSpacing(components));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret jFullCenter(hstackWithSpacing(components));";
      }
    });
  }

  static public JPanel jcenteredline(List<? extends Component> components) {
    return jcenteredline(asArray(Component.class, components));
  }

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

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

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

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

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

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

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

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

  static public <A> ArrayList<A> asList(Iterator<A> it) {
    ArrayList l = new ArrayList();
    if (it != null)
      while (it.hasNext()) l.add(it.next());
    return l;
  }

  static public <A> ArrayList<A> asList(IterableIterator<A> s) {
    return asList((Iterator) s);
  }

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

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

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

  static public <A> List<A> asList(Pair<A, A> p) {
    return p == null ? null : ll(p.a, p.b);
  }

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

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

  static public JComponent withLabel(JComponent label, JComponent component) {
    return westAndCenterWithMargin(label, component);
  }

  static public String humanizeLabel(String s) {
    return humanizeFormLabel(s);
  }

  static public JSpinner dm_spinner(String field, int min, int max) {
    return liveValueSpinner(dm_fieldLiveValue(field), min, max);
  }

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

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

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

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

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

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

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

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

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

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

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

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

  static public int[] emptyIntArray_a = new int[0];

  static public int[] emptyIntArray() {
    return emptyIntArray_a;
  }

  static public char[] emptyCharArray = new char[0];

  static public char[] emptyCharArray() {
    return emptyCharArray;
  }

  static public double[] emptyDoubleArray = new double[0];

  static public double[] emptyDoubleArray() {
    return emptyDoubleArray;
  }

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

  static public Object[] emptyObjectArray_a = new Object[0];

  static public Object[] emptyObjectArray() {
    return emptyObjectArray_a;
  }

  static public Symbol emptySymbol_value;

  static public Symbol emptySymbol() {
    if (emptySymbol_value == null)
      emptySymbol_value = symbol("");
    return emptySymbol_value;
  }

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

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

  static public String substring(String s, IntRange r) {
    return r == null ? null : substring(s, r.start, r.end);
  }

  static public String substring(String s, CharSequence l) {
    return substring(s, lCharSequence(l));
  }

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

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

  static public boolean empty(Iterable c) {
    return c == null || !c.iterator().hasNext();
  }

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

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

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

  static public boolean empty(BitSet bs) {
    return bs == null || bs.isEmpty();
  }

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

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

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

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

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

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

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

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

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

  static public boolean empty(MultiMap mm) {
    return mm == null || mm.isEmpty();
  }

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

  static public boolean empty(IntRange r) {
    return r == null || r.empty();
  }

  static public boolean empty(DoubleRange r) {
    return r == null || r.isEmpty();
  }

  static public boolean empty(IntBuffer b) {
    return b == null || b.isEmpty();
  }

  static public boolean empty(Rect r) {
    return !(r != null && r.w != 0 && r.h != 0);
  }

  static public Runnable addThreadInfoToRunnable(final Object r) {
    final Object info = _threadInfo();
    return info == null ? asRunnable(r) : new Runnable() {

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

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

  static public <A extends JLabel> A setHorizontalAlignment(final int pos, final A a) {
    swingCall(a, "setHorizontalAlignment", pos);
    return a;
  }

  static public <A extends AbstractButton> A setHorizontalAlignment(final int pos, final A a) {
    swingCall(a, "setHorizontalAlignment", pos);
    return a;
  }

  static public <A extends JTextField> A setHorizontalAlignment(final int pos, final A a) {
    swingCall(a, "setHorizontalAlignment", pos);
    return a;
  }

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

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

  static public JLabel jimage(Image img) {
    return jImageLabel(img);
  }

  static public JLabel jimage(String imageID) {
    return jImageLabel(imageID);
  }

  static public BufferedImage scaleImage_bilinear(BufferedImage before, double scaleX) {
    return scaleImage_bilinear(before, scaleX, scaleX);
  }

  static public BufferedImage scaleImage_bilinear(BufferedImage before, double scaleX, double scaleY) {
    return scaleImageWithOp(before, scaleX, scaleY, AffineTransformOp.TYPE_BILINEAR);
  }

  static public BufferedImage scaleImage_bilinear(double scale, BufferedImage before) {
    return scaleImage_bilinear(before, scale);
  }

  static public boolean loadBufferedImage_useImageCache = true;

  static public BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) {
    try {
      ping();
      if (snippetIDOrURLOrFile == null)
        return null;
      if (isURL(snippetIDOrURLOrFile))
        return imageIO_readURL(snippetIDOrURLOrFile);
      if (isAbsolutePath(snippetIDOrURLOrFile))
        return loadBufferedImage(new File(snippetIDOrURLOrFile));
      if (!isSnippetID(snippetIDOrURLOrFile))
        throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
      String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return loadBufferedImage(rl.loadLibrary(snippetID));
      File dir = imageSnippetsCacheDir();
      if (loadBufferedImage_useImageCache) {
        dir.mkdirs();
        File file = new File(dir, snippetID + ".png");
        if (file.exists() && file.length() != 0)
          try {
            return ImageIO.read(file);
          } catch (Throwable e) {
            e.printStackTrace();
          }
      }
      String imageURL = snippetImageURL_http(snippetID);
      print("Loading image: " + imageURL);
      BufferedImage image = imageIO_readURL(imageURL);
      if (loadBufferedImage_useImageCache) {
        File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
        ImageIO.write(image, "png", tempFile);
        tempFile.renameTo(new File(dir, snippetID + ".png"));
      }
      return image;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedImage loadBufferedImage(File file) {
    return loadBufferedImageFile(file);
  }

  static public boolean ping() {
    return ping(pingSource());
  }

  static public boolean ping(PingSource source) {
    ping_v3(source);
    return true;
  }

  static public boolean ping_impl(boolean okInCleanUp) {
    return ping();
  }

  static volatile public boolean ping_pauseAll = false;

  static public String getComputerID_quick() {
    return computerID();
  }

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

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

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

  static public int roundDownTo(int n, int x) {
    return x / n * n;
  }

  static public long roundDownTo(long n, long x) {
    return x / n * n;
  }

  static public void _onJavaXSet() {
  }

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

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

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

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

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

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

  static public Runnable _topLevelErrorHandling(Runnable r) {
    if (r == null)
      return null;
    Object info = _threadInfo();
    Object mod = dm_current_generic();
    if (info == null && mod == null)
      return r;
    return new Runnable() {

      public void run() {
        try {
          AutoCloseable __1 = (AutoCloseable) (rcall("enter", mod));
          try {
            _threadInheritInfo(info);
            r.run();
          } finally {
            _close(__1);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "temp (AutoCloseable) rcall enter(mod);\r\n    _threadInheritInfo(info);\r\n    r....";
      }
    };
  }

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

  static public double parseDouble(String s) {
    return empty(s) ? 0.0 : Double.parseDouble(s);
  }

  static public Object sleepQuietly_monitor = new Object();

  static public void sleepQuietly() {
    try {
      assertFalse(isAWTThread());
      synchronized (sleepQuietly_monitor) {
        sleepQuietly_monitor.wait();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public String roundBracket(Object s) {
    return roundBracket(str(s));
  }

  static public ButtonGroup selectFirstRadioButton(ButtonGroup g) {
    selectRadioButton(first(buttonsInGroup(g)));
    return g;
  }

  static public ButtonGroup jUnselectedRadioButtons(Collection<String> strings) {
    final ButtonGroup g = new ButtonGroup();
    for (String s : unnull(strings)) jradiobutton(s, g);
    return g;
  }

  static public int hstackWithSpacing_spacing = 10;

  static public JPanel hstackWithSpacing(Object... parts) {
    parts = flattenArray2(parts);
    int spacing = hstackWithSpacing_spacing;
    int i = 0;
    if (first(parts) instanceof Integer) {
      spacing = toInt(first(parts));
      ++i;
    }
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.VERTICAL;
    gbc.gridheight = GridBagConstraints.REMAINDER;
    for (; i < l(parts); i++) {
      if (i != 0)
        panel.add(javax.swing.Box.createRigidArea(new Dimension(spacing, 0)), gbc);
      panel.add(wrapForSmartAdd(parts[i]), gbc);
    }
    gbc.weightx = 1;
    panel.add(jrigid(), gbc);
    return panel;
  }

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

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

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

  static public <A, B> Map<A, B> addAll(Map<A, B> a, Map<? extends A, ? extends B> b) {
    if (a != null && b != null)
      a.putAll(b);
    return a;
  }

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

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

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

  static public JPanel westAndCenterWithMargin(Component w, Component c) {
    return westAndCenter(withRightMargin(w), c);
  }

  static public JPanel westAndCenterWithMargin(int margin, Component w, Component c) {
    return westAndCenter(withRightMargin(margin, w), c);
  }

  static public JSpinner liveValueSpinner(final SimpleLiveValue<Integer> lv, int min, int max) {
    final JSpinner spinner = jSpinner(lv.get(), min, max);
    onChange(spinner, new Runnable() {

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

      public String toString() {
        return "lv.set(intFromSpinner(spinner))";
      }
    });
    lv.onChange(new Runnable() {

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

      public String toString() {
        return "setSpinnerValue(spinner, lv!)";
      }
    });
    return spinner;
  }

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

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

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

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

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

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

  static public int shorten_default = 100;

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

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

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

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

  static public int parseHexChar(char c) {
    if (c >= '0' && c <= '9')
      return charDiff(c, '0');
    if (c >= 'a' && c <= 'f')
      return charDiff(c, 'a') + 10;
    if (c >= 'A' && c <= 'F')
      return charDiff(c, 'A') + 10;
    return -1;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public WeakHasherMap<Symbol, Boolean> symbol_map = new WeakHasherMap(new Hasher<Symbol>() {

    public int hashCode(Symbol symbol) {
      return symbol.text.hashCode();
    }

    public boolean equals(Symbol a, Symbol b) {
      if (a == null)
        return b == null;
      return b != null && eq(a.text, b.text);
    }
  });

  static public Symbol symbol(String s) {
    if (s == null)
      return null;
    synchronized (symbol_map) {
      Symbol symbol = new Symbol(s, true);
      Symbol existingSymbol = symbol_map.findKey(symbol);
      if (existingSymbol == null)
        symbol_map.put(existingSymbol = symbol, true);
      return existingSymbol;
    }
  }

  static public Symbol symbol(CharSequence s) {
    if (s == null)
      return null;
    if (s instanceof Symbol)
      return (Symbol) s;
    if (s instanceof String)
      return symbol((String) s);
    return symbol(str(s));
  }

  static public Symbol symbol(Object o) {
    return symbol((CharSequence) o);
  }

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

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

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

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

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

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

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

  static public Object swingCall(final Object o, final String method, final Object... args) {
    return swing(new F0<Object>() {

      public Object get() {
        try {
          return call(o, method, args);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret call(o, method, args);";
      }
    });
  }

  static public JLabel jImageLabel(Image img) {
    return swingNu(JLabel.class, imageIcon(img));
  }

  static public JLabel jImageLabel(javax.swing.Icon icon) {
    return swingNu(JLabel.class, icon);
  }

  static public JLabel jImageLabel(String imageID) {
    return jImageLabel(imageIcon(imageID));
  }

  static public JLabel jImageLabel(String text, String imageID) {
    final JLabel l = swingNu(JLabel.class, text, imageIcon(imageID), JLabel.CENTER);
    {
      swing(new Runnable() {

        public void run() {
          try {
            l.setVerticalTextPosition(SwingConstants.BOTTOM);
            l.setHorizontalTextPosition(SwingConstants.CENTER);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "l.setVerticalTextPosition(SwingConstants.BOTTOM);\r\n    l.setHorizontalTextPos...";
        }
      });
    }
    return l;
  }

  static public BufferedImage scaleImageWithOp(BufferedImage before, double scaleX, int affineTransformOpType) {
    return scaleImageWithOp(before, scaleX, scaleX, affineTransformOpType);
  }

  static public BufferedImage scaleImageWithOp(BufferedImage before, double scaleX, double scaleY, int affineTransformOpType) {
    if (scaleX == 1 && scaleY == 1)
      return before;
    int w = before.getWidth();
    int h = before.getHeight();
    int neww = max(1, iround(w * scaleX)), newh = max(1, iround(h * scaleY));
    BufferedImage after = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB);
    AffineTransform at = new AffineTransform();
    at.scale(scaleX, scaleY);
    AffineTransformOp scaleOp = new AffineTransformOp(at, affineTransformOpType);
    return scaleOp.filter(before, after);
  }

  static public boolean isURL(String s) {
    return startsWithOneOf(s, "http://", "https://", "file:");
  }

  static public BufferedImage imageIO_readURL(String url) {
    try {
      return ImageIO.read(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

  static public File imageSnippetsCacheDir() {
    return javaxCachesDir("Image-Snippets");
  }

  static public String snippetImageURL_http(String snippetID) {
    return snippetImageURL_http(snippetID, "png");
  }

  static public String snippetImageURL_http(String snippetID, String contentType) {
    return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
  }

  static public BufferedImage loadBufferedImageFile(File file) {
    try {
      return isFile(file) ? ImageIO.read(file) : null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String _computerID;

  static public Lock computerID_lock = lock();

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

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

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

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

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

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

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

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

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

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

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

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

  static public void selectRadioButton(final AbstractButton rb) {
    if (rb == null)
      return;
    {
      swing(new Runnable() {

        public void run() {
          try {
            rb.setSelected(true);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "rb.setSelected(true);";
        }
      });
    }
  }

  static public void selectRadioButton(ButtonGroup group, int index) {
    selectRadioButton(get(buttonsInGroup(group), index));
  }

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

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

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

  static public <A, B> Pair<A, B> first(Map<A, B> map) {
    return mapEntryToPair(first(entrySet(map)));
  }

  static public <A, B> Pair<A, B> first(MultiMap<A, B> mm) {
    if (mm == null)
      return null;
    var e = first(mm.data.entrySet());
    if (e == null)
      return null;
    return pair(e.getKey(), first(e.getValue()));
  }

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

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

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

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

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

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

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

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

  static public int first(IntBuffer buf) {
    return buf.get(0);
  }

  static public <A> A first(A[] l, IF1<A, Boolean> pred) {
    return firstThat(l, pred);
  }

  static public <A> A first(Iterable<A> l, IF1<A, Boolean> pred) {
    return firstThat(l, pred);
  }

  static public <A> A first(IF1<A, Boolean> pred, Iterable<A> l) {
    return firstThat(pred, l);
  }

  static public JRadioButton jradiobutton(String text, ButtonGroup group) {
    return swing(new F0<JRadioButton>() {

      public JRadioButton get() {
        try {
          JRadioButton rb = new JRadioButton(text);
          if (group != null)
            group.add(rb);
          return rb;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JRadioButton rb = new JRadioButton(text);\r\n    if (group != null) group.add(r...";
      }
    });
  }

  static public JRadioButton jradiobutton(ButtonGroup group, String text) {
    return jradiobutton(text, group);
  }

  static public JRadioButton jradiobutton(ButtonGroup group, String text, boolean selected) {
    var rb = jradiobutton(group, text);
    if (selected)
      selectRadioButton(rb);
    return rb;
  }

  static public int toInt(Object o) {
    if (o == null)
      return 0;
    if (o instanceof Number)
      return ((Number) o).intValue();
    if (o instanceof String)
      return parseInt((String) o);
    if (o instanceof Boolean)
      return boolToInt((Boolean) o);
    throw fail("woot not int: " + getClassName(o));
  }

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

  static public Component jrigid() {
    return javax.swing.Box.createRigidArea(new Dimension(0, 0));
  }

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

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

  static public int withRightMargin_defaultWidth = 6;

  static public JPanel withRightMargin(Component c) {
    return withRightMargin(withRightMargin_defaultWidth, c);
  }

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

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

      public String toString() {
        return "JPanel p = marginPanel();\r\n    p.setBorder(BorderFactory.createEmptyBorder(0,...";
      }
    });
  }

  static public JSpinner jSpinner(final int value) {
    return swing(new F0<JSpinner>() {

      public JSpinner get() {
        try {
          JSpinner s = new JSpinner();
          s.setValue(value);
          return s;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "new JSpinner s;\r\n    s.setValue(value);\r\n    ret s;";
      }
    });
  }

  static public JSpinner jSpinner(final int value, final int min, final int max) {
    return swing(new F0<JSpinner>() {

      public JSpinner get() {
        try {
          return new JSpinner(new SpinnerNumberModel(value, min, max, 1));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new JSpinner(new SpinnerNumberModel(value, min, max, 1));";
      }
    });
  }

  static public int intFromSpinner(JSpinner s) {
    return toInt(s.getValue());
  }

  static public void setSpinnerValue(final JSpinner s, final int value) {
    if (s != null) {
      swing(new Runnable() {

        public void run() {
          try {
            s.setValue(value);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "s.setValue(value);";
        }
      });
    }
  }

  static public CharSequence subCharSequence(CharSequence s, int x) {
    return subCharSequence(s, x, s == null ? 0 : s.length());
  }

  static public CharSequence subCharSequence(CharSequence 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.subSequence(x, y);
  }

  static public int charDiff(char a, char b) {
    return (int) a - (int) b;
  }

  static public int charDiff(String a, char b) {
    return charDiff(stringToChar(a), b);
  }

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

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

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

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

  static public boolean eqic(Symbol a, Symbol b) {
    return eq(a, b);
  }

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

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

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

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

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

  static public int imageIcon_cacheSize = 10;

  static public boolean imageIcon_verbose = false;

  static public Map<String, ImageIcon> imageIcon_cache;

  static public Lock imageIcon_lock = lock();

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

  static public ImageIcon imageIcon(String imageID) {
    try {
      if (imageID == null)
        return null;
      Lock __0 = imageIcon_lock;
      lock(__0);
      try {
        if (imageIcon_cache == null)
          imageIcon_cache = new MRUCache(imageIcon_cacheSize);
        imageID = fsI(imageID);
        ImageIcon ii = imageIcon_cache.get(imageID);
        if (ii == null) {
          if (imageIcon_verbose)
            print("Loading image icon: " + imageID);
          File f = loadBinarySnippet(imageID);
          Boolean b = imageIcon_fixGIF.get();
          if (!isFalse(b))
            ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
          else
            ii = new ImageIcon(f.toURI().toURL());
        } else
          imageIcon_cache.remove(imageID);
        imageIcon_cache.put(imageID, ii);
        return ii;
      } finally {
        unlock(__0);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ImageIcon imageIcon(File f) {
    try {
      return new ImageIcon(f.toURI().toURL());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ImageIcon imageIcon(Image img) {
    return new ImageIcon(img);
  }

  static public ImageIcon imageIcon(RGBImage img) {
    return imageIcon(img.getBufferedImage());
  }

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

  static public <A> A proxy(Class<A> intrface, final Object target) {
    if (target == null)
      return null;
    if (isInstance(intrface, target))
      return (A) target;
    return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new proxy_InvocationHandler(target));
  }

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

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

  static public File javaxCachesDir_dir;

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

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

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

  static public String snippetImageURL(long snippetID) {
    return snippetImageURL(fsI(snippetID));
  }

  static public String snippetImageURL(String snippetID) {
    return snippetImageURL(snippetID, "png");
  }

  static public String snippetImageURL(String snippetID, String contentType) {
    if (snippetID == null || isURL(snippetID))
      return snippetID;
    long id = parseSnippetID(snippetID);
    String url;
    if (isImageServerSnippet(id))
      url = imageServerLink(id);
    else
      url = "https://botcompany.de/img/" + id;
    return url;
  }

  static public void lock(Lock lock) {
    try {
      ping();
      if (lock == null)
        return;
      try {
        vmBus_send("locking", lock, "thread", currentThread());
        lock.lockInterruptibly();
        vmBus_send("locked", lock, "thread", currentThread());
      } catch (InterruptedException e) {
        Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
        print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
        printStackTrace(e);
        rethrow(e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

  static public String loadTextFile(File f, String defaultContents) {
    return loadTextFile(f, defaultContents, "UTF-8");
  }

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

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

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

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

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

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

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

  static public String makeRandomID(int length, Random random) {
    char[] id = new char[length];
    for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
    return new String(id);
  }

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

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

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

  static public void unlock(Lock lock, String msg) {
    if (lock == null)
      return;
    lock.unlock();
    vmBus_send("unlocked", lock, "thread", currentThread());
    print("Unlocked: " + msg);
  }

  static public void unlock(Lock lock) {
    if (lock == null)
      return;
    lock.unlock();
    vmBus_send("unlocked", lock, "thread", currentThread());
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public <A, B> Pair<A, B> mapEntryToPair(Map.Entry<A, B> e) {
    return e == null ? null : pair(e.getKey(), e.getValue());
  }

  static public <A, B> Set<Map.Entry<A, B>> entrySet(Map<A, B> map) {
    return _entrySet(map);
  }

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

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

  static public <A> A firstThat(Iterable<A> l, IF1<A, Boolean> pred) {
    for (A a : unnullForIteration(l)) if (pred.get(a))
      return a;
    return null;
  }

  static public <A> A firstThat(A[] l, IF1<A, Boolean> pred) {
    for (A a : unnullForIteration(l)) if (pred.get(a))
      return a;
    return null;
  }

  static public <A> A firstThat(IF1<A, Boolean> pred, Iterable<A> l) {
    return firstThat(l, pred);
  }

  static public <A> A firstThat(IF1<A, Boolean> pred, A[] l) {
    return firstThat(l, pred);
  }

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

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

  static public int boolToInt(boolean b) {
    return b ? 1 : 0;
  }

  static public <A extends Component> A _recordNewSwingComponent(A c) {
    if (c != null)
      callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
    return c;
  }

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

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

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

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

  static public JPanel marginPanel() {
    return jtransparent(borderLayoutPanel());
  }

  static public char stringToChar(String s) {
    if (l(s) != 1)
      throw fail("bad stringToChar: " + s);
    return firstChar(s);
  }

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

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

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

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

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

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

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

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

  static public File loadBinarySnippet(String snippetID) {
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return rl.loadLibrary(snippetID);
    return loadBinarySnippet_noResourceLoader(snippetID);
  }

  static public File loadBinarySnippet_noResourceLoader(String snippetID) {
    try {
      long id = parseSnippetID(snippetID);
      if (isImageServerSnippet(id))
        return loadImageAsFile(snippetID);
      File f = DiskSnippetCache_getLibrary(id);
      if (fileSize(f) == 0)
        f = loadDataSnippetToFile_noResourceLoader(snippetID);
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public boolean loadBufferedImageFixingGIFs_debug = false;

  static public ThreadLocal<Var<byte[]>> loadBufferedImageFixingGIFs_output = new ThreadLocal();

  static public Image loadBufferedImageFixingGIFs(File file) {
    try {
      if (!file.exists())
        return null;
      if (!isGIF(file))
        return ImageIO.read(file);
      if (loadBufferedImageFixingGIFs_debug)
        print("loadBufferedImageFixingGIFs" + ": checking gif");
      ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
      reader.setInput(ImageIO.createImageInputStream(file));
      int numImages = reader.getNumImages(true);
      IIOMetadata imageMetaData = reader.getImageMetadata(0);
      String metaFormatName = imageMetaData.getNativeMetadataFormatName();
      boolean foundBug = false;
      for (int i = 0; i < numImages && !foundBug; i++) {
        IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
        int nNodes = root.getLength();
        for (int j = 0; j < nNodes; j++) {
          org.w3c.dom.Node node = root.item(j);
          if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
            String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
            if (Integer.parseInt(delay) == 0) {
              foundBug = true;
            }
            break;
          }
        }
      }
      if (loadBufferedImageFixingGIFs_debug)
        print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
      Image image;
      if (!foundBug) {
        image = Toolkit.getDefaultToolkit().createImage(f2s(file));
      } else {
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        {
          ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
          try {
            ImageWriter writer = ImageIO.getImageWriter(reader);
            writer.setOutput(ios);
            writer.prepareWriteSequence(null);
            for (int i = 0; i < numImages; i++) {
              BufferedImage frameIn = reader.read(i);
              IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
              int nNodes = root.getLength();
              for (int j = 0; j < nNodes; j++) {
                org.w3c.dom.Node node = root.item(j);
                if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
                  String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
                  if (Integer.parseInt(delay) == 0) {
                    ((IIOMetadataNode) node).setAttribute("delayTime", "10");
                  }
                  break;
                }
              }
              IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
              metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
              IIOImage frameOut = new IIOImage(frameIn, null, metadata);
              writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
            }
            writer.endWriteSequence();
          } finally {
            _close(ios);
          }
        }
        byte[] data = baoStream.toByteArray();
        setVar(loadBufferedImageFixingGIFs_output.get(), data);
        if (loadBufferedImageFixingGIFs_debug)
          print("Data size: " + l(data));
        image = Toolkit.getDefaultToolkit().createImage(data);
      }
      return image;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

  static public String _userHome;

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

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

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

  static public String imageServerLink(String md5OrID) {
    if (possibleMD5(md5OrID))
      return "https://botcompany.de/images/md5/" + md5OrID;
    return imageServerLink(parseSnippetID(md5OrID));
  }

  static public String imageServerLink(long id) {
    return "https://botcompany.de/images/" + id;
  }

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

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

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

  static public Map<Thread, Object> vm_threadInterruptionReasonsMap() {
    return vm_generalWeakSubMap("Thread interruption reasons");
  }

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

  static public void lockOrFail(Lock lock, long timeout) {
    try {
      ping();
      vmBus_send("locking", lock, "thread", currentThread());
      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);
      }
      vmBus_send("locked", lock, "thread", currentThread());
      ping();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public File javaxDataDir_dir;

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

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

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

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

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

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

  static public class CriticalAction {

    public String description;

    public CriticalAction() {
    }

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

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

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

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

  static public long now_virtualTime;

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

  static public String mainClassNameForClassLoader(ClassLoader cl) {
    return or((String) callOpt(cl, "mainClassName"), "main");
  }

  static public Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) {
    try {
      return cl == null ? null : cl.loadClass(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

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

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

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

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

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

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

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

  static public <A, B> Set<Map.Entry<A, B>> _entrySet(Map<A, B> map) {
    return map == null ? Collections.EMPTY_SET : map.entrySet();
  }

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

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

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

  static public int[] unnullForIteration(int[] l) {
    return l == null ? emptyIntArray() : l;
  }

  static public char[] unnullForIteration(char[] l) {
    return l == null ? emptyCharArray() : l;
  }

  static public double[] unnullForIteration(double[] l) {
    return l == null ? emptyDoubleArray() : l;
  }

  static public short[] unnullForIteration(short[] l) {
    return l == null ? emptyShortArray() : l;
  }

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

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

  static public <A> A[] unnullForIteration(A[] a) {
    return a == null ? (A[]) emptyObjectArray() : a;
  }

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

  static public Pt unnullForIteration(Pt p) {
    return p == null ? new Pt() : p;
  }

  static public Symbol unnullForIteration(Symbol s) {
    return s == null ? emptySymbol() : s;
  }

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

  static public long unnullForIteration(Long l) {
    return l == null ? 0L : l;
  }

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

  static public <A extends JComponent> A jtransparent(final A a) {
    {
      swing(new Runnable() {

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

        public String toString() {
          return "a.setOpaque(false);";
        }
      });
    }
    return a;
  }

  static public JPanel borderLayoutPanel() {
    return jpanel(new BorderLayout());
  }

  static public char firstChar(String s) {
    return s.charAt(0);
  }

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

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

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

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

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

  static public File loadImageAsFile(String snippetIDOrURL) {
    try {
      if (isURL(snippetIDOrURL))
        throw fail("not implemented");
      if (!isSnippetID(snippetIDOrURL))
        throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
      String snippetID = "" + parseSnippetID(snippetIDOrURL);
      File file = imageSnippetCacheFile(snippetID);
      if (fileSize(file) > 0)
        return file;
      String imageURL = snippetImageURL_noHttps(snippetID);
      System.err.println("Loading image: " + imageURL);
      byte[] data = loadBinaryPage(imageURL);
      saveBinaryFile(file, data);
      return file;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File DiskSnippetCache_file(long snippetID) {
    return new File(getGlobalCache(), "data_" + snippetID + ".jar");
  }

  public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
    File file = DiskSnippetCache_file(snippetID);
    return file.exists() ? file : null;
  }

  public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
    saveBinaryFile(DiskSnippetCache_file(snippetID), data);
  }

  static public byte[] loadDataSnippetImpl(String snippetID) throws IOException {
    byte[] data;
    try {
      URL url = new URL(dataSnippetLink(snippetID));
      print("Loading library: " + hideCredentials(url));
      try {
        data = loadBinaryPage(url.openConnection());
      } catch (RuntimeException e) {
        data = null;
      }
      if (data == null || data.length == 0) {
        url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID));
        print("Loading library: " + hideCredentials(url));
        data = loadBinaryPage(url.openConnection());
      }
      print("Bytes loaded: " + data.length);
    } catch (FileNotFoundException e) {
      throw new IOException("Binary snippet #" + snippetID + " not found or not public");
    }
    return data;
  }

  static public long fileSize(String path) {
    return getFileSize(path);
  }

  static public long fileSize(File f) {
    return getFileSize(f);
  }

  static public File loadDataSnippetToFile(String snippetID) {
    try {
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.loadLibrary(snippetID);
      return loadDataSnippetToFile_noResourceLoader(snippetID);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File loadDataSnippetToFile_noResourceLoader(String snippetID) {
    try {
      snippetID = fsI(snippetID);
      File f = DiskSnippetCache_file(parseSnippetID(snippetID));
      List<URL> urlsTried = new ArrayList();
      List<Throwable> errors = new ArrayList();
      try {
        URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
        print("Loading library: " + hideCredentials(url));
        try {
          loadBinaryPageToFile(openConnection(url), f);
          if (fileSize(f) == 0)
            throw fail();
        } catch (Throwable e) {
          errors.add(e);
          url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID)));
          print(e);
          print("Trying other server: " + hideCredentials(url));
          loadBinaryPageToFile(openConnection(url), f);
          print("Got bytes: " + fileSize(f));
        }
        if (fileSize(f) == 0)
          throw fail();
        System.err.println("Bytes loaded: " + fileSize(f));
      } catch (Throwable e) {
        errors.add(e);
        throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
      }
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] isGIF_magic = bytesFromHex("47494638");

  static public boolean isGIF(byte[] data) {
    return byteArrayStartsWith(data, isGIF_magic);
  }

  static public boolean isGIF(File f) {
    return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
  }

  static public <A> void setVar(IVar<A> v, A value) {
    if (v != null)
      v.set(value);
  }

  static public <A> IVF1<A> setVar(IVar<A> v) {
    return a -> {
      if (v != null)
        v.set(a);
    };
  }

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

  static public String actualUserHome_value;

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

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

  static public boolean possibleMD5(String s) {
    return isMD5(s);
  }

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

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

  static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
    while (it.hasNext()) {
      ping();
      pcallF_minimalExceptionHandling(it.next(), args);
    }
  }

  static public Set vm_busListeners_live_cache;

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

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

  static public Map<String, Set> vm_busListenersByMessage_live_cache;

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

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

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

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

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

  static public String n2(AtomicLong l) {
    return n2(l.get());
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public <A> List<A> immutableEmptyList() {
    return Collections.emptyList();
  }

  static public short[] emptyShortArray = new short[0];

  static public short[] emptyShortArray() {
    return emptyShortArray;
  }

  static public <A, B> Map<A, B> immutableEmptyMap() {
    return Collections.emptyMap();
  }

  static public JPanel jpanel(LayoutManager layout) {
    return swingNu(JPanel.class, layout);
  }

  static public JPanel jpanel() {
    return swingNu(JPanel.class);
  }

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

  static public Class classForName(String name) {
    return classForName(name, null);
  }

  static public Class classForName(String name, Object classFinder) {
    if (classForName_cache == null || classFinder != null)
      return classForName_uncached(name, classFinder);
    Class c = classForName_cache.get(name);
    if (c == null)
      classForName_cache.put(name, c = classForName_uncached(name, null));
    return c;
  }

  static public Class classForName_uncached(String name, Object classFinder) {
    try {
      if (classFinder != null)
        return (Class) callF(classFinder, name);
      return Class.forName(name);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  static public <A> A nuObjectWithoutArguments(Class<A> c) {
    try {
      if (nuObjectWithoutArguments_cache == null)
        return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
      Constructor m = nuObjectWithoutArguments_cache.get(c);
      if (m == null)
        nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
      return (A) m.newInstance();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

  static public File imageSnippetCacheFile(String snippetID) {
    File dir = imageSnippetsCacheDir();
    if (!loadBufferedImage_useImageCache)
      return null;
    return new File(dir, parseSnippetID(snippetID) + ".png");
  }

  static public String snippetImageURL_noHttps(String snippetID) {
    return snippetImageURL_noHttps(snippetID, "png");
  }

  static public String snippetImageURL_noHttps(String snippetID, String contentType) {
    return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/");
  }

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

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

  static public byte[] loadBinaryPage(String url) {
    try {
      print("Loading " + url);
      return loadBinaryPage(loadPage_openConnection(new URL(url)));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] loadBinaryPage(URLConnection con) {
    try {
      Map<String, String> extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders);
      setHeaders(con);
      for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
      return loadBinaryPage_noHeaders(con);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] loadBinaryPage_noHeaders(URLConnection con) {
    try {
      ByteArrayOutputStream buf = new ByteArrayOutputStream();
      InputStream inputStream = con.getInputStream();
      loadBinaryPage_responseHeaders.set(con.getHeaderFields());
      long len = 0;
      try {
        len = con.getContentLength();
      } catch (Throwable e) {
        printStackTrace(e);
      }
      int n = 0;
      while (true) {
        int ch = inputStream.read();
        if (ch < 0)
          break;
        buf.write(ch);
        if (++n % 100000 == 0)
          println("  " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
      }
      inputStream.close();
      return buf.toByteArray();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static byte[] saveBinaryFile(String fileName, byte[] contents) {
    try {
      File file = new File(fileName);
      File parentFile = file.getParentFile();
      if (parentFile != null)
        parentFile.mkdirs();
      String tempFileName = fileName + "_temp";
      FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
      fileOutputStream.write(contents);
      fileOutputStream.close();
      if (file.exists() && !file.delete())
        throw new IOException("Can't delete " + fileName);
      if (!new File(tempFileName).renameTo(file))
        throw new IOException("Can't rename " + tempFileName + " to " + fileName);
      vmBus_send("wroteFile", file);
      return contents;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] saveBinaryFile(File fileName, byte[] contents) {
    return saveBinaryFile(fileName.getPath(), contents);
  }

  static public File getGlobalCache() {
    File file = new File(javaxCachesDir(), "Binary Snippets");
    file.mkdirs();
    return file;
  }

  static public String dataSnippetLink(String snippetID) {
    long id = parseSnippetID(snippetID);
    if (id >= 1100000 && id < 1200000)
      return imageServerURL() + id;
    if (id >= 1200000 && id < 1300000) {
      String pw = muricaPassword();
      if (empty(pw))
        throw fail("Please set 'murica password by running #1008829");
      return "https://botcompany.de/files/" + id + "?_pass=" + pw;
    }
    return fileServerURL() + "/" + id;
  }

  static public String tb_mainServer_default = "https://code.botcompany.de:9898";

  static public Object tb_mainServer_override;

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

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

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

  static public <B, A extends B> A addAndReturn(Collection<B> c, A a) {
    if (c != null)
      c.add(a);
    return a;
  }

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

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

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

  static public boolean byteArrayStartsWith(byte[] a, byte[] b) {
    if (a == null || b == null)
      return false;
    if (a.length < b.length)
      return false;
    for (int i = 0; i < b.length; i++) if (a[i] != b[i])
      return false;
    return true;
  }

  static public byte[] loadBeginningOfBinaryFile(File file, int maxBytes) {
    return loadBinaryFilePart(file, 0, maxBytes);
  }

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

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

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

  static public boolean isMD5(String s) {
    return l(s) == 32 && isLowerHexString(s);
  }

  static public Object pcallF_minimalExceptionHandling(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable e) {
      System.out.println(getStackTrace(e));
      _storeException(e);
    }
    return null;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public int loadPage_defaultTimeout = 60000;

  static public ThreadLocal<String> loadPage_charset = new ThreadLocal();

  static public boolean loadPage_allowGzip = true, loadPage_debug;

  static public boolean loadPage_anonymous = false;

  static public int loadPage_verboseness = 100000;

  static public int loadPage_retries = 1;

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

  static volatile public int loadPage_forcedTimeout;

  static public ThreadLocal<Integer> loadPage_forcedTimeout_byThread = new ThreadLocal();

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

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

  static public ThreadLocal<Long> loadPage_sizeLimit = 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 (!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 (loadPage_debug)
          print(exceptionToStringShort(e));
        if (tries < loadPage_retries - 1)
          sleepSeconds(1);
      }
      throw e;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadPage_preprocess(String url) {
    if (url.startsWith("tb/"))
      url = tb_mainServer() + "/" + url;
    if (url.indexOf("://") < 0)
      url = "http://" + url;
    return url;
  }

  static public String loadPage(String url) {
    try {
      url = loadPage_preprocess(url);
      if (!isTrue(loadPage_silent.get()))
        printWithTime("Loading: " + hideCredentials(url));
      return loadPageSilently(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadPage(URL url) {
    return loadPage(url.toExternalForm());
  }

  static public String loadPage(URLConnection con, URL url) throws IOException {
    return loadPage(con, url, true);
  }

  static public String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
    Map<String, String> extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
    Long limit = optPar(loadPage_sizeLimit);
    if (addHeaders)
      try {
        if (!loadPage_anonymous)
          setHeaders(con);
        if (loadPage_allowGzip)
          con.setRequestProperty("Accept-Encoding", "gzip");
        con.setRequestProperty("X-No-Cookies", "1");
        for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
      } catch (Throwable e) {
      }
    vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
    loadPage_responseHeaders.set(con.getHeaderFields());
    InputStream in = null;
    try {
      in = urlConnection_getInputStream(con);
      if (loadPage_debug)
        print("Put stream in map: " + currentThread());
      String contentType = con.getContentType();
      if (contentType == null) {
        throw new IOException("Page could not be read: " + hideCredentials(url));
      }
      String charset = loadPage_charset == null ? null : loadPage_charset.get();
      if (charset == null)
        charset = loadPage_guessCharset(contentType);
      if ("gzip".equals(con.getContentEncoding())) {
        if (loadPage_debug)
          print("loadPage: Using gzip.");
        in = newGZIPInputStream(in);
      }
      Reader r;
      try {
        r = new InputStreamReader(in, unquote(charset));
      } catch (UnsupportedEncodingException e) {
        print(toHex(utf8(charset)));
        throw e;
      }
      boolean silent = isTrue(loadPage_silent.get());
      StringBuilder buf = new StringBuilder();
      int n = 0;
      while (limit == null || n < limit) {
        ping();
        int ch = r.read();
        if (ch < 0)
          break;
        buf.append((char) ch);
        ++n;
        if (!silent && (n % loadPage_verboseness) == 0)
          print("  " + n + " chars read");
      }
      return buf.toString();
    } finally {
      if (loadPage_debug)
        print("loadPage done");
      vm_generalSubMap("URLConnection per thread").remove(currentThread());
      if (in != null)
        in.close();
    }
  }

  static public String loadPage_guessCharset(String contentType) {
    Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
    String match = m.matches() ? m.group(1) : null;
    if (loadPage_debug)
      print("loadPage: contentType=" + contentType + ", match: " + match);
    return or(match, "UTF-8");
  }

  static public URLConnection loadPage_openConnection(URL url) {
    URLConnection con = openConnection(url);
    int timeout = toInt(loadPage_forcedTimeout_byThread.get());
    if (timeout == 0)
      timeout = loadPage_forcedTimeout;
    if (timeout != 0)
      setURLConnectionTimeouts(con, loadPage_forcedTimeout);
    else
      setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
    return con;
  }

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

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

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

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

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

  static public <A> A println(A a) {
    return print(a);
  }

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

  static volatile public boolean muricaPassword_pretendNotAuthed = false;

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

  static public String fileServerURL() {
    return "https://botcompany.de/files";
  }

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

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

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

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

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

  static public byte[] loadBinaryFilePart(File file, long start, long end) {
    try {
      RandomAccessFile raf = new RandomAccessFile(file, "r");
      int n = toInt(min(raf.length(), end - start));
      byte[] buffer = new byte[n];
      try {
        raf.seek(start);
        raf.readFully(buffer, 0, n);
        return buffer;
      } finally {
        raf.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public <A> A[] dropLast(A[] a) {
    return dropLast(a, 1);
  }

  static public <A> A[] dropLast(A[] a, int n) {
    if (a == null)
      return null;
    n = Math.min(n, a.length);
    A[] b = arrayOfSameType(a, a.length - n);
    System.arraycopy(a, 0, b, 0, b.length);
    return b;
  }

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

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

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

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

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

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

  static public boolean isLowerHexString(String s) {
    for (int i = 0; i < l(s); i++) {
      char c = s.charAt(i);
      if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
      } else
        return false;
    }
    return true;
  }

  static public Throwable _storeException_value;

  static public void _storeException(Throwable e) {
    _storeException_value = e;
  }

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

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

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

  static public ClassLoader classLoaderForObject(Object o) {
    if (o instanceof ClassLoader)
      return ((ClassLoader) o);
    if (o == null)
      return null;
    return _getClass(o).getClassLoader();
  }

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

  static public boolean networkAllowanceTest(String url) {
    return isAllowed("networkAllowanceTest", url);
  }

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

  static public <A> A printWithTime(String s, A a) {
    print(hmsWithColons() + ": " + s, a);
    return a;
  }

  static public <A> A optPar(ThreadLocal<A> tl, A defaultValue) {
    A a = tl.get();
    if (a != null) {
      tl.set(null);
      return a;
    }
    return defaultValue;
  }

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

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

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

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

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

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

  static public Map vm_generalSubMap(Object name) {
    synchronized (vm_generalMap()) {
      Map map = (Map) (vm_generalMap_get(name));
      if (map == null)
        vm_generalMap_put(name, map = synchroMap());
      return map;
    }
  }

  static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
    return con.getInputStream();
  }

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

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

  static public String unquote(String s) {
    if (s == null)
      return null;
    if (startsWith(s, '[')) {
      int i = 1;
      while (i < s.length() && s.charAt(i) == '=') ++i;
      if (i < s.length() && s.charAt(i) == '[') {
        String m = s.substring(1, i);
        if (s.endsWith("]" + m + "]"))
          return s.substring(i + 1, s.length() - i - 1);
      }
    }
    if (s.length() > 1) {
      char c = s.charAt(0);
      if (c == '\"' || c == '\'') {
        int l = endsWith(s, c) ? s.length() - 1 : s.length();
        StringBuilder sb = new StringBuilder(l - 1);
        for (int i = 1; i < l; i++) {
          char ch = s.charAt(i);
          if (ch == '\\') {
            char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
            if (nextChar >= '0' && nextChar <= '7') {
              String code = "" + nextChar;
              i++;
              if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
                code += s.charAt(i + 1);
                i++;
                if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
                  code += s.charAt(i + 1);
                  i++;
                }
              }
              sb.append((char) Integer.parseInt(code, 8));
              continue;
            }
            switch(nextChar) {
              case '\"':
                ch = '\"';
                break;
              case '\\':
                ch = '\\';
                break;
              case 'b':
                ch = '\b';
                break;
              case 'f':
                ch = '\f';
                break;
              case 'n':
                ch = '\n';
                break;
              case 'r':
                ch = '\r';
                break;
              case 't':
                ch = '\t';
                break;
              case '\'':
                ch = '\'';
                break;
              case 'u':
                if (i >= l - 5) {
                  ch = 'u';
                  break;
                }
                int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
                sb.append(Character.toChars(code));
                i += 5;
                continue;
              default:
                ch = nextChar;
            }
            i++;
          }
          sb.append(ch);
        }
        return sb.toString();
      }
    }
    return s;
  }

  static public String toHex(byte[] bytes) {
    return bytesToHex(bytes);
  }

  static public String toHex(byte[] bytes, int ofs, int len) {
    return bytesToHex(bytes, ofs, len);
  }

  static public byte[] utf8(String s) {
    return toUtf8(s);
  }

  static public Matcher regexpMatcher(String pat, String s) {
    return compileRegexp(pat).matcher(unnull(s));
  }

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

  static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
    if (con.getConnectTimeout() == 0) {
      con.setConnectTimeout(toInt(timeout));
      if (con.getConnectTimeout() != timeout)
        print("Warning: URL connect timeout not set by JDK.");
    }
    if (con.getReadTimeout() == 0) {
      con.setReadTimeout(toInt(timeout));
      if (con.getReadTimeout() != timeout)
        print("Warning: URL read timeout not set by JDK.");
    }
    return con;
  }

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

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

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

  static public <A> A[] arrayOfSameType(A[] a, int n) {
    return newObjectArrayOfSameType(a, n);
  }

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

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

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

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

  static public <A> List<A> subList(List<A> l, IntRange r) {
    return subList(l, r.start, r.end);
  }

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

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

  static volatile public Object isAllowed_function;

  static volatile public boolean isAllowed_all = true;

  static public boolean isAllowed(String askingMethod, Object... args) {
    Object f = vm_generalMap_get("isAllowed_function");
    if (f != null && !isTrue(callF(f, askingMethod, args)))
      return false;
    return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
  }

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

  static public String hmsWithColons(long time) {
    return new SimpleDateFormat("HH:mm:ss").format(time);
  }

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

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

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

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

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

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

  static public int gzInputStream_defaultBufferSize = 65536;

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

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

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

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

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

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

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

  static public Map<String, java.util.regex.Pattern> compileRegexp_cache = syncMRUCache(10);

  static public java.util.regex.Pattern compileRegexp(String pat) {
    java.util.regex.Pattern p = compileRegexp_cache.get(pat);
    if (p == null) {
      compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
    }
    return p;
  }

  static public File javaxSecretDir_dir;

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

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

  static public File programDir_mine;

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

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

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

  static public <A> A[] newObjectArrayOfSameType(A[] a) {
    return newObjectArrayOfSameType(a, a.length);
  }

  static public <A> A[] newObjectArrayOfSameType(A[] a, int n) {
    return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
  }

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

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

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

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

  static public boolean even(BigInteger n) {
    return even(n.intValue());
  }

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

  static public Charset utf8charset_cache;

  static public Charset utf8charset() {
    if (utf8charset_cache == null)
      utf8charset_cache = utf8charset_load();
    return utf8charset_cache;
  }

  static public Charset utf8charset_load() {
    return Charset.forName("UTF-8");
  }

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

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

  static volatile public String caseID_caseID;

  static public String caseID() {
    return caseID_caseID;
  }

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

  final static public class _MethodCache {

    final public Class c;

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

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

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

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

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

  static public class GridCodec1 implements JavaCodec<BufferedImage>, IFieldsToList {

    public BufferedImage stage0_image;

    public GridCodec1() {
    }

    public GridCodec1(BufferedImage stage0_image) {
      this.stage0_image = stage0_image;
    }

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

    final public GridCodec1 setRows(int rows) {
      return rows(rows);
    }

    public GridCodec1 rows(int rows) {
      this.rows = rows;
      return this;
    }

    final public int getRows() {
      return rows();
    }

    public int rows() {
      return rows;
    }

    public int rows = 20;

    static public GridCodec1 demo() {
      return new GridCodec1(defaultScreenshot());
    }

    public Matrix<Integer> stage1_matrix;

    public long dataBytes, dataChars;

    public Matrix<Matrix<Integer>> stage2_grid;

    public JE_CompressEachElementIndividually<List<Integer>> strat;

    public JECompressionSearch<List<List<Integer>>> search;

    public JECompressionSearch<List<List<Integer>>> forward() {
      assertNotNull(stage0_image);
      var m = stage1_matrix = imageToMatrix(stage0_image);
      dataBytes = m.nCells() * 4 + 2;
      dataChars = dataBytes * 2 + l("lInt(\"\")");
      print("Matrix ~ " + shorten_str(60, m));
      print("Trivial comp ~ " + (m.nCells() * 8));
      stage2_grid = matrixToMNGrid_rows(m, rows);
      List<List<Integer>> stage3_cells = matrixOfMatricesToListOfLists(stage2_grid);
      search = jeCompressionSearch(stage3_cells, dataChars);
      strat = new JE_CompressEachElementIndividually<List<Integer>>().elementCompressionStrategy(() -> new JE_RepElement()).onCompressionFail(ints -> javaObjectToIJavaExpr(ints));
      search.addStrategy(strat);
      return search;
    }

    public String stats() {
      return strat == null ? null : strat.stats();
    }

    public JECompressionSearch<List<List<Integer>>>.Submission winner() {
      return search == null ? null : search.bestSubmission();
    }

    public ICachedJavaXExpr<List<List<Integer>>> winnerCodeWithoutPostProcessing() {
      return rCallF(winner(), __1 -> __1 == null ? null : __1.decompressor());
    }

    public ICachedJavaXExpr<BufferedImage> winnerCode() {
      var innerWinner = winnerCodeWithoutPostProcessing();
      if (innerWinner == null)
        return null;
      return addPostProcessing(innerWinner);
    }

    public List<Integer> cellWidths() {
      return lambdaMapMethod(__32 -> __32.getWidth(), rowToList(stage2_grid, 0));
    }

    public List<Integer> cellHeights() {
      return lambdaMapMethod(__33 -> __33.getHeight(), colToList(stage2_grid, 0));
    }

    public ICachedJavaXExpr<BufferedImage> addPostProcessing(ICachedJavaXExpr<List<List<Integer>>> inner) {
      List<Integer> cellWidths = cellWidths();
      List<Integer> cellHeights = cellHeights();
      return new AbstractJavaXExpr<BufferedImage>() {

        public FunctionCall javaConstruct() {
          return functionCall("gridLOLToImage", toJava(cellWidths), toJava(cellHeights), inner);
        }

        public String toString() {
          return str(javaConstruct());
        }

        public BufferedImage quickEval() {
          return gridLOLToImage(cellWidths, cellHeights, inner.quickEval());
        }
      };
    }

    public BufferedImage renderCellsLinearly() {
      return mergeBufferedImagesHorizontally(map(__48 -> intMatrixToImage(__48), matrixToList(stage2_grid)));
    }

    public void drawOverlay(ImageSurface is, Graphics2D g) {
      try {
        double zoom = is.getZoomX();
        List<Integer> cellWidths = cellWidths();
        List<Integer> cellHeights = cellHeights();
        List<Integer> cellX1s = partialSums_firstIs0(cellWidths);
        List<Integer> cellY1s = partialSums_firstIs0(cellHeights);
        for (int y = 0; y < l(cellHeights); y++) for (int x = 0; x < l(cellWidths); x++) if (strat.isElementCompressed(y * l(cellWidths) + x)) {
          Rect r = rectFromPoints(cellX1s.get(x), cellY1s.get(y), cellX1s.get(x + 1), cellY1s.get(y + 1));
          r = scaleRect(r, zoom);
          fillRect(g, r, colorWithAlpha(Color.GREEN, .5));
        }
      } catch (Throwable __e) {
        printStackTrace(__e);
      }
    }
  }

  static public class Symbol implements CharSequence {

    public String text;

    public Symbol() {
    }

    public Symbol(String text, boolean dummy) {
      this.text = text;
    }

    public int hashCode() {
      return _hashCode(text);
    }

    public String toString() {
      return text;
    }

    public boolean equals(Object o) {
      return this == o;
    }

    public int length() {
      return text.length();
    }

    public char charAt(int index) {
      return text.charAt(index);
    }

    public CharSequence subSequence(int start, int end) {
      return text.substring(start, end);
    }
  }

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

    public Var() {
    }

    public Var(A v) {
      this.v = v;
    }

    public A v;

    public synchronized void set(A a) {
      if (v != a) {
        v = a;
        notifyAll();
      }
    }

    public synchronized A get() {
      return v;
    }

    public synchronized boolean has() {
      return v != null;
    }

    public void clear() {
      set(null);
    }

    public String toString() {
      return str(this.get());
    }
  }

  static public class BetterThread extends Thread {

    public Runnable target;

    public BetterThread(Runnable target) {
      this.target = target;
      _created();
    }

    public BetterThread(Runnable target, String name) {
      super(name);
      this.target = target;
      _created();
    }

    public void _created() {
      vmBus_send("threadCreated", this);
    }

    public void run() {
      try {
        try {
          vmBus_send("threadStarted", this);
          if (target != null)
            target.run();
        } finally {
          vmBus_send("threadEnded", this);
        }
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public Runnable getTarget() {
      return target;
    }
  }

  static public class IIImageSurface extends ImageSurface {

    public BWIntegralImage ii;

    public IIImageSurface() {
    }

    public IIImageSurface(BWIntegralImage ii, BufferedImage img) {
      super(img);
      this.ii = ii;
    }

    public void drawImageItself(int w, int h, Graphics2D g) {
      if (ii == null) {
        super.drawImageItself(w, h, g);
        return;
      }
      int iw = getZoomedWidth(), ih = getZoomedHeight();
      Rect r = toRect(getVisibleRect());
      var scaled = scaledGrayImageFromBWIntegralImage_clip(ii, doubleRatio(iw, ii.getWidth()), r);
      g.drawImage(scaled, r.x, r.y, null);
    }

    public void setImage(BWIntegralImage ii, BufferedImage img) {
      this.ii = ii;
      super.setImage(img);
    }
  }

  static public class ImageSurface extends Surface {

    public BufferedImage image;

    public double zoomX = 1, zoomY = 1, zoomFactor = 1.5;

    public Rectangle selection;

    public List tools = new ArrayList();

    public Object overlay;

    public Runnable onSelectionChange;

    static public boolean verbose = false;

    public boolean noMinimumSize = true;

    public String titleForUpload;

    public Object onZoom;

    public boolean specialPurposed = false;

    public boolean zoomable = true;

    public boolean noAlpha = false;

    public Object interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR;

    public Object onNewImage;

    public BufferedImage imageToDraw;

    public File file;

    public ImageSurface() {
      this(dummyImage());
    }

    static public BufferedImage dummyImage() {
      return new RGBImage(1, 1, new int[] { 0xFFFFFF }).getBufferedImage();
    }

    public ImageSurface(MakesBufferedImage image) {
      this(image != null ? image.getBufferedImage() : dummyImage());
    }

    public ImageSurface(BufferedImage image) {
      setImage(image);
      clearSurface = false;
      componentPopupMenu2(this, ImageSurface_popupMenuMaker());
      new ImageSurfaceSelector(this);
      jHandleFileDrop(this, new VF1<File>() {

        public void get(File f) {
          try {
            setImage(loadBufferedImage(f));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "setImage(loadBufferedImage(f))";
        }
      });
    }

    public ImageSurface(RGBImage image, double zoom) {
      this(image);
      setZoom(zoom);
    }

    public void fillPopupMenu(JPopupMenu menu, final Point point) {
      if (zoomable) {
        JMenuItem miZoomReset = new JMenuItem("Zoom 100%");
        miZoomReset.addActionListener(new ActionListener() {

          public void actionPerformed(ActionEvent evt) {
            setZoom(1.0);
            centerPoint(point);
          }
        });
        menu.add(miZoomReset);
        JMenuItem miZoomIn = new JMenuItem("Zoom in");
        miZoomIn.addActionListener(new ActionListener() {

          public void actionPerformed(ActionEvent evt) {
            zoomIn(zoomFactor);
            centerPoint(point);
          }
        });
        menu.add(miZoomIn);
        JMenuItem miZoomOut = new JMenuItem("Zoom out");
        miZoomOut.addActionListener(new ActionListener() {

          public void actionPerformed(ActionEvent evt) {
            zoomOut(zoomFactor);
            centerPoint(point);
          }
        });
        menu.add(miZoomOut);
        JMenuItem miZoomToWindow = new JMenuItem("Zoom to window");
        miZoomToWindow.addActionListener(new ActionListener() {

          public void actionPerformed(ActionEvent evt) {
            zoomToDisplaySize();
          }
        });
        menu.add(miZoomToWindow);
        addMenuItem(menu, "Show full screen", new Runnable() {

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

          public String toString() {
            return "showFullScreen()";
          }
        });
        addMenuItem(menu, "Point: " + point.x + "," + point.y + " (image: " + image.getWidth() + "*" + image.getHeight() + ")", null);
        menu.addSeparator();
      }
      addMenuItem(menu, "Load image...", new Runnable() {

        public void run() {
          try {
            selectFile("Load image", new VF1<File>() {

              public void get(File f) {
                try {
                  setImage(loadImage2(f));
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "setImage(loadImage2(f))";
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "selectFile(\"Load image\",\r\n      new VF1<File>() { public void get(File f) cte...";
        }
      });
      addMenuItem(menu, "Save image...", new Runnable() {

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

        public String toString() {
          return "saveImage()";
        }
      });
      addMenuItem(menu, "Upload image...", new Runnable() {

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

        public String toString() {
          return "uploadTheImage()";
        }
      });
      addMenuItem(menu, "Copy image to clipboard", new Runnable() {

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

        public String toString() {
          return "copyImageToClipboard(getImage())";
        }
      });
      if (!specialPurposed) {
        addMenuItem(menu, "Paste image from clipboard", new Runnable() {

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

          public String toString() {
            return "loadFromClipboard()";
          }
        });
        addMenuItem(menu, "Load image snippet...", new Runnable() {

          public void run() {
            try {
              selectImageSnippet(new VF1<String>() {

                public void get(String imageID) {
                  try {
                    setImage(loadImage2(imageID));
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "setImage(loadImage2(imageID))";
                }
              });
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "selectImageSnippet(new VF1<String>() { public void get(String imageID) ctex {...";
          }
        });
      }
      if (selection != null)
        addMenuItem(menu, "Crop", new Runnable() {

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

          public String toString() {
            return "crop()";
          }
        });
      if (!specialPurposed)
        addMenuItem(menu, "No image", new Runnable() {

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

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

    public void noImage() {
      setImage((BufferedImage) null);
    }

    public void crop() {
      if (selection == null)
        return;
      BufferedImage img = cloneClipBufferedImage(getImage(), selection);
      selection = null;
      setImage(img);
    }

    public void loadFromClipboard() {
      BufferedImage img = getImageFromClipboard();
      if (img != null)
        setImage(img);
    }

    public void saveImage() {
      RGBImage image = new RGBImage(getImage(), null);
      JFileChooser fileChooser = new JFileChooser(getProgramDir());
      if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        try {
          image.save(file = fileChooser.getSelectedFile());
        } catch (IOException e) {
          popup(e);
        }
      }
    }

    public void drawImageItself(int w, int h, Graphics2D g) {
      int iw = getZoomedWidth(), ih = getZoomedHeight();
      if (interpolationMode == RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR || zoomX >= 1 || zoomY >= 1)
        g.drawImage(image, 0, 0, iw, ih, null);
      else
        g.drawImage(resizeImage(image, iw, ih), 0, 0, null);
    }

    public void render(int w, int h, Graphics2D g) {
      if (verbose)
        _print("render");
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolationMode);
      g.setColor(Color.white);
      BufferedImage image = or(imageToDraw, this.image);
      if (image == null)
        g.fillRect(0, 0, w, h);
      else {
        boolean alpha = !noAlpha && hasTransparency(image);
        if (alpha)
          g.fillRect(0, 0, w, h);
        drawImageItself(w, h, g);
        int iw = getZoomedWidth(), ih = getZoomedHeight();
        if (!alpha) {
          g.fillRect(iw, 0, w - iw, h);
          g.fillRect(0, ih, iw, h - ih);
        }
      }
      if (overlay != null) {
        if (verbose)
          _print("render overlay");
        pcallF(overlay, g);
      }
      if (selection != null) {
        if (verbose)
          _print("render selection");
        drawSelectionRect(g, selection, Color.green, Color.white);
      }
    }

    public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white) {
      drawSelectionRect(g, selection, green, white, zoomX, zoomY);
    }

    public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white, double zoomX, double zoomY) {
      g.setColor(green);
      int top = (int) (selection.y * zoomY);
      int bottom = (int) ((selection.y + selection.height) * zoomY);
      int left = (int) (selection.x * zoomX);
      int right = (int) ((selection.x + selection.width) * zoomX);
      g.drawRect(left - 1, top - 1, right - left + 1, bottom - top + 1);
      g.setColor(white);
      g.drawRect(left - 2, top - 2, right - left + 3, bottom - top + 3);
    }

    public ImageSurface setZoom(double zoom) {
      setZoom(zoom, zoom);
      return this;
    }

    public void setZoom(double zoomX, double zoomY) {
      if (this.zoomX == zoomX && this.zoomY == zoomY)
        return;
      if (verbose)
        _print("Setting zoom");
      this.zoomX = zoomX;
      this.zoomY = zoomY;
      revalidate();
      repaint();
      centerPoint(new Point(getImage().getWidth() / 2, getImage().getHeight() / 2));
      pcallF(onZoom);
    }

    public Dimension getMinimumSize() {
      if (noMinimumSize)
        return new Dimension(1, 1);
      int w = getZoomedWidth();
      int h = getZoomedHeight();
      Dimension min = super.getMinimumSize();
      return new Dimension(Math.max(w, min.width), Math.max(h, min.height));
    }

    public int getZoomedHeight() {
      return (int) (image.getHeight() * zoomY);
    }

    public int getZoomedWidth() {
      return (int) (image.getWidth() * zoomX);
    }

    public void setImage(MakesBufferedImage image) {
      setImage(image == null ? null : image.getBufferedImage());
    }

    public void setImage(final BufferedImage img) {
      {
        swing(new Runnable() {

          public void run() {
            try {
              BufferedImage newImage = img != null ? img : dummyImage();
              BufferedImage oldImage = image;
              image = newImage;
              if (!imagesHaveSameSize(oldImage, newImage)) {
                if (verbose)
                  _print("New image size");
                revalidate();
              }
              repaint();
              pcallF(onNewImage);
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "BufferedImage newImage = img != null ? img : dummyImage();\r\n      BufferedIma...";
          }
        });
      }
    }

    public void setImageAndZoomToDisplay(BufferedImage img) {
      setImage(img);
      zoomToDisplaySize();
    }

    public BufferedImage getImage() {
      return image;
    }

    public double getZoomX() {
      return zoomX;
    }

    public double getZoomY() {
      return zoomY;
    }

    public Dimension getPreferredSize() {
      return new Dimension(getZoomedWidth(), getZoomedHeight());
    }

    public JScrollPane makeScrollPane() {
      JScrollPane scrollPane = new JScrollPane(this);
      scrollPane.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
      return scrollPane;
    }

    public void zoomToWindow() {
      zoomToDisplaySize();
    }

    public void zoomToDisplaySize() {
      swing(new Runnable() {

        public void run() {
          try {
            if (image == null)
              return;
            Dimension display = getDisplaySize();
            double xRatio = (display.width - 5) / (double) image.getWidth();
            double yRatio = (display.height - 5) / (double) image.getHeight();
            setZoom(min(xRatio, yRatio));
            revalidate();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (image == null) return;\r\n    Dimension display = getDisplaySize();\r\n    do...";
        }
      });
    }

    final public Dimension getDisplaySize() {
      Container c = getParent();
      while (c != null) {
        if (c instanceof JScrollPane)
          return c.getSize();
        c = c.getParent();
      }
      return getSize();
    }

    public void setSelection(Rect r) {
      setSelection(toRectangle(r));
    }

    public void setSelection(Rectangle r) {
      if (neq(selection, r)) {
        selection = r;
        pcallF(onSelectionChange);
        repaint();
      }
    }

    public Rectangle getSelection() {
      return selection;
    }

    public RGBImage getRGBImage() {
      return new RGBImage(getImage());
    }

    public void centerPoint(Point p) {
      JScrollPane sp = enclosingScrollPane(this);
      if (sp == null)
        return;
      p = new Point((int) (p.x * getZoomX()), (int) (p.y * getZoomY()));
      final JViewport viewport = sp.getViewport();
      Dimension viewSize = viewport.getExtentSize();
      int x = max(0, p.x - viewSize.width / 2);
      int y = max(0, p.y - viewSize.height / 2);
      p = new Point(x, y);
      final Point _p = p;
      awtLater(new Runnable() {

        public void run() {
          try {
            viewport.setViewPosition(_p);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "viewport.setViewPosition(_p);";
        }
      });
    }

    public Pt pointFromEvent(MouseEvent e) {
      return pointFromComponentCoordinates(new Pt(e.getX(), e.getY()));
    }

    public Pt pointFromComponentCoordinates(Pt p) {
      return new Pt((int) (p.x / zoomX), (int) (p.y / zoomY));
    }

    public Pt pointToComponentCoordinates(double x, double y) {
      return new Pt((int) (x * zoomX), (int) (y * zoomY));
    }

    public void uploadTheImage() {
      call(hotwire("#1016427"), "go", getImage(), titleForUpload);
    }

    public void showFullScreen() {
      showFullScreenImageSurface(getImage());
    }

    public void zoomIn(double f) {
      setZoom(getZoomX() * f, getZoomY() * f);
    }

    public void zoomOut(double f) {
      setZoom(getZoomX() / f, getZoomY() / f);
    }

    public ImageSurface setFile(File f) {
      file = f;
      return this;
    }

    public void setOverlay(IVF1<Graphics2D> overlay) {
      this.overlay = overlay;
    }
  }

  static public VF2<ImageSurface, JPopupMenu> ImageSurface_popupMenuMaker() {
    return new VF2<ImageSurface, JPopupMenu>() {

      public void get(ImageSurface is, JPopupMenu menu) {
        try {
          Point p = is.pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint();
          is.fillPopupMenu(menu, p);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Point p = is.pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint();\r...";
      }
    };
  }

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

    public int maxSize = 10;

    public MRUCache() {
    }

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

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

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

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

  static public class MultiMap<A, B> {

    public Map<A, List<B>> data = new HashMap<A, List<B>>();

    public int fullSize;

    public MultiMap() {
    }

    public MultiMap(boolean useTreeMap) {
      if (useTreeMap)
        data = new TreeMap();
    }

    public MultiMap(MultiMap<A, B> map) {
      putAll(map);
    }

    public MultiMap(Map<A, List<B>> data) {
      this.data = data;
    }

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

    public void add(A key, B value) {
      put(key, value);
    }

    public void addAll(A key, Collection<B> values) {
      putAll(key, values);
    }

    public void addAllIfNotThere(A key, Collection<B> values) {
      synchronized (data) {
        for (B value : values) setPut(key, value);
      }
    }

    public void setPut(A key, B value) {
      synchronized (data) {
        if (!containsPair(key, value))
          put(key, value);
      }
    }

    public boolean containsPair(A key, B value) {
      synchronized (data) {
        return get(key).contains(value);
      }
    }

    public void putAll(Collection<A> keys, B value) {
      synchronized (data) {
        for (A key : unnullForIteration(keys)) put(key, value);
      }
    }

    public void putAll(A key, Collection<B> values) {
      synchronized (data) {
        if (nempty(values))
          getActual(key).addAll(values);
      }
    }

    public void putAll(Iterable<Pair<A, B>> pairs) {
      synchronized (data) {
        for (Pair<A, B> p : unnullForIteration(pairs)) put(p.a, p.b);
      }
    }

    public void removeAll(A key, Collection<B> values) {
      synchronized (data) {
        for (B value : values) remove(key, value);
      }
    }

    public List<B> get(A key) {
      synchronized (data) {
        List<B> list = data.get(key);
        return list == null ? Collections.<B>emptyList() : list;
      }
    }

    public List<B> getOpt(A key) {
      synchronized (data) {
        return data.get(key);
      }
    }

    public List<B> getAndClear(A key) {
      synchronized (data) {
        List<B> l = cloneList(data.get(key));
        remove(key);
        return l;
      }
    }

    public List<B> getActual(A key) {
      synchronized (data) {
        List<B> list = data.get(key);
        if (list == null)
          data.put(key, list = _makeEmptyList());
        return list;
      }
    }

    public void clean(A key) {
      synchronized (data) {
        List<B> list = data.get(key);
        if (list != null && list.isEmpty()) {
          fullSize -= l(list);
          data.remove(key);
        }
      }
    }

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

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

    public void remove(A key) {
      synchronized (data) {
        fullSize -= l(this.getOpt(key));
        data.remove(key);
      }
    }

    final public void remove(Pair<A, B> p) {
      removePair(p);
    }

    public void removePair(Pair<A, B> p) {
      if (p != null)
        remove(p.a, p.b);
    }

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

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

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

    public B getFirst(A key) {
      synchronized (data) {
        List<B> list = get(key);
        return list.isEmpty() ? null : list.get(0);
      }
    }

    public void addAll(MultiMap<A, B> map) {
      putAll(map);
    }

    public void putAll(MultiMap<A, B> map) {
      synchronized (data) {
        for (A key : map.keySet()) putAll(key, map.get(key));
      }
    }

    public void putAll(Map<A, B> map) {
      synchronized (data) {
        if (map != null)
          for (Map.Entry<A, B> e : map.entrySet()) put(e.getKey(), e.getValue());
      }
    }

    final public int keyCount() {
      return keysSize();
    }

    public int keysSize() {
      synchronized (data) {
        return l(data);
      }
    }

    final public int fullSize() {
      return size();
    }

    public int size() {
      synchronized (data) {
        return fullSize;
      }
    }

    public List<A> reverseGet(B b) {
      synchronized (data) {
        List<A> l = new ArrayList();
        for (A key : data.keySet()) if (data.get(key).contains(b))
          l.add(key);
        return l;
      }
    }

    public Map<A, List<B>> asMap() {
      synchronized (data) {
        return cloneMap(data);
      }
    }

    public boolean isEmpty() {
      synchronized (data) {
        return data.isEmpty();
      }
    }

    public List<B> _makeEmptyList() {
      return new ArrayList();
    }

    public Collection<List<B>> allLists() {
      synchronized (data) {
        return new ArrayList(data.values());
      }
    }

    public Collection<List<B>> values() {
      return allLists();
    }

    public List<B> allValues() {
      return concatLists(data.values());
    }

    public Object mutex() {
      return data;
    }

    public String toString() {
      return "mm" + str(data);
    }
  }

  static public interface Hasher<A> {

    public int hashCode(A a);

    public boolean equals(A a, A b);
  }

  static public interface IResourceLoader {

    public String loadSnippet(String snippetID);

    public String getTranspiled(String snippetID);

    public int getSnippetType(String snippetID);

    public String getSnippetTitle(String snippetID);

    public File loadLibrary(String snippetID);

    default public File pathToJavaXJar() {
      return pathToJavaxJar_noResourceLoader();
    }

    default public File getSnippetJar(String snippetID, String transpiledSrc) {
      return null;
    }
  }

  static final public class WeakHasherMap<K, V> extends AbstractMap<K, V> implements Map<K, V> {

    public Hasher hasher = null;

    final public boolean keyEquals(Object k1, Object k2) {
      return (hasher == null ? k1.equals(k2) : hasher.equals(k1, k2));
    }

    final public int keyHashCode(Object k1) {
      return (hasher == null ? k1.hashCode() : hasher.hashCode(k1));
    }

    final public WeakKey WeakKeyCreate(K k) {
      if (k == null)
        return null;
      else
        return new WeakKey(k);
    }

    final public WeakKey WeakKeyCreate(K k, ReferenceQueue<? super K> q) {
      if (k == null)
        return null;
      else
        return new WeakKey(k, q);
    }

    final public class WeakKey extends WeakReference<K> {

      public int hash;

      public WeakKey(K k) {
        super(k);
        hash = keyHashCode(k);
      }

      final public WeakKey create(K k) {
        if (k == null)
          return null;
        else
          return new WeakKey(k);
      }

      public WeakKey(K k, ReferenceQueue<? super K> q) {
        super(k, q);
        hash = keyHashCode(k);
      }

      final public WeakKey create(K k, ReferenceQueue<? super K> q) {
        if (k == null)
          return null;
        else
          return new WeakKey(k, q);
      }

      @Override
      public boolean equals(Object o) {
        if (o == null)
          return false;
        if (this == o)
          return true;
        if (!(o.getClass().equals(WeakKey.class)))
          return false;
        Object t = this.get();
        @SuppressWarnings("unchecked")
        Object u = ((WeakKey) o).get();
        if ((t == null) || (u == null))
          return false;
        if (t == u)
          return true;
        return keyEquals(t, u);
      }

      @Override
      public int hashCode() {
        return hash;
      }
    }

    public HashMap<WeakKey, V> hash;

    public ReferenceQueue<? super K> queue = new ReferenceQueue<K>();

    @SuppressWarnings("unchecked")
    final public void processQueue() {
      WeakKey wk;
      while ((wk = (WeakKey) queue.poll()) != null) {
        hash.remove(wk);
      }
    }

    public WeakHasherMap(int initialCapacity, float loadFactor) {
      hash = new HashMap<WeakKey, V>(initialCapacity, loadFactor);
    }

    public WeakHasherMap(int initialCapacity) {
      hash = new HashMap<WeakKey, V>(initialCapacity);
    }

    public WeakHasherMap() {
      hash = new HashMap<WeakKey, V>();
    }

    public WeakHasherMap(Hasher h) {
      hash = new HashMap<WeakKey, V>();
      hasher = h;
    }

    @Override
    public int size() {
      return entrySet().size();
    }

    @Override
    public boolean isEmpty() {
      return entrySet().isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
      @SuppressWarnings("unchecked")
      K kkey = (K) key;
      return hash.containsKey(WeakKeyCreate(kkey));
    }

    @Override
    public V get(Object key) {
      @SuppressWarnings("unchecked")
      K kkey = (K) key;
      return hash.get(WeakKeyCreate(kkey));
    }

    @Override
    public V put(K key, V value) {
      processQueue();
      return hash.put(WeakKeyCreate(key, queue), value);
    }

    @Override
    public V remove(Object key) {
      processQueue();
      @SuppressWarnings("unchecked")
      K kkey = (K) key;
      return hash.remove(WeakKeyCreate(kkey));
    }

    @Override
    public void clear() {
      processQueue();
      hash.clear();
    }

    @SuppressWarnings("TypeParameterShadowing")
    final public class Entry<K, V> implements Map.Entry<K, V> {

      public Map.Entry<WeakKey, V> ent;

      public K key;

      public Entry(Map.Entry<WeakKey, V> ent, K key) {
        this.ent = ent;
        this.key = key;
      }

      @Override
      public K getKey() {
        return key;
      }

      @Override
      public V getValue() {
        return ent.getValue();
      }

      @Override
      public V setValue(V value) {
        return ent.setValue(value);
      }

      final public boolean keyvalEquals(K o1, K o2) {
        return (o1 == null) ? (o2 == null) : keyEquals(o1, o2);
      }

      final public boolean valEquals(V o1, V o2) {
        return (o1 == null) ? (o2 == null) : o1.equals(o2);
      }

      @SuppressWarnings("NonOverridingEquals")
      public boolean equals(Map.Entry<K, V> e) {
        return (keyvalEquals(key, e.getKey()) && valEquals(getValue(), e.getValue()));
      }

      @Override
      public int hashCode() {
        V v;
        return (((key == null) ? 0 : keyHashCode(key)) ^ (((v = getValue()) == null) ? 0 : v.hashCode()));
      }
    }

    final public class EntrySet extends AbstractSet<Map.Entry<K, V>> {

      public Set<Map.Entry<WeakKey, V>> hashEntrySet = hash.entrySet();

      @Override
      public Iterator<Map.Entry<K, V>> iterator() {
        return new Iterator<Map.Entry<K, V>>() {

          public Iterator<Map.Entry<WeakKey, V>> hashIterator = hashEntrySet.iterator();

          public Map.Entry<K, V> next = null;

          @Override
          public boolean hasNext() {
            while (hashIterator.hasNext()) {
              Map.Entry<WeakKey, V> ent = hashIterator.next();
              WeakKey wk = ent.getKey();
              K k = null;
              if ((wk != null) && ((k = wk.get()) == null)) {
                continue;
              }
              next = new Entry<K, V>(ent, k);
              return true;
            }
            return false;
          }

          @Override
          public Map.Entry<K, V> next() {
            if ((next == null) && !hasNext())
              throw new NoSuchElementException();
            Map.Entry<K, V> e = next;
            next = null;
            return e;
          }

          @Override
          public void remove() {
            hashIterator.remove();
          }
        };
      }

      @Override
      public boolean isEmpty() {
        return !(iterator().hasNext());
      }

      @Override
      public int size() {
        int j = 0;
        for (Iterator<Map.Entry<K, V>> i = iterator(); i.hasNext(); i.next()) j++;
        return j;
      }

      @Override
      public boolean remove(Object o) {
        processQueue();
        if (!(o instanceof Map.Entry<?, ?>))
          return false;
        @SuppressWarnings("unchecked")
        Map.Entry<K, V> e = (Map.Entry<K, V>) o;
        Object ev = e.getValue();
        WeakKey wk = WeakKeyCreate(e.getKey());
        Object hv = hash.get(wk);
        if ((hv == null) ? ((ev == null) && hash.containsKey(wk)) : hv.equals(ev)) {
          hash.remove(wk);
          return true;
        }
        return false;
      }

      @Override
      public int hashCode() {
        int h = 0;
        for (Iterator<Map.Entry<WeakKey, V>> i = hashEntrySet.iterator(); i.hasNext(); ) {
          Map.Entry<WeakKey, V> ent = i.next();
          WeakKey wk = ent.getKey();
          Object v;
          if (wk == null)
            continue;
          h += (wk.hashCode() ^ (((v = ent.getValue()) == null) ? 0 : v.hashCode()));
        }
        return h;
      }
    }

    public Set<Map.Entry<K, V>> entrySet = null;

    @Override
    public Set<Map.Entry<K, V>> entrySet() {
      if (entrySet == null)
        entrySet = new EntrySet();
      return entrySet;
    }

    public K findKey(Object key) {
      processQueue();
      K kkey = (K) key;
      WeakKey wkey = WeakKeyCreate(kkey);
      WeakKey found = hashMap_findKey(hash, wkey);
      return found == null ? null : found.get();
    }
  }

  static public class proxy_InvocationHandler implements InvocationHandler {

    public Object target;

    public proxy_InvocationHandler() {
    }

    public proxy_InvocationHandler(Object target) {
      this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) {
      return call(target, method.getName(), unnull(args));
    }
  }

  static public interface IVar<A> extends IF0<A> {

    public void set(A a);

    public A get();

    default public boolean has() {
      return get() != null;
    }

    default public void clear() {
      set(null);
    }
  }

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

    public A a;

    public B b;

    public Pair() {
    }

    public Pair(A a, B b) {
      this.b = b;
      this.a = a;
    }

    public int hashCode() {
      return hashCodeFor(a) + 2 * hashCodeFor(b);
    }

    public boolean equals(Object o) {
      if (o == this)
        return true;
      if (!(o instanceof Pair))
        return false;
      Pair t = (Pair) o;
      return eq(a, t.a) && eq(b, t.b);
    }

    public String toString() {
      return "<" + a + ", " + b + ">";
    }

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

  static public class JE_CompressEachElementIndividually<El> extends AbstractCompressor_AnyType<ICachedJavaXExpr, List<El>> {

    final public JE_CompressEachElementIndividually<El> setElementCompressionStrategy(IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> elementCompressionStrategy) {
      return elementCompressionStrategy(elementCompressionStrategy);
    }

    public JE_CompressEachElementIndividually<El> elementCompressionStrategy(IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> elementCompressionStrategy) {
      this.elementCompressionStrategy = elementCompressionStrategy;
      return this;
    }

    final public IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> getElementCompressionStrategy() {
      return elementCompressionStrategy();
    }

    public IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> elementCompressionStrategy() {
      return elementCompressionStrategy;
    }

    public IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> elementCompressionStrategy;

    public List<CompressionSearch_AnyType<ICachedJavaXExpr<El>, El>> searches = new ArrayList();

    final public JE_CompressEachElementIndividually<El> setMakeLiteral(IF1<El, ICachedJavaXExpr> makeLiteral) {
      return makeLiteral(makeLiteral);
    }

    public JE_CompressEachElementIndividually<El> makeLiteral(IF1<El, ICachedJavaXExpr> makeLiteral) {
      this.makeLiteral = makeLiteral;
      return this;
    }

    final public IF1<El, ICachedJavaXExpr> getMakeLiteral() {
      return makeLiteral();
    }

    public IF1<El, ICachedJavaXExpr> makeLiteral() {
      return makeLiteral;
    }

    public IF1<El, ICachedJavaXExpr> makeLiteral;

    public BitSet compressedElementsBitSet = new BitSet();

    public JE_CompressEachElementIndividually<El> onCompressionFail(IF1<El, ICachedJavaXExpr> f) {
      makeLiteral = f;
      return this;
    }

    final public JE_CompressEachElementIndividually<El> setDebug(boolean debug) {
      return debug(debug);
    }

    public JE_CompressEachElementIndividually<El> debug(boolean debug) {
      this.debug = debug;
      return this;
    }

    final public boolean getDebug() {
      return debug();
    }

    public boolean debug() {
      return debug;
    }

    public boolean debug = false;

    public List<ICachedJavaXExpr> renderedElements = new ArrayList();

    public ICachedJavaXExpr renderedCode;

    public BitSet dirtyElements = new BitSet();

    public int size() {
      return l(inputData());
    }

    public int nNotLiteral() {
      return countPred(searches, search -> search.has());
    }

    public ICachedJavaXExpr getRenderedElement(int i) {
      if (metaGet("scaffolding") != null)
        scaffoldCalled(this, "getRenderedElement", i);
      if (contains(dirtyElements, i) || _get(renderedElements, i) == null) {
        remove(dirtyElements, i);
        var e = renderElement(i);
        listSet(renderedElements, i, e);
      }
      return renderedElements.get(i);
    }

    public ICachedJavaXExpr renderElement(int i) {
      var search = _get(searches, i);
      ICachedJavaXExpr comp = search == null ? null : search.get();
      if (comp != null) {
        synchronized (compressedElementsBitSet) {
          compressedElementsBitSet.set(i);
        }
        return comp;
      }
      ICachedJavaXExpr java = makeLiteral.get(_get(inputData(), i));
      metaSet(java, "gaveUp", this);
      return java;
    }

    public boolean dirty() {
      return nempty(dirtyElements) || l(renderedElements) < size();
    }

    public void flush() {
      if (!dirty())
        return;
      submit(code());
    }

    public List<ICachedJavaXExpr> codeForElements() {
      return countIteratorToList(__31 -> getRenderedElement(__31), size());
    }

    public ICachedJavaXExpr code() {
      if (dirty() || renderedCode == null) {
        List<ICachedJavaXExpr> els = codeForElements();
        int iNull = indexOf(els, null);
        if (iNull >= 0)
          throw fail("Null element: " + iNull + "/" + l(els));
        renderedCode = javaExpr(functionCall_list("ll", els), () -> mapQuickEval_javaExpr(els));
      }
      return renderedCode;
    }

    public void step0() {
      if (elementCompressionStrategy == null)
        return;
      probabilisticForEach(scheduler(), 1.0, 0.5, indexAsSideValue(inputData()), ivf1WithToString("Compress element", data -> {
        int i = data.sideValue();
        var subSearch = new CompressionSearch_AnyType<ICachedJavaXExpr<El>, El>(assertNotNull("childRegime", childRegime()), data.get(), 1);
        subSearch.onNewBest(() -> set(dirtyElements, i));
        listSet(searches, i, subSearch);
        subSearch.addStrategy(elementCompressionStrategy.get());
      }));
    }

    public String stats() {
      return renderVars("nNotLiteral", nNotLiteral() + " of " + size());
    }

    transient public IF0<CompressionRegime_AnyType<ICachedJavaXExpr<El>>> childRegime;

    public CompressionRegime_AnyType<ICachedJavaXExpr<El>> childRegime() {
      return childRegime != null ? childRegime.get() : childRegime_base();
    }

    final public CompressionRegime_AnyType<ICachedJavaXExpr<El>> childRegime_fallback(IF0<CompressionRegime_AnyType<ICachedJavaXExpr<El>>> _f) {
      return _f != null ? _f.get() : childRegime_base();
    }

    public CompressionRegime_AnyType<ICachedJavaXExpr<El>> childRegime_base() {
      return (CompressionRegime_AnyType) regime();
    }

    public boolean isElementCompressed(int i) {
      synchronized (compressedElementsBitSet) {
        return compressedElementsBitSet.get(i);
      }
    }
  }

  static abstract public class VF2<A, B> {

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

  static public interface IFieldsToList {

    public Object[] _fieldsToList();
  }

  static public interface ISetter<A> {

    public void set(A a);
  }

  static public class ImageSurfaceSelector extends MouseAdapter {

    public ImageSurface is;

    public Point startingPoint;

    public boolean enabled = true;

    static public boolean verbose = false;

    public ImageSurfaceSelector(ImageSurface is) {
      this.is = is;
      if (containsInstance(is.tools, ImageSurfaceSelector.class))
        return;
      is.tools.add(this);
      is.addMouseListener(this);
      is.addMouseMotionListener(this);
    }

    public void mousePressed(MouseEvent evt) {
      if (verbose)
        print("mousePressed");
      if (evt.getButton() != MouseEvent.BUTTON1)
        return;
      if (enabled)
        startingPoint = getPoint(evt);
    }

    public void mouseDragged(MouseEvent e) {
      if (verbose)
        print("mouseDragged");
      if (startingPoint != null) {
        Point endPoint = getPoint(e);
        Rectangle r = new Rectangle(startingPoint, new Dimension(endPoint.x - startingPoint.x + 1, endPoint.y - startingPoint.y + 1));
        normalize(r);
        r.width = min(r.width, is.getImage().getWidth() - r.x);
        r.height = min(r.height, is.getImage().getHeight() - r.y);
        is.setSelection(r);
      }
      if (verbose)
        print("mouseDragged done");
    }

    public static void normalize(Rectangle r) {
      if (r.width < 0) {
        r.x += r.width;
        r.width = -r.width;
      }
      if (r.height < 0) {
        r.y += r.height;
        r.height = -r.height;
      }
    }

    public void mouseReleased(MouseEvent e) {
      if (verbose)
        print("mouseReleased");
      mouseDragged(e);
      if (getPoint(e).equals(startingPoint))
        is.setSelection((Rectangle) null);
      startingPoint = null;
    }

    public Point getPoint(MouseEvent e) {
      return new Point((int) (e.getX() / is.getZoomX()), (int) (e.getY() / is.getZoomY()));
    }
  }

  abstract static public class Surface extends JPanel {

    public boolean clearSurface = true;

    public boolean clearOnce = false;

    public Surface() {
      setDoubleBuffered(false);
    }

    public Graphics2D createGraphics2D(int width, int height, Graphics g) {
      Graphics2D g2 = (Graphics2D) g;
      g2.setBackground(getBackground());
      if (clearSurface || clearOnce) {
        g2.clearRect(0, 0, width, height);
        clearOnce = false;
      }
      return g2;
    }

    public abstract void render(int w, int h, Graphics2D g);

    public void paintImmediately(int x, int y, int w, int h) {
      RepaintManager repaintManager = null;
      boolean save = true;
      if (!isDoubleBuffered()) {
        repaintManager = RepaintManager.currentManager(this);
        save = repaintManager.isDoubleBufferingEnabled();
        repaintManager.setDoubleBufferingEnabled(false);
      }
      super.paintImmediately(x, y, w, h);
      if (repaintManager != null)
        repaintManager.setDoubleBufferingEnabled(save);
    }

    public void paint(Graphics g) {
      Dimension d = getSize();
      Graphics2D g2 = createGraphics2D(d.width, d.height, g);
      render(d.width, d.height, g2);
      g2.dispose();
    }
  }

  static public boolean isAbstract(Class c) {
    return (c.getModifiers() & Modifier.ABSTRACT) != 0;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public List map(Map map, Object f) {
    List x = new ArrayList();
    if (map != null)
      for (Object _e : map.entrySet()) {
        ping();
        Map.Entry e = (Map.Entry) _e;
        x.add(callF(f, e.getKey(), e.getValue()));
      }
    return x;
  }

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

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

  static public Rect scaleRect(Rect r, double factorX, double factorY) {
    return rectFromPoints(iround(r.x * factorX), iround(r.y * factorY), iround(r.x2() * factorX), iround(r.y2() * factorY));
  }

  static public Rect scaleRect(Rect r, double factor) {
    return scaleRect(r, factor, factor);
  }

  static public Rect scaleRect(double factor, Rect r) {
    return scaleRect(r, factor);
  }

  static public DoubleRect scaleRect(DoubleRect r, double factorX, double factorY) {
    return doubleRect(r.x * factorX, r.y * factorY, r.w * factorX, r.h * factorY);
  }

  static public Color colorWithAlpha(Color c, double alpha) {
    return new Color(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, (float) clampZeroToOne(alpha));
  }

  static public Color colorWithAlpha(double alpha, Color c) {
    return colorWithAlpha(c, alpha);
  }

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

  static public BufferedImage scaledGrayImageFromBWIntegralImage_clip(BWIntegralImage img, double scalingFactor, Rect clip) {
    int w = clip.w, h = clip.h;
    int w1 = img.w, h1 = img.h;
    byte[] pixels = new byte[w * h];
    int i = 0;
    int xx2 = clip.x2(), yy2 = clip.y2();
    for (int y = clip.y; y < yy2; y++) for (int x = clip.x; x < xx2; x++) {
      int x1 = ifloor(x / scalingFactor), x2 = ifloor(max(x1 + 1, (x + 1) / scalingFactor));
      int y1 = ifloor(y / scalingFactor), y2 = ifloor(max(y1 + 1, (y + 1) / scalingFactor));
      int pixel = iround(img.getPixelAverage(x1, y1, x2, y2));
      pixels[i++] = clampToUByte(pixel);
    }
    return newGrayBufferedImage(w, h, pixels);
  }

  static public <A extends JComponent> void componentPopupMenu2(A component, final VF2<A, JPopupMenu> menuMaker) {
    final WeakReference<A> ref = new WeakReference<>(component);
    componentPopupMenu(component, new VF1<JPopupMenu>() {

      public void get(JPopupMenu menu) {
        try {
          callF(menuMaker, ref.get(), menu);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(menuMaker, ref!, menu);";
      }
    });
  }

  static public <A extends JComponent> A jHandleFileDrop(A c, final Object onDrop) {
    new DropTarget(c, new DropTargetAdapter() {

      public void drop(DropTargetDropEvent e) {
        try {
          Transferable tr = e.getTransferable();
          DataFlavor[] flavors = tr.getTransferDataFlavors();
          for (DataFlavor flavor : flavors) {
            if (flavor.isFlavorJavaFileListType()) {
              e.acceptDrop(e.getDropAction());
              File file = first((List<File>) tr.getTransferData(flavor));
              if (file != null && !isFalse(callF(onDrop, file)))
                e.dropComplete(true);
              return;
            }
          }
        } catch (Throwable __e) {
          printStackTrace(__e);
        }
        e.rejectDrop();
      }
    });
    return c;
  }

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

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

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

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

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

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

  static public void addMenuItem(JMenuBar menuBar, String text, Runnable action) {
    addMenuItem(menuBar, jmenuItem(text, action));
  }

  static public void addMenuItem(JMenuBar menuBar, JMenuItem menuItem) {
    addDirectMenuItem(menuBar, menuItem);
  }

  static public JFrame showFullScreen(JComponent c) {
    return showFullScreen(defaultFrameTitle(), c);
  }

  static public JFrame showFullScreen(final String title, final JComponent c) {
    return (JFrame) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
          if (!gd.isFullScreenSupported())
            throw fail("No full-screen mode supported!");
          boolean dec = JFrame.isDefaultLookAndFeelDecorated();
          if (dec)
            JFrame.setDefaultLookAndFeelDecorated(false);
          final JFrame window = new JFrame(title);
          window.setUndecorated(true);
          if (dec)
            JFrame.setDefaultLookAndFeelDecorated(true);
          registerEscape(window, new Runnable() {

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

            public String toString() {
              return "disposeWindow(window)";
            }
          });
          window.add(wrap(c));
          gd.setFullScreenWindow(window);
          for (int i = 100; i <= 1000; i += 100) awtLater(i, new Runnable() {

            public void run() {
              try {
                window.toFront();
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "window.toFront()";
            }
          });
          return window;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()\r\n      ...";
      }
    });
  }

  static public void selectFile(final String msg, VF1<File> action) {
    selectFile(msg, userDir(), action);
  }

  static public void selectFile(final String msg, final File defaultFile, VF1<File> action) {
    inputFilePath(msg, defaultFile, action);
  }

  static public void saveImage(File f, BufferedImage img) {
    if (hasJPEGExtension(f))
      saveJPG(f, img);
    else
      savePNG(f, img);
  }

  static public <A extends Image> A copyImageToClipboard(A img) {
    TransferableImage trans = new TransferableImage(img);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
    vmBus_send("newClipboardContents", img);
    print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
    return img;
  }

  static public JComponent selectImageSnippet(VF1<String> onSelect) {
    return selectSnippetID_v1(onSelect);
  }

  static public JComponent selectImageSnippet(String defaultID, VF1<String> onSelect) {
    return selectSnippetID_v1(defaultID, onSelect);
  }

  static public BufferedImage cloneClipBufferedImage(BufferedImage src, Rectangle clip) {
    return cloneBufferedImage(clipBufferedImage(src, clip));
  }

  static public BufferedImage cloneClipBufferedImage(BufferedImage src, Rect r) {
    return cloneBufferedImage(clipBufferedImage(src, r));
  }

  static public BufferedImage cloneClipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
    return cloneBufferedImage(clipBufferedImage(src, x, y, w, h));
  }

  static public BufferedImage getImageFromClipboard() {
    try {
      Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
      if (t == null)
        return null;
      List<File> l = (List<File>) (getTransferData(t, DataFlavor.javaFileListFlavor));
      if (nempty(l))
        return loadImage2(first(l));
      if (t.isDataFlavorSupported(DataFlavor.imageFlavor))
        return (BufferedImage) t.getTransferData(DataFlavor.imageFlavor);
      return imageFromDataURL(getTextFromClipboard());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void popup(final Throwable throwable) {
    popupError(throwable);
  }

  static public void popup(final String msg) {
    print(msg);
    SwingUtilities.invokeLater(new Runnable() {

      public void run() {
        JOptionPane.showMessageDialog(null, msg);
      }
    });
  }

  static public BufferedImage resizeImage(BufferedImage img, int newW, int newH) {
    return resizeImage(img, newW, newH, Image.SCALE_SMOOTH);
  }

  static public BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) {
    if (newW == img.getWidth() && newH == img.getHeight())
      return img;
    Image tmp = img.getScaledInstance(newW, newH, scaleType);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();
    return dimg;
  }

  static public BufferedImage resizeImage(BufferedImage img, int newW) {
    int newH = iround(img.getHeight() * (double) newW / img.getWidth());
    return resizeImage(img, newW, newH);
  }

  static public BufferedImage resizeImage(int newW, BufferedImage img) {
    return resizeImage(img, newW);
  }

  static public <A> A _print(String s, A a) {
    return print(s, a);
  }

  static public <A> A _print(A a) {
    return print(a);
  }

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

  static public boolean hasTransparency(BufferedImage img) {
    return img.getColorModel().hasAlpha();
  }

  static public <A extends Component> A revalidate(final A c) {
    if (c == null || !c.isShowing())
      return c;
    {
      swing(new Runnable() {

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

        public String toString() {
          return "// magic combo to actually relayout and repaint\r\n    c.revalidate();\r\n    c.r...";
        }
      });
    }
    return c;
  }

  static public void revalidate(JFrame f) {
    revalidate((Component) f);
  }

  static public void revalidate(JInternalFrame f) {
    revalidate((Component) f);
  }

  static public <A extends Component> A repaint(A c) {
    if (c != null)
      c.repaint();
    return c;
  }

  static public Dimension getMinimumSize(final Component c) {
    return c == null ? null : swing(new F0<Dimension>() {

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

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

  static public boolean imagesHaveSameSize(BufferedImage a, BufferedImage b) {
    return a != null && b != null && a.getWidth() == b.getWidth() && a.getHeight() == b.getHeight();
  }

  static public JScrollPane enclosingScrollPane(Component c) {
    while (c.getParent() != null && !(c.getParent() instanceof JViewport) && c.getParent().getComponentCount() == 1) c = c.getParent();
    if (!(c.getParent() instanceof JViewport))
      return null;
    c = c.getParent().getParent();
    return c instanceof JScrollPane ? (JScrollPane) c : null;
  }

  static public ImageSurface showFullScreenImageSurface(BufferedImage img) {
    ImageSurface is = jImageSurface(img);
    showFullScreen(jscroll_centered(disposeFrameOnClick(is)));
    return is;
  }

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

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

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

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

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

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

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

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

  static public <A, B> B second(Either<A, B> e) {
    return e == null ? null : e.bOpt();
  }

  static public <A, B> Map<A, B> putAll(Map<A, B> a, Map<? extends A, ? extends B> b) {
    if (a != null && b != null)
      a.putAll(b);
    return a;
  }

  static public <A, B> MultiMap<A, B> putAll(MultiMap<A, B> a, Map<? extends A, ? extends B> b) {
    if (a != null)
      a.putAll((Map) b);
    return a;
  }

  static public <A, B> Map<A, B> putAll(Map<A, B> a, Object... b) {
    if (a != null)
      litmap_impl(a, b);
    return a;
  }

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

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

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

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

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

  static public void remove(BitSet bs, int i) {
    bs.clear(i);
  }

  static public <A> A getAndClear(IVar<A> v) {
    A a = v.get();
    v.set(null);
    return a;
  }

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

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

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

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

  static public <A, B> int keysSize(MultiMap<A, B> mm) {
    return lKeys(mm);
  }

  static public <A> A reverseGet(List<A> l, int idx) {
    if (l == null || idx < 0)
      return null;
    int n = l(l);
    return idx < n ? l.get(n - 1 - idx) : null;
  }

  static public <A, B> Map<A, B> cloneMap(Map<A, B> map) {
    if (map == null)
      return new HashMap();
    synchronized (map) {
      return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
    }
  }

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

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

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

  static public <A, B> Collection<B> values(MultiMap<A, B> mm) {
    return mm == null ? emptyList() : concatLists(values(mm.data));
  }

  static public File loadLibrary(String snippetID) {
    return loadBinarySnippet(snippetID);
  }

  static public File pathToJavaxJar() {
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return rl.pathToJavaXJar();
    return pathToJavaxJar_noResourceLoader();
  }

  static public File pathToJavaxJar_noResourceLoader() {
    try {
      int x = latestInstalledJavaX();
      File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar");
      if (!xfile.isFile()) {
        print("Saving " + f2s(xfile));
        String url = x30JarServerURL();
        byte[] data = loadBinaryPage(url);
        if (data.length < 1000000)
          throw fail("Could not load " + url);
        saveBinaryFile(xfile.getPath(), data);
      }
      return xfile;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

  static public Method hashMap_findKey_method;

  static public <A, B> A hashMap_findKey(HashMap<A, B> map, Object key) {
    try {
      if (hashMap_findKey_method == null)
        hashMap_findKey_method = findMethodNamed(HashMap.class, "getNode");
      Map.Entry<A, B> entry = (Map.Entry) hashMap_findKey_method.invoke(map, hashMap_internalHash(key), key);
      return entry == null ? null : entry.getKey();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

  static public boolean containsInstance(Iterable i, Class c) {
    if (i != null)
      for (Object o : i) if (isInstanceX(c, o))
        return true;
    return false;
  }

  static public Color getBackground(final Component c) {
    return c == null ? null : swing(new F0<Color>() {

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

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

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

  static public DoubleRect doubleRect(double w, double h) {
    return new DoubleRect(0, 0, w, h);
  }

  static public DoubleRect doubleRect(double x, double y, double w, double h) {
    return new DoubleRect(x, y, w, h);
  }

  static public float clampZeroToOne(float x) {
    return x < 0 ? 0 : x > 1 ? 1 : x;
  }

  static public double clampZeroToOne(double x) {
    return x < 0 ? 0 : x > 1 ? 1 : x;
  }

  static public byte clampToUByte(long l) {
    return (byte) clamp(l, 0, 255);
  }

  static public BufferedImage newGrayBufferedImage(int w, int h) {
    return new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
  }

  static public BufferedImage newGrayBufferedImage(int w, int h, byte[] pixels) {
    return byteArrayToGrayBufferedImage(pixels, w, h);
  }

  static public boolean jmenuItem_newThreads = false;

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

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

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

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

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

  static public void addDirectMenuItem(JMenuBar mb, String text, Object action) {
    if (mb != null) {
      swing(new Runnable() {

        public void run() {
          try {
            addDirectMenuItem(mb, directJMenuItem(text, action));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "addDirectMenuItem(mb, directJMenuItem(text, action));";
        }
      });
    }
  }

  static public void addDirectMenuItem(Component c, String text, Object action) {
    addDirectMenuItem(addMenuBar(c), text, action);
  }

  static public void addDirectMenuItem(JMenuBar mb, JMenuItem menuItem) {
    if (mb != null) {
      swing(new Runnable() {

        public void run() {
          try {
            mb.add(menuItem);
            revalidate(mb);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "mb.add(menuItem);\r\n    revalidate(mb);";
        }
      });
    }
  }

  static public String defaultFrameTitle() {
    return autoFrameTitle();
  }

  static public void defaultFrameTitle(String title) {
    autoFrameTitle_value = title;
  }

  static public void registerEscape(JFrame frame, final Runnable r) {
    registerEscape_rootPane(frame.getRootPane(), r);
  }

  static public void inputFilePath(final String msg, final Object action) {
    inputFilePath(msg, userDir(), action);
  }

  static public void inputFilePath(final String msg, final File defaultFile, final Object action) {
    swingLater(new Runnable() {

      public void run() {
        try {
          final JTextField tfPath = jtextfield(f2s(or(defaultFile, userDir())));
          String title = joinStrings(" | ", msg, programName());
          JComponent form = showFormTitled(title, unnull(msg), centerAndEast(tfPath, jbutton("Browse...", new Runnable() {

            public void run() {
              try {
                JFileChooser fileChooser = new JFileChooser(getTextTrim(tfPath));
                if (fileChooser.showOpenDialog(tfPath) == JFileChooser.APPROVE_OPTION) {
                  tfPath.setText(fileChooser.getSelectedFile().getAbsolutePath());
                  tfPath.requestFocus();
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "JFileChooser fileChooser = new JFileChooser(getTextTrim(tfPath));\r\n        if...";
            }
          })), new Runnable() {

            public void run() {
              try {
                callF(action, new File(getTextTrim(tfPath)));
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "callF(action, new File(getTextTrim(tfPath)))";
            }
          });
          renameSubmitButton(form, "OK");
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "final JTextField tfPath = jtextfield(f2s(or(defaultFile, userDir())));\r\n    S...";
      }
    });
  }

  static public boolean hasJPEGExtension(File f) {
    return ewicOneOf(fileName(f), ".jpg", ".jpeg");
  }

  static public void saveJPG(BufferedImage img, File file) {
    try {
      if (!ImageIO.write(img, "jpeg", mkdirsFor(file))) {
        print("Reconstructing image for saving JPEG");
        img = reconstructBufferedImage(img);
        if (!ImageIO.write(img, "jpeg", file))
          throw fail("Couldn't write JPEG: " + file + " (" + img + ")");
      }
      vmBus_send("wroteFile", file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void saveJPG(File file, BufferedImage img) {
    try {
      saveJPG(img, file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void savePNG(BufferedImage img, File file) {
    try {
      File tempFile = new File(file.getPath() + "_temp");
      CriticalAction ca = beginCriticalAction("Save " + f2s(file));
      try {
        ImageIO.write(img, "png", mkdirsFor(tempFile));
        file.delete();
        tempFile.renameTo(file);
      } finally {
        ca.done();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void savePNG(File file, BufferedImage img) {
    savePNG(img, file);
  }

  static public void savePNG(File file, RGBImage img) {
    savePNG(file, img.getBufferedImage());
  }

  static public JComponent selectSnippetID_v1(final VF1<String> onSelect) {
    return selectSnippetID_v1("#", onSelect);
  }

  static public JComponent selectSnippetID_v1(String defaultID, final VF1<String> onSelect) {
    final JTextField tfSnippetID = jtextfield(defaultID);
    if (eq(defaultID, "#"))
      moveCaretToEnd(tfSnippetID);
    JComponent panel;
    renameSubmitButton(panel = showTitledForm("Select Snippet", "Snippet ID:", tfSnippetID, runnableThread(new Runnable() {

      public void run() {
        try {
          callF(onSelect, fsI(getTextTrim(tfSnippetID)));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(onSelect, fsI(getTextTrim(tfSnippetID)));";
      }
    })), "Select snippet");
    return panel;
  }

  static public BufferedImage cloneBufferedImage(BufferedImage image) {
    return copyImage(image);
  }

  static public Object getTransferData(Transferable t, DataFlavor flavor) {
    try {
      return t != null && t.isDataFlavorSupported(flavor) ? t.getTransferData(flavor) : null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedImage imageFromDataURL(String url) {
    return decodeImage(bytesFromDataURL(url));
  }

  static public String getTextFromClipboard() {
    try {
      Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
      if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor))
        return (String) transferable.getTransferData(DataFlavor.stringFlavor);
      return null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void popupError(final Throwable throwable) {
    throwable.printStackTrace();
    SwingUtilities.invokeLater(new Runnable() {

      public void run() {
        String text = throwable.toString();
        JOptionPane.showMessageDialog(null, text);
      }
    });
  }

  static public ImageSurface jImageSurface() {
    return swingNu(ImageSurface.class);
  }

  static public ImageSurface jImageSurface(MakesBufferedImage img) {
    return swingNu(ImageSurface.class, img.getBufferedImage());
  }

  static public ImageSurface jImageSurface(BufferedImage img) {
    return swingNu(ImageSurface.class, img);
  }

  static public <A extends JComponent> A disposeFrameOnClick(final A c) {
    onClick(c, new Runnable() {

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

      public String toString() {
        return "disposeFrame(c)";
      }
    });
    return c;
  }

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

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

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

  static public <A, B> int lKeys(MultiMap<A, B> mm) {
    return mm == null ? 0 : mm.keysSize();
  }

  static public int latestInstalledJavaX() {
    File[] files = new File(userHome(), ".javax").listFiles();
    int v = 0;
    if (files != null)
      for (File f : files) {
        Matcher m = regexpMatcher("x(\\d\\d\\d?)\\.jar", f.getName());
        if (m.matches())
          v = Math.max(v, Integer.parseInt(m.group(1)));
      }
    return v;
  }

  static public String x30JarServerURL() {
    return "http://botcompany.de:8081/x30.jar";
  }

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

  static public Method findMethodNamed(Object obj, String method) {
    if (obj == null)
      return null;
    if (obj instanceof Class)
      return findMethodNamed((Class) obj, method);
    return findMethodNamed(obj.getClass(), method);
  }

  static public Method findMethodNamed(Class c, String method) {
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) {
        makeAccessible(m);
        return m;
      }
      c = c.getSuperclass();
    }
    return null;
  }

  static public int hashMap_internalHash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  }

  static public float clamp(float x, float a, float b) {
    return x < a ? a : x > b ? b : x;
  }

  static public double clamp(double x, double a, double b) {
    return x < a ? a : x > b ? b : x;
  }

  static public int clamp(int x, int a, int b) {
    return x < a ? a : x > b ? b : x;
  }

  static public long clamp(long x, long a, long b) {
    return x < a ? a : x > b ? b : x;
  }

  static public BufferedImage byteArrayToGrayBufferedImage(byte[] pixels, int w, int h) {
    PixelInterleavedSampleModel sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, w, h, 1, w, new int[] { 0 });
    DataBufferByte db = new DataBufferByte(pixels, pixels.length);
    WritableRaster wr = Raster.createWritableRaster(sm, db, new Point());
    return new BufferedImage(grayColorModel(), wr, false, null);
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  static public JMenuItem directJMenuItem(Action a) {
    return new JMenuItem(a) {

      public Dimension getMaximumSize() {
        return new Dimension(super.getPreferredSize().width, super.getMaximumSize().height);
      }
    };
  }

  static public JMenuItem directJMenuItem(String text, Object action) {
    return directJMenuItem(abstractAction(text, action));
  }

  static public JMenuBar addMenuBar(final Component c) {
    return swing(new F0<JMenuBar>() {

      public JMenuBar get() {
        try {
          RootPaneContainer f = getPossiblyInternalFrame(c);
          if (f == null)
            return null;
          JMenuBar bar = (JMenuBar) (call(f, "getJMenuBar"));
          if (bar == null) {
            setMenuBar(f, bar = new JMenuBar());
            revalidate((Component) f);
          }
          return bar;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "RootPaneContainer f = getPossiblyInternalFrame(c);\r\n    if (f == null) null;\r...";
      }
    });
  }

  static public void registerEscape_rootPane(JComponent rootPane, final Runnable r) {
    String name = "Escape";
    Action action = abstractAction(name, r);
    KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    rootPane.getActionMap().put(name, action);
    rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name);
  }

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

  static public JTextField jtextfield(String text) {
    return jTextField(text);
  }

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

  static public String joinStrings(String sep, Object... strings) {
    return joinStrings(sep, Arrays.asList(strings));
  }

  static public String joinStrings(String sep, Iterable strings) {
    StringBuilder buf = new StringBuilder();
    for (Object o : unnull(strings)) {
      String s = strOrNull(o);
      if (nempty(s)) {
        if (nempty(buf))
          buf.append(sep);
        buf.append(s);
      }
    }
    return str(buf);
  }

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

  static public int showForm_defaultGap = 4;

  static public int showForm_gapBetweenColumns = 10;

  static public JPanel showFormTitled(final String title, final Object... _parts) {
    JDesktopPane desktop = mainDesktopPane();
    if (desktop != null)
      return showInternalFrameFormTitled(desktop, title, _parts);
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          final Var<JFrame> frame = new Var();
          JPanel panel = showForm_makePanel(false, _parts);
          frame.set(showForm_makeFrame(title, panel));
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "final new Var<JFrame> frame;\r\n    JPanel panel = showForm_makePanel(false, _p...";
      }
    });
  }

  static public JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) {
    List<JComponent> out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts));
    return vstackWithSpacing(out, showForm_defaultGap);
  }

  static public String getTextTrim(JTextComponent c) {
    return trim(getText(c));
  }

  static public String getTextTrim(JComboBox cb) {
    return trim(getText(cb));
  }

  static public String getTextTrim(JComponent c) {
    if (c instanceof JLabel)
      return trim(((JLabel) c).getText());
    if (c instanceof JComboBox)
      return getTextTrim((JComboBox) c);
    return getTextTrim((JTextComponent) c);
  }

  static public <A extends JComponent> A renameSubmitButton(A form, String newName) {
    renameButton(form, showFormSubmitButtonName(), newName);
    return form;
  }

  static public <A extends JComponent> A renameSubmitButton(String newName, A form) {
    return renameSubmitButton(form, newName);
  }

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

  static public BufferedImage reconstructBufferedImage(BufferedImage img) {
    if (img == null)
      return null;
    RGBImage rgb = new RGBImage(img);
    rgb.uncacheBufferedImage();
    return rgb.getBufferedImage();
  }

  static public <A extends JTextComponent> A moveCaretToEnd(A ta) {
    setCaretPosition(ta, textAreaTextLength(ta));
    return ta;
  }

  static public JComponent showTitledForm(String title, Object... _parts) {
    return showFormTitled(title, _parts);
  }

  static public BufferedImage copyImage(Image img) {
    if (img == null)
      return null;
    if (img instanceof BufferedImage)
      return copyImage((BufferedImage) img);
    int w = img.getWidth(null), h = img.getHeight(null);
    BufferedImage bi = newBufferedImage(w, h);
    drawImage(bi, img);
    return bi;
  }

  static public BufferedImage copyImage(BufferedImage bi) {
    if (bi == null)
      return null;
    ColorModel cm = bi.getColorModel();
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster());
    return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
  }

  static public BufferedImage decodeImage(byte[] data) {
    try {
      if (empty(data))
        return null;
      return ImageIO.read(new ByteArrayInputStream(data));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] bytesFromDataURL(String url) {
    String pref = "base64,";
    int i = indexOf(url, pref);
    if (i < 0)
      return null;
    return base64decode(substring(url, i + l(pref)));
  }

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

  static public ColorModel grayColorModel_cache;

  static public ColorModel grayColorModel() {
    if (grayColorModel_cache == null)
      grayColorModel_cache = grayColorModel_load();
    return grayColorModel_cache;
  }

  static public ColorModel grayColorModel_load() {
    return newGrayBufferedImage(1, 1).getColorModel();
  }

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

  static public ThreadLocal<List<Object>> holdInstance_l = new ThreadLocal();

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

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

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

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

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

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

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

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

  static public RootPaneContainer getPossiblyInternalFrame(Component c) {
    JInternalFrame f = getInternalFrame(c);
    if (f != null)
      return f;
    return optCast(RootPaneContainer.class, getWindow(c));
  }

  static public void setMenuBar(final JMenuBar mb, final RootPaneContainer f) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            call(f, "setJMenuBar", mb);
            revalidate((Component) f);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "call(f, \"setJMenuBar\", mb);\r\n    revalidate((Component) f);";
        }
      });
    }
  }

  static public void setMenuBar(RootPaneContainer f, JMenuBar mb) {
    setMenuBar(mb, f);
  }

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

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

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

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

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

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

  static public JDesktopPane mainDesktopPane_value;

  static public JDesktopPane mainDesktopPane() {
    return mainDesktopPane_value;
  }

  static public JPanel showInternalFrameFormTitled(final JDesktopPane desktop, final String title, final Object... _parts) {
    JPanel panel = showForm_makePanel(true, _parts);
    showForm_makeInternalFrame(desktop, title, panel);
    return panel;
  }

  static public JFrame showForm_makeFrame(String title, JPanel panel) {
    return handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400));
  }

  static public List<JComponent> showForm_arrange1(List<List<JComponent>> l) {
    int minW = showForm_leftWidth(l);
    List<JComponent> out = new ArrayList();
    for (List<JComponent> row : l) out.add(westAndCenter(withRightMargin(showForm_gapBetweenColumns, jMinWidthAtLeast(minW, first(row))), second(row)));
    return out;
  }

  static public List<List<JComponent>> showForm_makeComponents(final Boolean internalFrame, Object... _parts) {
    List<List<JComponent>> l = new ArrayList();
    List parts = asList(_parts);
    JButton submitButton = null;
    for (int i = 0; i < l(parts); i++) {
      final Object o = parts.get(i), next = get(parts, i + 1);
      if (o instanceof String && next instanceof Component)
        setComponentID((Component) next, (String) o);
      if (o instanceof Component || o instanceof String || next instanceof Component) {
        l.add(mapLL(__49 -> wrapForSmartAdd_jComponent(__49), o == null ? new JPanel() : o instanceof String ? humanizeFormLabel((String) o) : o, next));
        if (next instanceof JButton && submitButton == null)
          submitButton = (JButton) next;
        i++;
      } else if (isRunnable(o))
        l.add(mapLL(__50 -> wrapForSmartAdd_jComponent(__50), null, submitButton = jbutton(showFormSubmitButtonName(), new Runnable() {

          public void run() {
            try {
              Object result = call(o);
              print("Result of form runnable: " + result + ". Button:  " + heldInstance(JButton.class));
              if (neq(Boolean.FALSE, result)) {
                if (isTrue(internalFrame))
                  disposeInternalFrame(heldInstance(JButton.class));
                else if (isFalse(internalFrame))
                  disposeFrame(heldInstance(JButton.class));
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "Object result = call(o);\r\n        print(\"Result of form runnable: \" + result ...";
          }
        })));
      else
        print("showForm: Unknown element type: " + getClassName(o));
    }
    if (submitButton != null) {
      final JButton _submitButton = submitButton;
      onEnterInAllTextFields(concatLists(l), new Runnable() {

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

        public String toString() {
          return "clickButton(_submitButton)";
        }
      });
    }
    for (List<JComponent> row : l) {
      JComponent left = first(row);
      if (left instanceof JLabel)
        makeBold((JLabel) left).setVerticalAlignment(JLabel.TOP);
    }
    return l;
  }

  static public int vstackWithSpacing_default = 10;

  static public JPanel vstackWithSpacing(final List parts) {
    return vstackWithSpacing(parts, vstackWithSpacing_default);
  }

  static public JPanel vstackWithSpacing(final List parts, final int spacing) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new GridBagLayout());
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.weightx = 1;
          gbc.fill = GridBagConstraints.HORIZONTAL;
          gbc.gridwidth = GridBagConstraints.REMAINDER;
          gbc.insets = new Insets(spacing / 2, 0, spacing / 2, 0);
          smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts)));
          gbc.weighty = 1;
          gbc.insets = new Insets(0, 0, 0, 0);
          panel.add(jrigid(), gbc);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new GridBagLayout);\r\n    new GridBagConstraints gbc...";
      }
    });
  }

  static public JPanel vstackWithSpacing(Component... parts) {
    return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
  }

  static public JPanel vstackWithSpacing(int spacing, Component... parts) {
    return vstackWithSpacing(asList(parts), spacing);
  }

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

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

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

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

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

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

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

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

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

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

  static public JButton renameButton(JComponent c, String name) {
    JButton b = first(childrenOfType(c, JButton.class));
    if (b != null)
      b.setText(name);
    return b;
  }

  static public JButton renameButton(JComponent c, String oldName, String newName) {
    JButton b = findButton(c, oldName);
    if (b != null)
      b.setText(newName);
    return b;
  }

  static public String showFormSubmitButtonName() {
    return "Submit";
  }

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

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

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

  static public int textAreaTextLength(JTextComponent ta) {
    return l(getText(ta));
  }

  static public BufferedImage newBufferedImage(int w, int h) {
    return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  }

  static public BufferedImage newBufferedImage(int w, int h, RGB rgb) {
    return newBufferedImage(w, h, rgb.getColor());
  }

  static public BufferedImage newBufferedImage(int w, int h, Color color) {
    BufferedImage img = newBufferedImage(w, h);
    Graphics2D g = img.createGraphics();
    g.setColor(or(color, Color.white));
    g.fillRect(0, 0, w, h);
    return img;
  }

  static public BufferedImage newBufferedImage(Pt p, Color color) {
    return newBufferedImage(p.x, p.y, color);
  }

  static public BufferedImage newBufferedImage(int w, int h, int[] pixels) {
    return intArrayToBufferedImage(pixels, w, h);
  }

  static public BufferedImage drawImage(BufferedImage canvas, Image img, Pt p) {
    return drawImageOnImage(img, canvas, p.x, p.y);
  }

  static public void drawImage(BufferedImage g, Image img) {
    drawImage(graphics(g), img);
  }

  static public void drawImage(Graphics2D g, Image img) {
    drawImage(g, img, 0, 0);
  }

  static public void drawImage(Graphics2D g, Image img, Pt p) {
    drawImage(g, img, p.x, p.y);
  }

  static public void drawImage(Graphics2D g, Image img, int x, int y) {
    {
      if (g != null)
        g.drawImage(img, x, y, null);
    }
  }

  static public byte[] base64decode(String s) {
    byte[] alphaToInt = base64decode_base64toint;
    int sLen = s.length();
    int numGroups = sLen / 4;
    if (4 * numGroups != sLen)
      throw new IllegalArgumentException("String length must be a multiple of four.");
    int missingBytesInLastGroup = 0;
    int numFullGroups = numGroups;
    if (sLen != 0) {
      if (s.charAt(sLen - 1) == '=') {
        missingBytesInLastGroup++;
        numFullGroups--;
      }
      if (s.charAt(sLen - 2) == '=')
        missingBytesInLastGroup++;
    }
    byte[] result = new byte[3 * numGroups - missingBytesInLastGroup];
    int inCursor = 0, outCursor = 0;
    for (int i = 0; i < numFullGroups; i++) {
      int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch3 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
      result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
      result[outCursor++] = (byte) ((ch2 << 6) | ch3);
    }
    if (missingBytesInLastGroup != 0) {
      int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
      if (missingBytesInLastGroup == 1) {
        int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
        result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
      }
    }
    return result;
  }

  static public int base64decode_base64toint(char c, byte[] alphaToInt) {
    int result = alphaToInt[c];
    if (result < 0)
      throw new IllegalArgumentException("Illegal character " + c);
    return result;
  }

  static final public byte[] base64decode_base64toint = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };

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

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

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

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

  static public JInternalFrame getInternalFrame(final Object _o) {
    return _o == null ? null : swing(new F0<JInternalFrame>() {

      public JInternalFrame 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 JInternalFrame)
              return (JInternalFrame) 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...";
      }
    });
  }

  static public <A> A optCast(Class<A> c, Object o) {
    return isInstance(c, o) ? (A) o : null;
  }

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

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

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

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

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

  static public JInternalFrame showForm_makeInternalFrame(JDesktopPane desktop, String title, JPanel panel) {
    JInternalFrame f = addInternalFrame(desktop, title, withMargin(panel));
    minInternalFrameWidth(f, 400);
    packInternalFrameVertically(f);
    centerInternalFrame(f);
    return f;
  }

  static public JFrame handleEscapeKey(final JFrame frame) {
    KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    frame.getRootPane().registerKeyboardAction(new ActionListener() {

      public void actionPerformed(ActionEvent actionEvent) {
        frame.dispose();
      }
    }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
    return frame;
  }

  static public JFrame minFrameWidth(JFrame frame, int w) {
    if (frame != null && frame.getWidth() < w)
      frame.setSize(w, frame.getHeight());
    return frame;
  }

  static public JFrame minFrameWidth(int w, JFrame frame) {
    return minFrameWidth(frame, w);
  }

  static public JFrame showPackedFrame(String title, Component contents) {
    return packFrame(showFrame(title, contents));
  }

  static public JFrame showPackedFrame(Component contents) {
    return packFrame(showFrame(contents));
  }

  static public int showForm_leftWidth_safetyMargin = 10;

  static public int showForm_leftWidth(List<List<JComponent>> l) {
    forEachLevel2(l, x -> vmBus_send("updateLayoutNow", x));
    int minW = 0;
    for (List<JComponent> row : l) minW = max(minW, getMinimumSize(first(row)).width);
    return minW + or((Integer) vmBus_query("formSafetyMargin"), showForm_leftWidth_safetyMargin);
  }

  static public <A extends Component> A jMinWidthAtLeast(int w, final A c) {
    if (c == null)
      return null;
    return swing(new F0<A>() {

      public A get() {
        try {
          Dimension size = c.getMinimumSize();
          Dimension d = new Dimension(max(w, size.width), size.height);
          c.setMinimumSize(d);
          return jPreferWidth(d.width, c);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Dimension size = c.getMinimumSize();\r\n    Dimension d = new Dimension(max(w, ...";
      }
    });
  }

  static public void setComponentID(Component c, String id) {
    if (c != null)
      componentID_map.put(c, id);
  }

  static public List mapLL(Object f, Object... data) {
    return map(f, ll(data));
  }

  static public <A, B> List<B> mapLL(IF1<A, B> f, A... data) {
    return map(f, ll(data));
  }

  static public JComponent wrapForSmartAdd_jComponent(Object o) {
    return componentToJComponent(wrapForSmartAdd(o));
  }

  static public boolean isRunnable(Object o) {
    return o instanceof Runnable || hasMethod(o, "get");
  }

  static public void disposeInternalFrame(Component c) {
    final JInternalFrame f = getInternalFrame(c);
    if (f != null) {
      swing(new Runnable() {

        public void run() {
          try {
            vmBus_send("disposingInternalFrame", f);
            f.dispose();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "vmBus_send disposingInternalFrame(f);\r\n    f.dispose();\r\n    // now illegal.....";
        }
      });
    }
  }

  static public void onEnterInAllTextFields(JComponent c, Object action) {
    if (action == null)
      return;
    for (Component tf : allChildren(c)) onEnterIfTextField(tf, action);
  }

  static public void onEnterInAllTextFields(List c, Object action) {
    for (Object o : unnull(c)) if (o instanceof JComponent)
      onEnterInAllTextFields((JComponent) o, action);
  }

  static public void clickButton(final JButton b) {
    if (b != null) {
      swing(new Runnable() {

        public void run() {
          try {
            if (b.isEnabled())
              b.doClick();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (b.isEnabled())\r\n      b.doClick();";
        }
      });
    }
  }

  static public <A extends JComponent> A makeBold(final A c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD));";
        }
      });
    }
    return c;
  }

  static public JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
    for (Object o : parts) panel.add(wrapForSmartAdd(o), layout);
    return panel;
  }

  static public JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
    return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
  }

  static public <A> List<A> nonNulls(Iterable<A> l) {
    return withoutNulls(l);
  }

  static public <A> List<A> nonNulls(A[] l) {
    return withoutNulls(l);
  }

  static public <A, B> Map<A, B> nonNulls(Map<A, B> map) {
    return withoutNulls(map);
  }

  static public BufferedImage intArrayToBufferedImage(int[] pixels, int w, int h) {
    int[] bitMasks = new int[] { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 };
    SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, w, h, bitMasks);
    DataBufferInt db = new DataBufferInt(pixels, pixels.length);
    WritableRaster wr = Raster.createWritableRaster(sm, db, new Point());
    return new BufferedImage(ColorModel.getRGBdefault(), wr, false, null);
  }

  static public BufferedImage drawImageOnImage(Image img, BufferedImage canvas, int x, int y) {
    createGraphics(canvas).drawImage(img, x, y, null);
    return canvas;
  }

  static public Map<Component, String> componentID_map = weakHashMap();

  static public String componentID(Component c) {
    return c == null ? null : componentID_map.get(c);
  }

  static public <A> A popLast(List<A> l) {
    return liftLast(l);
  }

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

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

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

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

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

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

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

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

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

  static public ThreadLocal<Integer> addInternalFrame_layer = new ThreadLocal();

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

  static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h) {
    return addInternalFrame(desktop, title, x, y, w, h, null);
  }

  static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h, final Component contents) {
    return addInternalFrame(desktop, title, rect(x, y, w, h), contents);
  }

  static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Component contents) {
    return addInternalFrame(desktop, title, null, contents);
  }

  static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Rect r, final Component contents) {
    final boolean dontSelect = isTrue(optParam(addInternalFrame_dontSelect));
    final boolean toBack = isTrue(optParam(addInternalFrame_toBack));
    final Integer layer = optParam(addInternalFrame_layer);
    return swing(new F0<JInternalFrame>() {

      public JInternalFrame get() {
        try {
          JInternalFrame frame;
          if (contents instanceof JInternalFrame)
            frame = (JInternalFrame) contents;
          else {
            frame = jInternalFrame(title);
            setInternalFrameContents(frame, contents);
          }
          frame.setVisible(true);
          desktop.add(frame, layer);
          if (r != null)
            setBounds(frame, r);
          else
            internalFrameDefaultPosition(frame);
          if (dontSelect)
            if (toBack)
              frame.toBack();
            else
              frame.toFront();
          else
            frame.setSelected(true);
          return fixInternalFrame(frame);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JInternalFrame frame;\r\n    if (contents instanceof JInternalFrame)\r\n      fra...";
      }
    });
  }

  static public JInternalFrame addInternalFrame(JDesktopPane desktop, String title) {
    return addInternalFrame(desktop, title, jpanel());
  }

  static public JInternalFrame minInternalFrameWidth(final JInternalFrame frame, final int w) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            if (frame != null && frame.getWidth() < w)
              frame.setSize(w, frame.getHeight());
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (frame != null && frame.getWidth() < w)\r\n      frame.setSize(w, frame.getH...";
        }
      });
    }
    return frame;
  }

  static public JInternalFrame minInternalFrameWidth(int w, JInternalFrame frame) {
    return minInternalFrameWidth(frame, w);
  }

  static public <A extends Component> A packInternalFrameVertically(A c) {
    return packInternalFrameVertically(-1, c);
  }

  static public <A extends Component> A packInternalFrameVertically(int width, A c) {
    final JInternalFrame win = getInternalFrame(c);
    if (win == null)
      return c;
    final int w = width < 0 ? win.getWidth() : width;
    {
      swing(new Runnable() {

        public void run() {
          try {
            win.pack();
            win.setSize(w, win.getHeight());
            fixInternalFrame(win);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "win.pack();\r\n    win.setSize(w, win.getHeight());\r\n    fixInternalFrame(win);";
        }
      });
    }
    return c;
  }

  static public JInternalFrame centerInternalFrame(final JInternalFrame f) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            Container c = f.getParent();
            if (c != null) {
              f.setLocation((c.getWidth() - f.getWidth()) / 2, (c.getHeight() - f.getHeight()) / 2);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Container c = f.getParent();\r\n    if (c != null) {\r\n      //print(\"Container ...";
        }
      });
    }
    return f;
  }

  static public JInternalFrame centerInternalFrame(final int w, final int h, final JInternalFrame f) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            f.setSize(w, h);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "f.setSize(w, h);";
        }
      });
    }
    return centerInternalFrame(f);
  }

  static public int packFrame_minw = 150, packFrame_minh = 50;

  static public <A extends Component> A packFrame(final A c) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            Window w = getWindow(c);
            if (w != null) {
              w.pack();
              int maxW = getScreenWidth() - 50, maxH = getScreenHeight() - 50;
              w.setSize(min(maxW, max(w.getWidth(), packFrame_minw)), min(maxH, max(w.getHeight(), packFrame_minh)));
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Window w = getWindow(c);\r\n    if (w != null) {\r\n      w.pack();\r\n      int ma...";
        }
      });
    }
    return c;
  }

  static public JFrame packFrame(ButtonGroup g) {
    return packFrame(getFrame(g));
  }

  static public JFrame showFrame() {
    return makeFrame();
  }

  static public JFrame showFrame(Object content) {
    return makeFrame(content);
  }

  static public JFrame showFrame(String title) {
    return makeFrame(title);
  }

  static public JFrame showFrame(String title, Object content) {
    return makeFrame(title, content);
  }

  static public JFrame showFrame(final JFrame f) {
    if (f != null) {
      swing(new Runnable() {

        public void run() {
          try {
            if (frameTooSmall(f))
              frameStandardSize(f);
            if (!f.isVisible())
              f.setVisible(true);
            if (f.getState() == Frame.ICONIFIED)
              f.setState(Frame.NORMAL);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (frameTooSmall(f)) frameStandardSize(f);\r\n    if (!f.isVisible()) f.setVis...";
        }
      });
    }
    return f;
  }

  static public JFrame showFrame(String title, Object content, JFrame frame) {
    if (frame == null)
      return showFrame(title, content);
    else {
      frame.setTitle(title);
      setFrameContents(frame, content);
      return frame;
    }
  }

  static public <A, B extends Collection<A>> void forEachLevel2(Iterable<B> l, IVF1<A> f) {
    if (l != null)
      for (B b : l) forEach(b, f);
  }

  static public <A, B extends Collection<A>> void forEachLevel2(IVF1<A> f, Iterable<B> l) {
    forEachLevel2(f, l);
  }

  static public <A extends Component> A jPreferWidth(int w, A c) {
    Dimension size = c.getPreferredSize();
    c.setPreferredSize(new Dimension(w, size.height));
    return c;
  }

  static public List<Component> allChildren(Component c) {
    return childrenOfType(c, Component.class);
  }

  static public void onEnterIfTextField(Component c, Object action) {
    if (action == null)
      return;
    if (c instanceof JTextField)
      onEnter((JTextField) c, action);
    else if (c instanceof JComboBox)
      onEnter((JComboBox) c, action);
  }

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

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

  static public <A> List<A> withoutNulls(A[] l) {
    List<A> l2 = new ArrayList();
    if (l != null)
      for (A a : l) if (a != null)
        l2.add(a);
    return l2;
  }

  static public Map<BufferedImage, Object> createGraphics_modulators = synchroIdentityHashMap();

  static public Graphics2D createGraphics(BufferedImage img) {
    Graphics2D g = img.createGraphics();
    Object mod = createGraphics_modulators.get(img);
    if (mod != null)
      callF(mod, g);
    return g;
  }

  static public void createGraphics_modulate(BufferedImage img, Object mod) {
    mapPut2(createGraphics_modulators, img, mod);
  }

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

  static public <A> A liftLast(List<A> l) {
    if (empty(l))
      return null;
    int i = l(l) - 1;
    A a = l.get(i);
    l.remove(i);
    return a;
  }

  static public <A> List<A> liftLast(int n, List<A> l) {
    int i = l(l) - n;
    List<A> part = cloneSubList(l, i);
    removeSubList(l, i);
    return part;
  }

  static public boolean jInternalFrame_iconifiable = true;

  static public JInternalFrame jInternalFrame() {
    return jInternalFrame("");
  }

  static public JInternalFrame jInternalFrame(final String title) {
    return swing(new F0<JInternalFrame>() {

      public JInternalFrame get() {
        try {
          JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame_iconifiable);
          f.setVisible(true);
          return f;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame...";
      }
    });
  }

  static public void setInternalFrameContents(final Component c, final Object contents) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            JInternalFrame frame = getInternalFrame(c);
            if (frame == null)
              return;
            frame.getContentPane().removeAll();
            frame.getContentPane().setLayout(new BorderLayout());
            if (contents != null)
              frame.getContentPane().add(wrap(contents));
            revalidate(frame);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "JInternalFrame frame = getInternalFrame(c);\r\n    if (frame == null) return;\r\n...";
        }
      });
    }
  }

  static public <A extends Component> A setBounds(final int x, final int y, final int w, final int h, final A a) {
    if (a != null) {
      swing(new Runnable() {

        public void run() {
          try {
            a.setBounds(x, y, w, h);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "a.setBounds(x, y, w, h);";
        }
      });
    }
    return a;
  }

  static public <A extends Component> A setBounds(A a, Rect r) {
    if (a != null && r != null) {
      swing(new Runnable() {

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

        public String toString() {
          return "a.setBounds(toRectangle(r));";
        }
      });
    }
    return a;
  }

  static public <A extends Component> A setBounds(Rect r, A a) {
    return setBounds(a, r);
  }

  static public <A extends Component> A setBounds(A a, int x, int y, int w, int h) {
    return setBounds(x, y, w, h, a);
  }

  static public void internalFrameDefaultPosition(JInternalFrame f) {
    f.setSize(500, 300);
    centerInternalFrame(f);
  }

  static public int fixInternalFrame_borderTopLeft = 0;

  static public int fixInternalFrame_borderBottomRight = 40;

  static public JInternalFrame fixInternalFrame(final JInternalFrame f) {
    return swing(new F0<JInternalFrame>() {

      public JInternalFrame get() {
        try {
          Container c = f.getParent();
          if (c == null)
            return f;
          Rect r = toRect(f.getBounds());
          int a = fixInternalFrame_borderTopLeft, b = fixInternalFrame_borderBottomRight;
          Rect outer = new Rect(a, a, c.getWidth() - b, c.getHeight() - b);
          if (!rectContains(outer, r))
            f.setLocation(max(a, min(r.x, outer.x2())), max(a, min(r.y, outer.y2())));
          if (r.w > c.getWidth() || r.h > c.getHeight())
            f.setSize(c.getWidth() - a, c.getHeight() - a);
          return f;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Container c = f.getParent();\r\n    if (c == null) ret f;\r\n    Rect r = toRect(...";
      }
    });
  }

  static public boolean frameTooSmall(JFrame frame) {
    return frame.getWidth() < 100 || frame.getHeight() < 50;
  }

  static public void frameStandardSize(JFrame frame) {
    frame.setBounds(300, 100, 500, 400);
  }

  static public void setFrameContents(final Component c, final Object contents) {
    swing(new Runnable() {

      public void run() {
        try {
          JFrame frame = getFrame(c);
          if (frame == null)
            return;
          frame.getContentPane().removeAll();
          frame.getContentPane().setLayout(new BorderLayout());
          frame.getContentPane().add(wrap(contents));
          revalidate(frame);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JFrame frame = getFrame(c);\r\n  if (frame == null) return;\r\n  frame.getContent...";
      }
    });
  }

  static public boolean containsNulls(Collection c) {
    return contains(c, null);
  }

  static public <A, B> Map<A, B> synchroIdentityHashMap() {
    return synchroMap(new IdentityHashMap());
  }

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

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

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

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

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

  static public boolean rectContains(int x1, int y1, int w, int h, Pt p) {
    return p.x >= x1 && p.y >= y1 && p.x < x1 + w && p.y < y1 + h;
  }

  static public boolean rectContains(Rect a, Rect b) {
    return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2();
  }

  static public boolean rectContains(Rect a, int x, int y) {
    return a != null && a.contains(x, y);
  }

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

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

  static public class TransferableImage implements Transferable {

    public Image i;

    public TransferableImage(Image i) {
      this.i = i;
    }

    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
      if (flavor.equals(DataFlavor.imageFlavor) && i != null) {
        return i;
      } else {
        throw new UnsupportedFlavorException(flavor);
      }
    }

    public DataFlavor[] getTransferDataFlavors() {
      DataFlavor[] flavors = new DataFlavor[1];
      flavors[0] = DataFlavor.imageFlavor;
      return flavors;
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
      DataFlavor[] flavors = getTransferDataFlavors();
      for (int i = 0; i < flavors.length; i++) {
        if (flavor.equals(flavors[i])) {
          return true;
        }
      }
      return false;
    }
  }

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

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

  static public Graphics2D graphics(BufferedImage img) {
    return imageGraphics(img);
  }

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

  static public Graphics2D imageGraphics(BufferedImage img) {
    return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : createGraphics(img);
  }

  static public Graphics2D antiAliasGraphics(BufferedImage img) {
    return antiAliasOn(createGraphics(img));
  }

  static public Graphics2D antiAliasOn(Graphics2D g) {
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    return g;
  }
}