import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import static x30_pkg.x30_util.asList;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import javax.swing.border.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.text.NumberFormat;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import javax.swing.plaf.basic.BasicSliderUI;
import java.awt.geom.Ellipse2D;
import java.awt.geom.*;

class main {

  public static class ImageSegmenter extends DynImageSurface {

    public int blur;

    public boolean distanceFromColor = false;

    public int dc_r, dc_g, dc_b;

    public float dc_gain = 5f, maxGain = 25f;

    public float contrastThreshold = 0.5f;

    public int gridSize = 2;

    public DoubleRange widthRange = new DoubleRange(0, 1);

    public DoubleRange heightRange = new DoubleRange(0, 1);

    public DoubleRange xRange = new DoubleRange(0, 1);

    public DoubleRange yRange = new DoubleRange(0, 1);

    public List<Rect> segments;

    public transient BufferedImage blurredImage;

    public transient JLabel lblFound;

    public transient ReliableSingleThread rst = dm_rst(this, new Runnable() {

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

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

    public JComponent visualize() {
      JSlider slider = main.onChange(jLiveValueSlider(dm_fieldLiveValue("contrastThreshold")), rst);
      JSpinner spinner = main.onChange(dm_spinner("gridSize", 2, 10), rst);
      JSpinner blurSpinner = main.onChange(dm_spinner("blur", 0, 10), rst);
      AutoCloseable __7 = tempAfterwards(new Runnable() {

        public void run() {
          try {
            imageSurfaceOnHover(imageSurface, new VF1<Pt>() {

              public void get(Pt p) {
                try {
                  RGB rgb = bufferedImage_getRGB(blurredImage, p);
                  setToolTip(imageSurface, rgb == null ? null : "Color: " + rgbToIntTriple(rgb));
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "RGB rgb = bufferedImage_getRGB(blurredImage, p);\r\n        setToolTip(imageSur...";
              }
            });
            updateLblFound();
            rst.trigger();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "imageSurfaceOnHover(imageSurface, new VF1<Pt>() { public void get(Pt p) ctex ...";
        }
      });
      try {
        return withCenteredLinesBelow(super.visualize(), ll(jCenteredSection(" Preprocessing ", withSideMargin(20, jline(withLabel("Blur:", blurSpinner), main.onChange(dm_checkBox("Distance from color:", "distanceFromColor"), rst), withLabel("R:", main.onChange(dm_spinner("dc_r", 0, 255), rst)), withLabel("G:", main.onChange(dm_spinner("dc_g", 0, 255), rst)), withLabel("B:", main.onChange(dm_spinner("dc_b", 0, 255), rst)), withLabel("Gain:", main.onChange(jMinWidth(100, jLiveValueSliderZeroToX(maxGain, dm_fieldLiveValue("dc_gain"))), rst)))))), ll(jCenteredSection(" Segmenting ", withSideMargin(20, jline(withLabel("Contrast Threshold:", jMinWidth(100, slider)), withLabel("Grid size:", spinner), jbutton("Segment", rst)))), jCenteredSection(" Result ", withSideMargin(20, lblFound = jboldlabel(" "))), jVerticalCenter(jPopDownButton_noText("Show segments", runnableThread(new Runnable() {

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

          public String toString() {
            return "showSegments();";
          }
        })))), ll(withLabel("Width range:", main.onChange(doubleRangeLiveValueSlider(dm_fieldLiveValue("widthRange")), rst)), withLabel("Height range:", main.onChange(doubleRangeLiveValueSlider(dm_fieldLiveValue("heightRange")), rst))), ll(withLabel("X position:", main.onChange(doubleRangeLiveValueSlider(dm_fieldLiveValue("xRange")), rst)), withLabel("Y position:", main.onChange(doubleRangeLiveValueSlider(dm_fieldLiveValue("yRange")), rst))));
      } finally {
        _close(__7);
      }
    }

    public void start() {
      super.start();
      if (!hasImage())
        setImage(whiteImage(100, 100));
      dm_vmBus_onMessage("newClipboardContents", new VF1<Object>() {

        public void get(Object o) {
          try {
            if (o instanceof BufferedImage) {
              startThread(new Runnable() {

                public void run() {
                  try {
                    setImage(((BufferedImage) o));
                    rst.trigger();
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "setImage(((BufferedImage) o)); rst.trigger();";
                }
              });
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (o cast BufferedImage) thread { setImage(o); rst.trigger(); }";
        }
      });
    }

    public void segmentIt() {
      AutoCloseable __8 = enter();
      try {
        if (!hasImage())
          return;
        int w = imageWidth(), h = imageHeight();
        BufferedImage image = getImage();
        BufferedImage imageToDraw = null;
        if (blur != 0)
          image = imageToDraw = new BoxBlurFilter(blur).filter(image, null);
        blurredImage = image;
        AutoSegmenter as = new AutoSegmenter();
        as.g = gridSize;
        as.contrastThreshold = contrastThreshold;
        BWImage bw;
        if (distanceFromColor) {
          bw = img_distanceFromColor_withGain(image, rgbFromInts(dc_r, dc_g, dc_b), dc_gain);
          imageToDraw = bw.getBufferedImage();
        } else
          bw = new BWImage(image);
        List<Rect> segments = as.go(bw);
        IntRange wr = doubleToIntRange_endPlus1(w, widthRange);
        IntRange hr = doubleToIntRange_endPlus1(h, heightRange);
        IntRange xr = doubleToIntRange_endPlus1(w, xRange);
        IntRange yr = doubleToIntRange_endPlus1(h, yRange);
        printVars_str("wr", wr, "hr", hr, "xr", xr, "yr", yr);
        segments = filterRectsByWidthRange(segments, wr);
        segments = filterRectsByHeightRange(segments, hr);
        segments = filterRectsByCenterXRange(segments, xr);
        segments = filterRectsByCenterYRange(segments, yr);
        setField("segments", segments);
        updateLblFound();
        imageSurface.imageToDraw = imageToDraw;
        overlaySelectionsOnImageSurface(imageSurface, segments);
      } finally {
        _close(__8);
      }
    }

    public void showSegments() {
      List<Rect> segments = this.segments;
      showImage_centered(n2(segments, "segment") + " found", mergeBufferedImagesVertically(map(segments, r -> clipBufferedImage(getImage(), r))));
    }

    public void updateLblFound() {
      setText(lblFound, nSegments(segments) + " found");
    }
  }

  public static boolean _moduleClass_ImageSegmenter = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static volatile StringBuffer local_log = new StringBuffer();

  public static volatile Appendable print_log = local_log;

  public static volatile int print_log_max = 1024 * 1024;

  public static volatile int local_log_max = 100 * 1024;

  public static boolean print_silent = false;

  public static Object print_byThread_lock = new Object();

  public static volatile ThreadLocal<Object> print_byThread;

  public static volatile Object print_allThreads;

  public static volatile Object print_preprocess;

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

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

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

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

  public static void print_raw(String s) {
    if (print_preprocess != null)
      s = (String) callF(print_preprocess, s);
    s = fixNewLines(s);
    Appendable loc = local_log;
    Appendable buf = print_log;
    int loc_max = print_log_max;
    if (buf != loc && buf != null) {
      print_append(buf, s, print_log_max);
      loc_max = local_log_max;
    }
    if (loc != null)
      print_append(loc, s, loc_max);
    System.out.print(s);
  }

  public static void print_autoRotate() {
  }

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

  public static ReliableSingleThread dm_rst(Runnable r) {
    return dm_rst(dm_current_mandatory(), r);
  }

  public static ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
    return dm_rst(mod, new ReliableSingleThread(r));
  }

  public static ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
    rst.enter = dm_rEnter(mod);
    return rst;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static JSlider jLiveValueSlider(final SimpleLiveValue<Float> lv) {
    return liveSliderZeroToOne(lv.get(), new VF1<Float>() {

      public void get(Float f) {
        try {
          lv.set(f);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

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

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

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

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

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

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

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

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

  public static AutoCloseable tempAfterwards(final Object r) {
    return new AutoCloseable() {

      public void close() {
        callF(r);
      }
    };
  }

  public static void imageSurfaceOnHover(ImageSurface is, VF1<Pt> onHover) {
    if (is == null || onHover == null)
      return;
    {
      swing(new Runnable() {

        public void run() {
          try {
            MouseAdapter ma = new MouseAdapter() {

              public void mouseMoved(MouseEvent e) {
                pick(e);
              }

              public void mouseEntered(MouseEvent e) {
                pick(e);
              }

              public void mouseExited(MouseEvent e) {
                pick(null);
              }

              public void pick(MouseEvent e) {
                callF(onHover, e == null ? (Pt) null : is.pointFromEvent(e));
              }
            };
            is.addMouseMotionListener(ma);
            is.addMouseListener(ma);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "MouseAdapter ma = new MouseAdapter {\r\n      public void mouseMoved(MouseEvent...";
        }
      });
    }
  }

  public static RGB bufferedImage_getRGB(BufferedImage img, int x, int y) {
    return img == null || x < 0 || y < 0 || x >= img.getWidth() || y >= img.getHeight() ? null : new RGB(img.getRGB(x, y));
  }

  public static RGB bufferedImage_getRGB(BufferedImage img, Pt p) {
    return p == null ? null : bufferedImage_getRGB(img, p.x, p.y);
  }

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

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

  public static T3<Integer, Integer, Integer> rgbToIntTriple(RGB rgb) {
    return rgb == null ? null : t3(rgb.redInt(), rgb.greenInt(), rgb.blueInt());
  }

  public static JComponent withCenteredLinesBelow(JComponent center, List<Component>... lines) {
    return foldl("withCenteredLineBelow", center, lines);
  }

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

  public static JPanel jCenteredSection(Component c) {
    return jCenteredSection("", c);
  }

  public static JPanel jCenteredSection(final String title, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = jSection(title, c);
          ((TitledBorder) p.getBorder()).setTitleJustification(TitledBorder.CENTER);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = jSection(title, c);\r\n    ((TitledBorder) p.getBorder()).setTitleJu...";
      }
    });
  }

  public static JPanel jCenteredSection(String title) {
    return jCenteredSection(title, jpanel());
  }

  public static JPanel withSideMargin(Component c) {
    return withLeftAndRightMargin(c);
  }

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

  public static JPanel withSideMargin(int w1, int w2, Component c) {
    return withLeftAndRightMargin(w1, w2, c);
  }

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

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

      public String toString() {
        return "ret new LeftAlignedLine(components);";
      }
    });
  }

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

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

  public static JCheckBox dm_checkBox(String field) {
    return dm_fieldCheckBox(field);
  }

  public static JCheckBox dm_checkBox(String text, String field) {
    return dm_fieldCheckBox(text, field);
  }

  public static <A extends Component> A jMinWidth(final int w, final A c) {
    if (c == null)
      return null;
    return swing(new F0<A>() {

      public A get() {
        try {
          Dimension size = c.getMinimumSize();
          c.setMinimumSize(new Dimension(w, size.height));
          return jPreferWidth(w, c);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Dimension size = c.getMinimumSize();\r\n    c.setMinimumSize(new Dimension(/*ma...";
      }
    });
  }

  public static JSlider jLiveValueSliderZeroToX(final float maxValue, final SimpleLiveValue<Float> lv) {
    return liveSliderZeroToX(maxValue, lv.get(), new VF1<Float>() {

      public void get(Float f) {
        try {
          lv.set(f);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

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

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

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

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

  public static JLabel jboldlabel(String text) {
    return jboldLabel(text);
  }

  public static JComponent jVerticalCenter(Component c) {
    Box box = Box.createVerticalBox();
    box.add(Box.createVerticalGlue());
    box.add(c);
    box.add(Box.createVerticalGlue());
    return box;
  }

  public static JButton jPopDownButton_noText(final Object... menuParams) {
    return jPopDownButton("", menuParams);
  }

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

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

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

  public static JSlider doubleRangeLiveValueSlider(final SimpleLiveValue<DoubleRange> lv) {
    return rangeSliderZeroToOne(lv.get(), new VF1<DoubleRange>() {

      public void get(DoubleRange r) {
        try {
          lv.set(r);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

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

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

  public static JLabel setImage(final BufferedImage img, final JLabel lbl) {
    if (lbl != null) {
      swing(new Runnable() {

        public void run() {
          try {
            lbl.setIcon(imageIcon(img));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "lbl.setIcon(imageIcon(img));";
        }
      });
    }
    return lbl;
  }

  public static JLabel setImage(JLabel lbl, BufferedImage img) {
    return setImage(img, lbl);
  }

  public static JLabel setImage(final String imageID, final JLabel lbl) {
    if (lbl != null) {
      swing(new Runnable() {

        public void run() {
          try {
            lbl.setIcon(imageIcon(imageID));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "lbl.setIcon(imageIcon(imageID));";
        }
      });
    }
    return lbl;
  }

  public static JLabel setImage(JLabel lbl, String imageID) {
    return setImage(imageID, lbl);
  }

  public static BufferedImage whiteImage(int w, int h) {
    return newBufferedImage(w, h, Color.white);
  }

  public static <A> AutoCloseable dm_vmBus_onMessage(final String msg, final VF1<A> onMessage) {
    return dm_ownResource(vmBus_onMessage(msg, onMessage));
  }

  public static <A, B> AutoCloseable dm_vmBus_onMessage(String msg, final VF2<A, B> onMessage) {
    return dm_ownResource(vmBus_onMessage(msg, onMessage));
  }

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

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

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

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

  public static BWImage img_distanceFromColor_withGain(RGBImage img, RGB color, float gain) {
    int w = img.getWidth(), h = img.getHeight();
    int col = color.getInt();
    BWImage bw = new BWImage(w, h);
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) bw.setPixel(x, y, rgbDiff(img.getInt(x, y), col) * gain);
    return bw;
  }

  public static BWImage img_distanceFromColor_withGain(BufferedImage img, RGB color, float gain) {
    return img_distanceFromColor_withGain(new RGBImage(img), color, gain);
  }

  public static RGB rgbFromInts(int r, int g, int b) {
    return RGB.newSafe(r / 255f, g / 255f, b / 255f);
  }

  public static IntRange doubleToIntRange_endPlus1(double factor, DoubleRange r) {
    return r == null ? null : intRange(iround(r.start * factor), iround(r.end * factor) + 1);
  }

  public static void printVars_str(Object... params) {
    String s = "";
    if (odd(l(params))) {
      s = str(first(params));
      if (endsWithLetter(s))
        s += ": ";
      params = dropFirst(params);
    }
    print(s + renderVars_str(params));
  }

  public static List<Rect> filterRectsByWidthRange(Collection<Rect> l, IntRange range) {
    return filter(l, new F1<Rect, Boolean>() {

      public Boolean get(Rect r) {
        try {
          return intRangeContains(range, r.w);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "intRangeContains(range, r.w)";
      }
    });
  }

  public static List<Rect> filterRectsByHeightRange(Collection<Rect> l, IntRange range) {
    return filter(l, new F1<Rect, Boolean>() {

      public Boolean get(Rect r) {
        try {
          return intRangeContains(range, r.h);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "intRangeContains(range, r.h)";
      }
    });
  }

  public static List<Rect> filterRectsByCenterXRange(Collection<Rect> l, IntRange range) {
    return filter(l, new F1<Rect, Boolean>() {

      public Boolean get(Rect r) {
        try {
          return intRangeContains(range, rectCenterX(r));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "intRangeContains(range, rectCenterX(r))";
      }
    });
  }

  public static List<Rect> filterRectsByCenterYRange(Collection<Rect> l, IntRange range) {
    return filter(l, new F1<Rect, Boolean>() {

      public Boolean get(Rect r) {
        try {
          return intRangeContains(range, rectCenterY(r));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "intRangeContains(range, rectCenterY(r))";
      }
    });
  }

  public static void overlaySelectionsOnImageSurface(final ImageSurface is, final List<Rect> rects) {
    if (is == null)
      return;
    is.overlay = new VF1<Graphics2D>() {

      public void get(Graphics2D g) {
        try {
          for (Rect r : rects) is.drawSelectionRect(g, r.getRectangle(), Color.blue, Color.white);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "for (Rect r : rects)\r\n      is.drawSelectionRect(g, r.getRectangle(), Color.b...";
      }
    };
    is.repaint();
  }

  public static ImageSurface showImage_centered(final BufferedImage img) {
    return (ImageSurface) swing(new F0<Object>() {

      public Object get() {
        try {
          ImageSurface is = new ImageSurface(img);
          JPanel panel = new JPanel(new GridBagLayout());
          panel.add(is);
          JFrame frame = showPackedFrame(new JScrollPane(panel));
          frameIcon(frame, showImage_defaultIcon);
          return is;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ImageSurface is = new ImageSurface(img);\r\n    JPanel panel = new JPanel(new G...";
      }
    });
  }

  public static ImageSurface showImage_centered(final BufferedImage img, final String title) {
    return setFrameTitle(showImage_centered(img), title);
  }

  public static ImageSurface showImage_centered(String title, BufferedImage img) {
    return showImage_centered(img, title);
  }

  public static ImageSurface showImage_centered(String title, RGBImage img) {
    return showImage_centered(title, img.getBufferedImage());
  }

  public static ImageSurface showImage_centered(ImageSurface is, BufferedImage img) {
    if (is == null)
      return showImage_centered(img);
    is.setImage(img);
    return is;
  }

  public static ImageSurface showImage_centered(ImageSurface is, String title, BufferedImage img) {
    if (is == null)
      return showImage_centered(title, img);
    is.setImage(img);
    setFrameTitle(is, title);
    return is;
  }

  public static ImageSurface showImage_centered(ImageSurface surface, RGBImage img, String title) {
    return setFrameTitle(showImage_centered(img, surface), title);
  }

  public static ImageSurface showImage_centered(RGBImage img, ImageSurface surface) {
    if (surface == null)
      return showImage_centered(img);
    else {
      surface.setImage(img);
      return surface;
    }
  }

  public static ImageSurface showImage_centered(RGBImage img) {
    return showImage_centered(img.getBufferedImage());
  }

  public static ImageSurface showImage_centered(ImageSurface surface, String title, RGBImage img) {
    return showImage_centered(surface, img, title);
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static BufferedImage mergeBufferedImagesVertically(List<BufferedImage> images) {
    return mergeImagesVertically(map("toRGBImage", images)).getBufferedImage();
  }

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

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

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

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

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

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

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

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

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

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

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

  public static List map(Map map, Object f) {
    List x = new ArrayList();
    if (map != null)
      for (Object _e : map.entrySet()) {
        Map.Entry e = (Map.Entry) _e;
        x.add(callF(f, e.getKey(), e.getValue()));
      }
    return x;
  }

  public static BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) {
    return clipBufferedImage(src, new Rect(clip));
  }

  public static BufferedImage clipBufferedImage(BufferedImage src, Rect r) {
    if (src == null)
      return null;
    r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight()));
    if (rectEmpty(r))
      return null;
    return src.getSubimage(r.x, r.y, r.w, r.h);
  }

  public static BufferedImage clipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
    return clipBufferedImage(src, new Rect(x, y, w, h));
  }

  public static boolean setText_opt = true;

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

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

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

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

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

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

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

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

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

  public static String nSegments(long n) {
    return n2(n, "segment");
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static String showImage_defaultIcon = "#1004230";

  public static ImageSurface showImage(String snippetIDOrURL, String title) {
    return showImage(loadImage(snippetIDOrURL), title);
  }

  public static ImageSurface showImage(String title, BufferedImage img) {
    return showImage(img, title);
  }

  public static ImageSurface showImage(final BufferedImage img, final String title) {
    return (ImageSurface) swing(new F0<Object>() {

      public Object get() {
        try {
          ImageSurface is = showImage(img);
          getFrame(is).setTitle(title);
          return is;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ImageSurface is = showImage(img);\r\n    getFrame(is).setTitle(title);\r\n    ret...";
      }
    });
  }

  public static ImageSurface showImage(final BufferedImage img) {
    return (ImageSurface) swing(new F0<Object>() {

      public Object get() {
        try {
          ImageSurface is = new ImageSurface(img);
          JFrame frame = showPackedFrame(new JScrollPane(is));
          moveToTopRightCorner(frame);
          frameIcon(frame, showImage_defaultIcon);
          return is;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ImageSurface is = new ImageSurface(img);\r\n    JFrame frame = showPackedFrame(...";
      }
    });
  }

  public static ImageSurface showImage(String imageID) {
    return showImage(loadImage2(imageID));
  }

  public static ImageSurface showImage(ImageSurface surface, BufferedImage img) {
    return showImage(img, surface);
  }

  public static ImageSurface showImage(ImageSurface surface, String title, BufferedImage img) {
    return showImage(surface, img, title);
  }

  public static ImageSurface showImage(ImageSurface surface, BufferedImage img, String title) {
    return setFrameTitle(showImage(img, surface), title);
  }

  public static ImageSurface showImage(BufferedImage img, ImageSurface surface) {
    if (surface == null)
      return showImage(img);
    else {
      surface.setImage(img);
      return surface;
    }
  }

  public static ImageSurface showImage(String title, MakesBufferedImage img) {
    return showImage(title, img.getBufferedImage());
  }

  public static ImageSurface showImage(ImageSurface is, MakesBufferedImage img) {
    return showImage(is, img.getBufferedImage());
  }

  public static ImageSurface showImage(RGBImage img) {
    return showImage(img.getBufferedImage());
  }

  public static ImageSurface showImage(RGBImage img, String title) {
    ImageSurface is = showImage(img.getBufferedImage());
    getFrame(is).setTitle(title);
    return is;
  }

  public static ImageSurface showImage(ImageSurface surface, RGBImage img) {
    return showImage(img, surface);
  }

  public static ImageSurface showImage(RGBImage img, ImageSurface surface) {
    if (surface == null)
      return showImage(img);
    else {
      surface.setImage(img);
      return surface;
    }
  }

  public static ImageSurface showImage(ImageSurface surface, String title, RGBImage img) {
    return showImage(surface, img, title);
  }

  public static ImageSurface showImage(ImageSurface surface, RGBImage img, String title) {
    return setFrameTitle(showImage(img, surface), title);
  }

  public static ImageSurface showImage(BWImage img) {
    return showImage(img.getBufferedImage());
  }

  public static ImageSurface showImage() {
    return showImage(currentImage());
  }

  public static ImageSurface showImage(File f) {
    return showImage(f2s(f), loadImage2(f));
  }

  public static Object _defaultClassFinder_value = defaultDefaultClassFinder();

  public static Object _defaultClassFinder() {
    return _defaultClassFinder_value;
  }

  public static String programID;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static F0<AutoCloseable> dm_rEnter(final DynModule mod) {
    return mod == null ? null : new F0<AutoCloseable>() {

      public AutoCloseable get() {
        try {
          return mod.enter();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret mod.enter();";
      }
    };
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static JSlider liveSliderZeroToOne(final float def, final Object f) {
    return swing(new F0<JSlider>() {

      public JSlider get() {
        try {
          final int max = 9999;
          final JSlider slider = new JSlider(0, max, iround(def * max));
          slider.addChangeListener(new ChangeListener() {

            public int lastValue = slider.getValue();

            public void stateChanged(ChangeEvent e) {
              int value = slider.getValue();
              if (value != lastValue) {
                lastValue = value;
                float x = value / (float) max;
                setToolTip(slider, str(x));
                pcallF(f, x);
              }
            }
          });
          return slider;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "final int max = 9999;\r\n    final JSlider slider = new JSlider(0, max, iround(...";
      }
    });
  }

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

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

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

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

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

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

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

  public static 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.get())";
      }
    });
    return spinner;
  }

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

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

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

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

  public static <A, B, C> T3<A, B, C> t3(A a, B b, C c) {
    return new T3(a, b, c);
  }

  public static <A, B> A foldl(F2<A, B, A> f, A seed, Iterable<B> l) {
    A a = seed;
    if (l != null)
      for (B b : l) a = callF(f, a, b);
    return a;
  }

  public static <A, B> A foldl(F2<A, B, A> f, A seed, B[] l) {
    A a = seed;
    if (l != null)
      for (B b : l) a = callF(f, a, b);
    return a;
  }

  public static <A, B> A foldl(Object f, A seed, B[] l) {
    A a = seed;
    if (l != null)
      for (B b : l) a = (A) callF(f, a, b);
    return a;
  }

  public static JPanel withCenteredLineBelow(JComponent center, Component... components) {
    return centerAndSouth(center, withMargin(jcenteredline(components)));
  }

  public static JPanel withCenteredLineBelow(JComponent center, List<? extends Component> components) {
    return withCenteredLineBelow(center, asComponentArray(components));
  }

  public static JPanel jSection(Component c) {
    return jSection("", c);
  }

  public static JPanel jSection(final String title, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
          border = BorderFactory.createTitledBorder(border, title);
          JSection panel = new JSection(c);
          panel.setBorder(border);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n    bo...";
      }
    });
  }

  public static JPanel jSection(String title) {
    return jSection(title, jpanel());
  }

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

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

  public static int withLeftAndRightMargin_defaultWidth = 6;

  public static JPanel withLeftAndRightMargin(Component c) {
    return withLeftAndRightMargin(withLeftAndRightMargin_defaultWidth, c);
  }

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

  public static JPanel withLeftAndRightMargin(final int w1, final int w2, final Component c) {
    return swing(new F0<JPanel>() {

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

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

  public static Object[] asArray(List l) {
    return toObjectArray(l);
  }

  public static <A> A[] asArray(Class<A> type, List l) {
    return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
  }

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

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

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

  public static JCheckBox dm_fieldCheckBox(String field) {
    return dm_fieldCheckBox(humanizeFormLabel(field), field);
  }

  public static JCheckBox dm_fieldCheckBox(String text, String field) {
    if (isIdentifier(text) && !isIdentifier(field)) {
      String temp = field;
      field = text;
      text = temp;
    }
    return jLiveValueCheckBox(text, dm_fieldLiveValue(field));
  }

  public static <A extends Component> A jPreferWidth(int w, A c) {
    Dimension size = c.getPreferredSize();
    c.setPreferredSize(new Dimension(w, size.height));
    return c;
  }

  public static JSlider liveSliderZeroToX(final float maxValue, final float def, final Object f) {
    return swing(new F0<JSlider>() {

      public JSlider get() {
        try {
          final int max = 10000;
          final float factor = max / maxValue;
          final JSlider slider = new JSlider(0, max, iround(def * factor));
          slider.addChangeListener(new ChangeListener() {

            public int lastValue = slider.getValue();

            public void stateChanged(ChangeEvent e) {
              int value = slider.getValue();
              if (value != lastValue) {
                lastValue = value;
                float x = value / factor;
                setToolTip(slider, str(x));
                pcallF(f, x);
              }
            }
          });
          return slider;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "final int max = 10000;\r\n    final float factor = max/maxValue;\r\n    final JSl...";
      }
    });
  }

  public static boolean newButton_autoToolTip = true;

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

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

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

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

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

  public static JButton jPopDownButton(String text, final Object... menuParams) {
    return jbutton((empty(text) ? "" : text + " ") + unicode_downPointingTriangle(), new Runnable() {

      public void run() {
        try {
          JPopupMenu menu = new JPopupMenu();
          int emptyCount = menu.getComponentCount();
          String position = (String) (optPar(menuParams, "position"));
          fillJPopupMenu(menu, paramsWithout(menuParams, "position"));
          if (menu.getComponentCount() != emptyCount) {
            JButton btn = heldInstance(JButton.class);
            int x = 0;
            if (eq(position, "center"))
              x = (btn.getWidth() - getPreferredWidth(menu)) / 2;
            else if (eq(position, "right"))
              x = btn.getWidth() - getPreferredWidth(menu);
            menu.show(btn, x, btn.getHeight());
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "new JPopupMenu menu;\r\n    int emptyCount = menu.getComponentCount();\r\n    Str...";
      }
    });
  }

  public static RangeSlider rangeSliderZeroToOne(DoubleRange defRange, Object f) {
    return swing(new F0<RangeSlider>() {

      public RangeSlider get() {
        try {
          int max = 9999;
          RangeSlider slider = new RangeSlider(0, max);
          rangeSliderSetZeroToOneDoubleRange(slider, max, defRange);
          slider.addChangeListener(new ChangeListener() {

            public DoubleRange lastValue = zeroToOneDoubleRangeFromRangeSlider(max, slider);

            public void stateChanged(ChangeEvent e) {
              DoubleRange value = zeroToOneDoubleRangeFromRangeSlider(max, slider);
              if (neq(value, lastValue)) {
                lastValue = value;
                setToolTip(slider, str(value));
                pcallF(f, value);
              }
            }
          });
          return slider;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "int max = 9999;\r\n    RangeSlider slider = new RangeSlider(0, max);\r\n    range...";
      }
    });
  }

  public static int imageIcon_cacheSize = 10;

  public static boolean imageIcon_verbose = false;

  public static Map<String, ImageIcon> imageIcon_cache;

  public static Lock imageIcon_lock = lock();

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

  public static ImageIcon imageIcon(String imageID) {
    try {
      if (imageID == null)
        return null;
      Lock __80 = imageIcon_lock;
      lock(__80);
      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(__80);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

  public static BufferedImage newBufferedImage(int w, int h) {
    return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  }

  public static BufferedImage newBufferedImage(int w, int h, Color color) {
    BufferedImage img = newBufferedImage(w, h);
    Graphics2D g = img.createGraphics();
    g.setColor(color);
    g.fillRect(0, 0, w, h);
    return img;
  }

  public static BufferedImage newBufferedImage(Pt p, Color color) {
    return newBufferedImage(p.x, p.y, color);
  }

  public static <A extends AutoCloseable> A dm_ownResource(A resource) {
    dm_currentModuleMandatory().ownResource(resource);
    return resource;
  }

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

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

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

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

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

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

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

  public static String defaultThreadName_name;

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

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

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

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

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

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

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

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

  public static Map<Thread, Boolean> _registerThread_threads;

  public static Object _onRegisterThread;

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

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

  public static float rgbDiff(RGB a, RGB b) {
    return (float) (Math.abs(a.r - b.r) + Math.abs(a.g - b.g) + Math.abs(a.b - b.b)) / 3;
  }

  public static float rgbDiff(int a, int b) {
    int r1 = (a >> 16) & 0xFF;
    int g1 = (a >> 8) & 0xFF;
    int b1 = a & 0xFF;
    int r2 = (b >> 16) & 0xFF;
    int g2 = (b >> 8) & 0xFF;
    int b2 = b & 0xFF;
    return (Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2)) / (3f * 255);
  }

  public static IntRange intRange(int start, int end) {
    return new IntRange(start, end);
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static boolean endsWithLetter(String s) {
    return nempty(s) && isLetter(last(s));
  }

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

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

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

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

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

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

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

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

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

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

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

  public static String renderVars_str(Object... params) {
    List<String> l = new ArrayList();
    for (int i = 0; i + 1 < l(params); i += 2) l.add(params[i] + "=" + params[i + 1] + ". ");
    return trim(join(l));
  }

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

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

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

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

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

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

  public static boolean intRangeContains(IntRange r, int i) {
    return r != null && i >= r.start && i < r.end;
  }

  public static Integer rectCenterX(Rect r) {
    return r == null ? null : r.x + r.w / 2;
  }

  public static Integer rectCenterY(Rect r) {
    return r == null ? null : r.y + r.h / 2;
  }

  public static JFrame showPackedFrame(String title, Component contents) {
    return packFrame(showFrame(title, contents));
  }

  public static JFrame showPackedFrame(Component contents) {
    return packFrame(showFrame(contents));
  }

  public static Component frameIcon(Component c, String imageID) {
    setFrameIconLater(c, imageID);
    return c;
  }

  public static Component frameIcon(String imageID, Component c) {
    setFrameIconLater(c, imageID);
    return c;
  }

  public static <A> A setFrameTitle(A c, final String title) {
    final Frame f = getAWTFrame(c);
    if (f != null) {
      swing(new Runnable() {

        public void run() {
          try {
            f.setTitle(title);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "f.setTitle(title);";
        }
      });
    }
    return c;
  }

  public static <A extends Component> A setFrameTitle(String title, A c) {
    return setFrameTitle(c, title);
  }

  public static JFrame setFrameTitle(String title) {
    Object f = getOpt(mc(), "frame");
    if (f instanceof JFrame)
      return setFrameTitle((JFrame) f, title);
    return null;
  }

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

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

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

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

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

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

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

  public static RGBImage mergeImagesVertically(RGBImage... images) {
    return mergeImagesVertically(toList(images));
  }

  public static RGBImage mergeImagesVertically(List<RGBImage> images, Object... __) {
    int spacing = imageMergeSpacing();
    RGB spaceColor = optPar("spaceColor", __, new RGB(0.9f));
    int h = intSum(images, "height") + (l(images) - 1) * spacing, w = intMax(images, "width");
    RGBImage out = new RGBImage(w, h, spaceColor);
    int y = 0;
    for (int i = 0; i < l(images); i++) {
      RGBImage img = images.get(i);
      int x = (w - img.w()) / 2;
      copyRGBImage(img, 0, 0, out, x, y);
      y += img.h() + spacing;
    }
    return out;
  }

  public static RGBImage toRGBImage(BWImage img) {
    return img == null ? null : img.toRGB();
  }

  public static RGBImage toRGBImage(BufferedImage img) {
    return img == null ? null : new RGBImage(img);
  }

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

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

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

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

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

  public static Rect intersectRects(Rect a, Rect b) {
    int x = max(a.x, b.x), y = max(a.y, b.y);
    int x2 = min(a.x + a.w, b.x + b.w), y2 = min(a.y + a.h, b.y + b.h);
    return new Rect(x, y, x2 - x, y2 - y);
  }

  public static boolean rectEmpty(Rect r) {
    return r == null || r.w <= 0 || r.h <= 0;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static Class __javax;

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

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

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

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

  public static RGBImage loadImage(String snippetIDOrURL) {
    return new RGBImage(loadBufferedImage(snippetIDOrURL));
  }

  public static RGBImage loadImage(File f) {
    return new RGBImage(loadBufferedImage(f));
  }

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

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

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

  public static int moveToTopRightCorner_inset = 20;

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

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

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

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

  public static ThreadLocal<BufferedImage> currentImage_var = new ThreadLocal();

  public static BufferedImage currentImage() {
    return currentImage_var.get();
  }

  public static void currentImage(BufferedImage img) {
    currentImage_var.set(img);
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static volatile boolean ping_pauseAll = false;

  public static int ping_sleep = 100;

  public static volatile boolean ping_anyActions = false;

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

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

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

  public static boolean ping_impl(boolean okInCleanUp) {
    try {
      if (ping_pauseAll && !isAWTThread()) {
        do Thread.sleep(ping_sleep); while (ping_pauseAll);
        return true;
      }
      if (ping_anyActions) {
        if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
          failIfUnlicensed();
        Object action = null;
        synchronized (ping_actions) {
          if (!ping_actions.isEmpty()) {
            action = ping_actions.get(currentThread());
            if (action instanceof Runnable)
              ping_actions.remove(currentThread());
            if (ping_actions.isEmpty())
              ping_anyActions = false;
          }
        }
        if (action instanceof Runnable)
          ((Runnable) action).run();
        else if (eq(action, "cancelled"))
          throw fail("Thread cancelled.");
      }
      return false;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  public static void rotateStringBuffer(StringBuffer buf, int max) {
    try {
      if (buf == null)
        return;
      synchronized (buf) {
        if (buf.length() <= max)
          return;
        try {
          int newLength = max / 2;
          int ofs = buf.length() - newLength;
          String newString = buf.substring(ofs);
          buf.setLength(0);
          buf.append("[...] ").append(newString);
        } catch (Exception e) {
          buf.setLength(0);
        }
        buf.trimToSize();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static void rotateStringBuilder(StringBuilder buf, int max) {
    try {
      if (buf == null)
        return;
      synchronized (buf) {
        if (buf.length() <= max)
          return;
        try {
          int newLength = max / 2;
          int ofs = buf.length() - newLength;
          String newString = buf.substring(ofs);
          buf.setLength(0);
          buf.append("[...] ").append(newString);
        } catch (Exception e) {
          buf.setLength(0);
        }
        buf.trimToSize();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static int withMargin_defaultWidth = 6;

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

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

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

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

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

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

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

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

  public static Component[] asComponentArray(Collection<? extends Component> c) {
    Component[] a = new Component[l(c)];
    Iterator<? extends Component> it = c.iterator();
    for (int i = 0; i < l(a); i++) a[i] = it.next();
    return a;
  }

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

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

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

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

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

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

  public static Map<String, String> humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");

  public static String humanizeFormLabel(String s) {
    if (containsSpace(s))
      return s;
    return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
  }

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

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

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

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

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

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

  public static JLabel makeLabelBold(final JLabel l) {
    if (l != null) {
      swing(new Runnable() {

        public void run() {
          try {
            l.setFont(l.getFont().deriveFont(Font.BOLD));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "l.setFont(l.getFont().deriveFont(Font.BOLD));";
        }
      });
    }
    return l;
  }

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

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

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

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

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

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

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

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

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

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

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

  public static String unicode_downPointingTriangle() {
    return charToString(0x25BC);
  }

  public static <A> A optPar(ThreadLocal<A> tl, A defaultValue) {
    A a = tl.get();
    if (a != null) {
      tl.set(null);
      return a;
    }
    return defaultValue;
  }

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

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

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

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

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

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

  public static void fillJPopupMenu(JPopupMenu m, Object... x) {
    if (x == null)
      return;
    for (int i = 0; i < l(x); i++) {
      Object o = x[i], y = get(x, i + 1);
      if (o instanceof List)
        fillJPopupMenu(m, asArray((List) o));
      else if (isMenuSeparatorIndicator(o))
        m.addSeparator();
      else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) {
        final LiveValue<String> lv = (LiveValue<String>) o;
        final JMenuItem mi = jmenuItem("", y);
        bindLiveValueListenerToComponent(mi, lv, new Runnable() {

          public void run() {
            try {
              String s = lv.get();
              if (isCurlyBracketed(s)) {
                setEnabled(mi, false);
                s = unCurlyBracket(s);
              } else
                setEnabled(mi, true);
              setText(mi, s);
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "String s = lv.get();\r\n        if (isCurlyBracketed(s)) {\r\n          setEnable...";
          }
        });
        m.add(mi);
      } else if (o instanceof String && isRunnableX(y)) {
        m.add(jmenuItem((String) o, y));
        ++i;
      } else if (o instanceof JMenuItem)
        m.add((JMenuItem) o);
      else if (o instanceof String || o instanceof Action || o instanceof Component)
        call(m, "add", o);
      else
        print("Unknown menu item: " + o);
    }
  }

  public static Object[] paramsWithout(Object[] a1, Object... keys) {
    if (l(a1) == 1 && a1[0] instanceof Map)
      return new Object[] { mapMinus((Map) a1[0], keys) };
    Set set = lithashset(keys);
    List l = new ArrayList();
    for (int i = 0; i + 1 < l(a1); i += 2) if (!set.contains(a1[i])) {
      l.add(a1[i]);
      l.add(a1[i + 1]);
    }
    return toObjectArray(l);
  }

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

  public static int getPreferredWidth(Component c) {
    return preferredWidth(c);
  }

  public static void rangeSliderSetZeroToOneDoubleRange(RangeSlider slider, int max, DoubleRange r) {
    if (slider != null && r != null) {
      swing(new Runnable() {

        public void run() {
          try {
            slider.setValues(iround(r.start * max), iround(r.end * max));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "slider.setValues(iround(r.start*max), iround(r.end*max));";
        }
      });
    }
  }

  public static DoubleRange zeroToOneDoubleRangeFromRangeSlider(int max, RangeSlider slider) {
    return swing(new F0<DoubleRange>() {

      public DoubleRange get() {
        try {
          return new DoubleRange(doubleRatio(slider.getValue(), max), doubleRatio(slider.getUpperValue(), max));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret DoubleRange(doubleRatio(slider.getValue(), max), doubleRatio(slider.getUp...";
      }
    });
  }

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

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

  public static File loadBinarySnippet(String snippetID) {
    try {
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.loadLibrary(snippetID);
      long id = parseSnippetID(snippetID);
      if (isImageServerSnippet(id))
        return loadImageAsFile(snippetID);
      File f = DiskSnippetCache_getLibrary(id);
      if (fileSize(f) == 0)
        f = loadDataSnippetToFile(snippetID);
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static boolean loadBufferedImageFixingGIFs_debug = false;

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

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

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

  public static Map<String, Set> vm_busListenersByMessage_live_cache;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static int packFrame_minw = 150, packFrame_minh = 50;

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

  public static JFrame packFrame(ButtonGroup g) {
    return packFrame(getFrame(g));
  }

  public static JFrame showFrame() {
    return makeFrame();
  }

  public static JFrame showFrame(Object content) {
    return makeFrame(content);
  }

  public static JFrame showFrame(String title) {
    return makeFrame(title);
  }

  public static JFrame showFrame(String title, Object content) {
    return makeFrame(title, content);
  }

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

  public static JFrame showFrame(String title, Object content, JFrame frame) {
    if (frame == null)
      return showFrame(title, content);
    else {
      frame.setTitle(title);
      setFrameContents(frame, content);
      return frame;
    }
  }

  public static JFrame setFrameIconLater(Component c, final String imageID) {
    final JFrame frame = getFrame(c);
    if (frame != null)
      startThread("Loading Icon", new Runnable() {

        public void run() {
          try {
            final Image i = imageIcon(or2(imageID, "#1005557")).getImage();
            swingLater(new Runnable() {

              public void run() {
                try {
                  frame.setIconImage(i);
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "frame.setIconImage(i);";
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n      swingL...";
        }
      });
    return frame;
  }

  public static Frame getAWTFrame(final Object _o) {
    return swing(new F0<Frame>() {

      public Frame 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 Frame)
              return (Frame) c;
            c = c.getParent();
          }
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "O o = _o;\r\n    /*\r\n    ifdef HaveProcessing\r\n      if (o instanceof PApplet) ...";
      }
    });
  }

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

  public static int imageMergeSpacing = 5;

  public static int imageMergeSpacing() {
    return imageMergeSpacing;
  }

  public static void imageMergeSpacing(int pixels) {
    imageMergeSpacing = pixels;
  }

  public static int intSum(Collection c, String field) {
    int sum = 0;
    for (Object o : unnull(c)) sum += toInt(getOpt(o, field));
    return sum;
  }

  public static int intSum(Iterable<Integer> l) {
    int sum = 0;
    for (Integer i : unnull(l)) if (i != null)
      sum += i;
    return sum;
  }

  public static int intMax(Collection c, String field) {
    int max = 0;
    for (Object o : c) max = Math.max(max, toInt(getOpt(o, field)));
    return max;
  }

  public static void copyRGBImage(RGBImage src, int srcX, int srcY, RGBImage dst, int dstX, int dstY) {
    copyRGBImage(src, srcX, srcY, dst, dstX, dstY, src.getWidth() - srcX, src.getHeight() - srcY);
  }

  public static void copyRGBImage(RGBImage src, int srcX, int srcY, RGBImage dst, int dstX, int dstY, int w, int h) {
    w = min(w, dst.getWidth() - dstX);
    h = min(h, dst.getHeight() - dstY);
    w = min(w, src.getWidth() - srcX);
    h = min(h, src.getHeight() - srcY);
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) dst.setPixel(dstX + x, dstY + y, src.getInt(srcX + x, srcY + y));
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static ThreadLocal<List<Object>> holdInstance_l = new ThreadLocal();

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

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

  public static boolean loadBufferedImage_useImageCache = true;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static volatile PersistableThrowable _handleException_lastException;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static JPanel jFullCenter(final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new GridBagLayout());
          panel.add(c);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new GridBagLayout);\r\n    panel.add(c);\r\n    ret panel;";
      }
    });
  }

  public static int hstackWithSpacing_spacing = 10;

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

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

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

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

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

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

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

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

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

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

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

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

  public static boolean containsSpace(String s) {
    return containsSpaces(s);
  }

  public static String firstToUpper(String s) {
    if (empty(s))
      return s;
    return Character.toUpperCase(s.charAt(0)) + s.substring(1);
  }

  public static <A> List<A> replaceElementsUsingMap(Iterable<A> l, final Map<A, A> map) {
    return map(l, new F1<A, A>() {

      public A get(A a) {
        try {
          return getOrKeep(map, a);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "getOrKeep(map, a)";
      }
    });
  }

  public static List<String> splitCamelCase(String s) {
    return ai_splitCamelCase(s);
  }

  public static boolean isJavaIdentifier(String s) {
    if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
      return false;
    for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
      return false;
    return true;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static String charToString(char c) {
    return String.valueOf(c);
  }

  public static String charToString(int c) {
    return String.valueOf((char) c);
  }

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

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

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

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

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

  public static boolean isMenuSeparatorIndicator(Object o) {
    return eqOneOf(o, "***", "---", "===", "");
  }

  public static boolean isRunnableX(Object o) {
    if (o == null)
      return false;
    if (o instanceof String)
      return hasMethod(mc(), (String) o);
    return o instanceof Runnable || hasMethod(o, "get");
  }

  public static boolean jmenuItem_newThreads = false;

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

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

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

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

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

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

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

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

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

  public static boolean isCurlyBracketed(String s) {
    return isCurlyBraced(s);
  }

  public static <A extends JComponent> A setEnabled(A c, boolean enable) {
    if (c != null) {
      swing(new Runnable() {

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

        public String toString() {
          return "c.setEnabled(enable);";
        }
      });
    }
    return c;
  }

  public static <A extends JComponent> A setEnabled(boolean enable, A c) {
    return setEnabled(c, enable);
  }

  public static String unCurlyBracket(String s) {
    return tok_unCurlyBracket(s);
  }

  public static <A, B> Map<A, B> mapMinus(Map<A, B> map, Object... keys) {
    if (empty(keys))
      return map;
    Map<A, B> m2 = cloneMap(map);
    for (Object key : keys) m2.remove(key);
    return m2;
  }

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

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

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

  public static int preferredWidth(Component c) {
    return c == null ? 0 : getPreferredSize(c).width;
  }

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

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

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

  public static File loadImageAsFile(String snippetIDOrURL) {
    try {
      if (isURL(snippetIDOrURL))
        throw fail("not implemented");
      if (!isSnippetID(snippetIDOrURL))
        throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
      String snippetID = "" + parseSnippetID(snippetIDOrURL);
      File 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);
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static int getScreenWidth() {
    return getScreenSize().width;
  }

  public static int getScreenHeight() {
    return getScreenSize().height;
  }

  public static String makeFrame_defaultIcon;

  public static boolean makeFrame_hideConsole = false;

  public static ThreadLocal<VF1<JFrame>> makeFrame_post = new ThreadLocal();

  public static JFrame makeFrame() {
    return makeFrame((Component) null);
  }

  public static JFrame makeFrame(Object content) {
    return makeFrame(programTitle(), content);
  }

  public static JFrame makeFrame(String title) {
    return makeFrame(title, null);
  }

  public static JFrame makeFrame(String title, Object content) {
    return makeFrame(title, content, true);
  }

  public static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
    final VF1<JFrame> post = optParam(makeFrame_post);
    return swing(new F0<JFrame>() {

      public JFrame get() {
        try {
          if (getFrame(content) != null)
            return getFrame(setFrameTitle((Component) content, title));
          final JFrame frame = new JFrame(title);
          if (makeFrame_defaultIcon != null)
            setFrameIconLater(frame, makeFrame_defaultIcon);
          _initFrame(frame);
          Component wrapped = wrap(content);
          if (wrapped != null)
            frame.getContentPane().add(wrapped);
          frame.setBounds(defaultNewFrameBounds());
          callF(post, frame);
          if (showIt)
            frame.setVisible(true);
          if (showIt && makeFrame_hideConsole) {
            hideConsole();
            makeFrame_hideConsole = false;
          }
          return frame;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "if (getFrame(content) != null)\r\n      ret getFrame(setFrameTitle((Component) ...";
      }
    });
  }

  public static boolean frameTooSmall(JFrame frame) {
    return frame.getWidth() < 100 || frame.getHeight() < 50;
  }

  public static void frameStandardSize(JFrame frame) {
    frame.setBounds(300, 100, 500, 400);
  }

  public static void setFrameContents(final Component c, final Object contents) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            JFrame frame = getFrame(c);
            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    frame.getContentPane().removeAll();\r\n    fra...";
        }
      });
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static BufferedImage imageIO_readURL(String url) {
    try {
      if (startsWith(url, "https:"))
        disableCertificateValidation();
      return ImageIO.read(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

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

  public static volatile boolean licensed_yes = true;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static volatile PersistableThrowable lastException_lastException;

  public static PersistableThrowable lastException() {
    return lastException_lastException;
  }

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

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

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

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

  public static Object[] flattenArray2(Object... a) {
    List l = new ArrayList();
    if (a != null)
      for (Object x : a) if (x instanceof Object[])
        l.addAll(asList((Object[]) x));
      else if (x instanceof Collection)
        l.addAll((Collection) x);
      else
        l.add(x);
    return asObjectArray(l);
  }

  public static Component wrapForSmartAdd(Object o) {
    if (o == null)
      return jpanel();
    if (o instanceof String)
      return jlabel((String) o);
    return wrap(o);
  }

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

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

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

  public static Class classForName(String name) {
    try {
      if (classForName_cache == null)
        return Class.forName(name);
      Class c = classForName_cache.get(name);
      if (c == null)
        classForName_cache.put(name, c = Class.forName(name));
      return c;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

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

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

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

  public static boolean containsSpaces(String s) {
    return indexOf(s, ' ') >= 0;
  }

  public static <A> A getOrKeep(Map<A, ? extends A> map, A a) {
    if (map == null)
      return a;
    A v = map.get(a);
    return v != null ? v : a;
  }

  public static List<String> ai_splitCamelCase(String s) {
    int j = 0;
    List<String> l = new ArrayList();
    if (isAllUpperCase(s)) {
      l.add(s);
      return l;
    }
    for (int i = 0; i < l(s); i++) if (isUpperCaseLetter(s.charAt(i)) && i > j) {
      l.add(substring(s, j, i));
      j = i;
    }
    if (j < l(s))
      l.add(substring(s, j));
    return l;
  }

  public static void setChecked(final JCheckBox checkBox, final boolean b) {
    if (checkBox != null) {
      swing(new Runnable() {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static boolean isCurlyBraced(String s) {
    List<String> tok = tok_combineCurlyBrackets_keep(javaTok(s));
    return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
  }

  public static String tok_unCurlyBracket(String s) {
    return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
  }

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

  public static Dimension getPreferredSize(final Component c) {
    return c == null ? null : swing(new F0<Dimension>() {

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

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

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

      public Object invoke(Object proxy, Method method, Object[] args) {
        return call(target, method.getName(), unnull(args));
      }
    });
  }

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

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

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

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

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

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

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

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

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

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

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

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

  public static String dataSnippetLink(String snippetID) {
    long id = parseSnippetID(snippetID);
    if (id >= 1100000 && id < 1200000)
      return imageServerURL() + id;
    if (id >= 1400000 && id < 1500000)
      return "http://butter.botcompany.de:8080/files/" + id + "?_pass=" + muricaPassword();
    if (id >= 1200000 && id < 1300000) {
      String pw = muricaPassword();
      if (empty(pw))
        throw fail("Please set 'murica password by running #1008829");
      return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw;
    } else
      return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=application/binary";
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static void _initFrame(JFrame f) {
    myFrames_list.put(f, Boolean.TRUE);
    standardTitlePopupMenu(f);
  }

  public static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);

  public static Rectangle defaultNewFrameBounds() {
    return swing(new F0<Rectangle>() {

      public Rectangle get() {
        try {
          defaultNewFrameBounds_r.translate(60, 20);
          if (!screenRectangle().contains(defaultNewFrameBounds_r))
            defaultNewFrameBounds_r.setLocation(30 + random(30), 20 + random(20));
          return new Rectangle(defaultNewFrameBounds_r);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "defaultNewFrameBounds_r.translate(60, 20);\r\n    if (!screenRectangle().contai...";
      }
    });
  }

  public static void hideConsole() {
    final JFrame frame = consoleFrame();
    if (frame != null) {
      autoVMExit();
      swingLater(new Runnable() {

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

        public String toString() {
          return "frame.setVisible(false);";
        }
      });
    }
  }

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

  public static void revalidate(JFrame f) {
    revalidate((Component) f);
  }

  public static void revalidate(JInternalFrame f) {
    revalidate((Component) f);
  }

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

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

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

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

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

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

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

  public static String intToHex_flexLength(int i) {
    return Integer.toHexString(i);
  }

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

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

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

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

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

  public static <A> A popLast(List<A> l) {
    return liftLast(l);
  }

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

  public static volatile boolean disableCertificateValidation_attempted = false;

  public static void disableCertificateValidation() {
    try {
      if (disableCertificateValidation_attempted)
        return;
      disableCertificateValidation_attempted = true;
      try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

          public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
          }

          public void checkClientTrusted(X509Certificate[] certs, String authType) {
          }

          public void checkServerTrusted(X509Certificate[] certs, String authType) {
          }
        } };
        HostnameVerifier hv = new HostnameVerifier() {

          public boolean verify(String hostname, SSLSession session) {
            return true;
          }
        };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
      } catch (Throwable __e) {
        _handleException(__e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static File javaxCachesDir_dir;

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

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

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

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

  public static String snippetImageURL(String snippetID, String contentType) {
    if (isURL(snippetID))
      return snippetID;
    long id = parseSnippetID(snippetID);
    String url;
    if (id == 1000010 || id == 1000012)
      url = "http://tinybrain.de:8080/tb/show-blobimage.php?id=" + id;
    else if (isImageServerSnippet(id))
      url = imageServerLink(id);
    else
      url = "https://www.botcompany.de:8443/img/" + id;
    return url;
  }

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

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

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

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

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

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

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

  public static Object[] asObjectArray(List l) {
    return toObjectArray(l);
  }

  public static Map vm_generalMap_map;

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

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

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

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

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

  public static boolean isAllUpperCase(String s) {
    return hasLettersAllUpperCase(s);
  }

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

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

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

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

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

  public static List<String> tok_combineCurlyBrackets_keep(List<String> tok) {
    List<String> l = new ArrayList();
    for (int i = 0; i < l(tok); i++) {
      String t = tok.get(i);
      if (odd(i) && eq(t, "{")) {
        int j = findEndOfCurlyBracketPart(tok, i);
        l.add(joinSubList(tok, i, j));
        i = j - 1;
      } else
        l.add(t);
    }
    return l;
  }

  public static int javaTok_n, javaTok_elements;

  public static boolean javaTok_opt = false;

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

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

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

  public static <A> List<A> dropFirstThreeAndLastThree(List<A> l) {
    return dropFirstAndLast(3, l);
  }

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

  public static int loadPage_defaultTimeout = 60000;

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

  public static boolean loadPage_allowGzip = true, loadPage_debug;

  public static boolean loadPage_anonymous = false;

  public static int loadPage_verboseness = 100000;

  public static int loadPage_retries = 1;

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

  public static volatile int loadPage_forcedTimeout;

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

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

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

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

  public static String loadPageSilently(URL url) {
    try {
      if (url.getProtocol().equals("https"))
        disableCertificateValidation();
      if (!networkAllowanceTest(str(url)))
        throw fail("Not allowed: " + url);
      IOException e = null;
      for (int tries = 0; tries < loadPage_retries; tries++) try {
        URLConnection con = loadPage_openConnection(url);
        return loadPage(con, url);
      } catch (IOException _e) {
        e = _e;
        if (loadPageThroughProxy_enabled) {
          print("Trying proxy because of: " + e);
          try {
            return loadPageThroughProxy(str(url));
          } catch (Throwable e2) {
            print("  " + exceptionToStringShort(e2));
          }
        } else if (loadPage_debug)
          print(exceptionToStringShort(e));
        if (tries < loadPage_retries - 1)
          sleepSeconds(1);
      }
      throw e;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String loadPage_preprocess(String url) {
    if (url.startsWith("tb/"))
      url = tb_mainServer() + "/" + url;
    if (url.indexOf("://") < 0)
      url = "http://" + url;
    return url;
  }

  public static String loadPage(String url) {
    try {
      url = loadPage_preprocess(url);
      if (!isTrue(loadPage_silent.get()))
        printWithTime("Loading: " + hideCredentials(url));
      return loadPageSilently(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String loadPage(URL url) {
    return loadPage(url.toExternalForm());
  }

  public static String loadPage(URLConnection con, URL url) throws IOException {
    return loadPage(con, url, true);
  }

  public static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
    Map<String, String> extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
    if (addHeaders)
      try {
        if (!loadPage_anonymous)
          setHeaders(con);
        if (loadPage_allowGzip)
          con.setRequestProperty("Accept-Encoding", "gzip");
        con.setRequestProperty("X-No-Cookies", "1");
        for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
      } catch (Throwable e) {
      }
    vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
    loadPage_responseHeaders.set(con.getHeaderFields());
    InputStream in = null;
    try {
      in = urlConnection_getInputStream(con);
      if (loadPage_debug)
        print("Put stream in map: " + currentThread());
      String contentType = con.getContentType();
      if (contentType == null) {
        throw new IOException("Page could not be read: " + hideCredentials(url));
      }
      String charset = loadPage_charset == null ? null : loadPage_charset.get();
      if (charset == null)
        charset = loadPage_guessCharset(contentType);
      if ("gzip".equals(con.getContentEncoding())) {
        if (loadPage_debug)
          print("loadPage: Using gzip.");
        in = newGZIPInputStream(in);
      }
      Reader r;
      try {
        r = new InputStreamReader(in, unquote(charset));
      } catch (UnsupportedEncodingException e) {
        print(toHex(utf8(charset)));
        throw e;
      }
      StringBuilder buf = new StringBuilder();
      int n = 0;
      while (true) {
        int ch = r.read();
        if (ch < 0)
          break;
        buf.append((char) ch);
        ++n;
        if ((n % loadPage_verboseness) == 0)
          print("  " + n + " chars read");
      }
      return buf.toString();
    } finally {
      if (loadPage_debug)
        print("loadPage done");
      vm_generalSubMap("URLConnection per thread").remove(currentThread());
      if (in != null)
        in.close();
    }
  }

  public static String loadPage_guessCharset(String contentType) {
    Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
    String match = m.matches() ? m.group(1) : null;
    if (loadPage_debug)
      print("loadPage: contentType=" + contentType + ", match: " + match);
    return or(match, "UTF-8");
  }

  public static URLConnection loadPage_openConnection(URL url) {
    URLConnection con = openConnection(url);
    int timeout = toInt(loadPage_forcedTimeout_byThread.get());
    if (timeout == 0)
      timeout = loadPage_forcedTimeout;
    if (timeout != 0)
      setURLConnectionTimeouts(con, loadPage_forcedTimeout);
    else
      setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
    return con;
  }

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

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

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

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

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

  public static <A> A println(A a) {
    return print(a);
  }

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

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

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

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

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

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

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

  public static volatile boolean muricaPassword_pretendNotAuthed = false;

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

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

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

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

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

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

  public static String getProgramName_cache;

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

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

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

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

  public static void standardTitlePopupMenu(final JFrame frame) {
    if (isSubstanceLAF())
      titlePopupMenu(frame, new VF1<JPopupMenu>() {

        public void get(JPopupMenu menu) {
          try {
            boolean alwaysOnTop = frame.isAlwaysOnTop();
            menu.add(jmenuItem("Restart Program", "restart"));
            menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
            menu.add(jmenuItem("Show Console", "showConsole"));
            menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() {

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

              public String toString() {
                return "toggleAlwaysOnTop(frame)";
              }
            }));
            menu.add(jMenuItem("Shoot Window", new Runnable() {

              public void run() {
                try {
                  shootWindowGUI_external(frame, 500);
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "shootWindowGUI_external(frame, 500)";
              }
            }));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n        menu.add(jmenuItem(\"Restar...";
        }
      });
  }

  public static Rectangle screenRectangle() {
    return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
  }

  public static Random random_random = new Random();

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

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

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

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

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

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

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

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

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

  public static JFrame consoleFrame() {
    return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
  }

  public static void autoVMExit() {
    call(getJavaX(), "autoVMExit");
  }

  public static void restart() {
    Object j = getJavaX();
    call(j, "cleanRestart", get(j, "fullArgs"));
  }

  public static void duplicateThisProgram() {
    nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
  }

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

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

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

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

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

  public static <A> A liftLast(List<A> l) {
    if (l.isEmpty())
      return null;
    int i = l(l) - 1;
    A a = l.get(i);
    l.remove(i);
    return a;
  }

  public static String _userHome;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  public static boolean hasLettersAllUpperCase(String s) {
    return hasLetters(s) && !containsLowerCase(s);
  }

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

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

  public static int findEndOfCurlyBracketPart(List<String> cnc, int i) {
    int j = i + 2, level = 1;
    while (j < cnc.size()) {
      if (eq(cnc.get(j), "{"))
        ++level;
      else if (eq(cnc.get(j), "}"))
        --level;
      if (level == 0)
        return j + 1;
      ++j;
    }
    return cnc.size();
  }

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

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

  public static String joinSubList(List<String> l, IntRange r) {
    return r == null ? null : joinSubList(l, r.start, r.end);
  }

  public static String javaTok_substringN(String s, int i, int j) {
    if (i == j)
      return "";
    if (j == i + 1 && s.charAt(i) == ' ')
      return " ";
    return s.substring(i, j);
  }

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

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

  public static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
    return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
  }

  public static boolean endsWith(String a, String b) {
    return a != null && a.endsWith(b);
  }

  public static boolean endsWith(String a, char c) {
    return nempty(a) && lastChar(a) == c;
  }

  public static boolean endsWith(String a, String b, Matches m) {
    if (!endsWith(a, b))
      return false;
    m.m = new String[] { dropLast(l(b), a) };
    return true;
  }

  public static <A> List<A> dropFirstAndLast(int n, List<A> l) {
    return new ArrayList(subList(l, n, l(l) - n));
  }

  public static <A> List<A> dropFirstAndLast(List<A> l) {
    return dropFirstAndLast(1, l);
  }

  public static String dropFirstAndLast(String s) {
    return substring(s, 1, l(s) - 1);
  }

  public static boolean networkAllowanceTest(String url) {
    return isAllowed("networkAllowanceTest", url);
  }

  public static final boolean loadPageThroughProxy_enabled = false;

  public static String loadPageThroughProxy(String url) {
    return null;
  }

  public static String exceptionToStringShort(Throwable e) {
    lastException(e);
    e = getInnerException(e);
    String msg = hideCredentials(unnull(e.getMessage()));
    if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
      return baseClassName(e) + prependIfNempty(": ", msg);
    else
      return msg;
  }

  public static void sleepSeconds(double s) {
    if (s > 0)
      sleep(round(s * 1000));
  }

  public static String tb_mainServer_default = "http://code.botcompany.de:8081";

  public static Object tb_mainServer_override;

  public static String tb_mainServer() {
    if (tb_mainServer_override != null)
      return (String) callF(tb_mainServer_override);
    return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
  }

  public static File tb_mainServer_file() {
    return getProgramFile("#1001638", "mainserver.txt");
  }

  public static boolean tb_mainServer_isDefault() {
    return eq(tb_mainServer(), tb_mainServer_default);
  }

  public static <A> A printWithTime(A a) {
    print(hmsWithColons() + ": " + a);
    return a;
  }

  public static Map vm_generalSubMap(Object name) {
    synchronized (get(javax(), "generalMap")) {
      Map map = (Map) (vm_generalMap_get(name));
      if (map == null)
        vm_generalMap_put(name, map = synchroMap());
      return map;
    }
  }

  public static InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
    UnknownHostException lastException = null;
    for (int _repeat_1637 = 0; _repeat_1637 < 2; _repeat_1637++) {
      try {
        if (con instanceof HttpURLConnection)
          if (((HttpURLConnection) con).getResponseCode() == 500)
            throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
        return con.getInputStream();
      } catch (UnknownHostException e) {
        lastException = e;
        print("Retrying because of: " + e);
        continue;
      }
    }
    throw lastException;
  }

  public static GZIPInputStream newGZIPInputStream(File f) {
    return gzInputStream(f);
  }

  public static GZIPInputStream newGZIPInputStream(InputStream in) {
    return gzInputStream(in);
  }

  public static String unquote(String s) {
    if (s == null)
      return null;
    if (startsWith(s, '[')) {
      int i = 1;
      while (i < s.length() && s.charAt(i) == '=') ++i;
      if (i < s.length() && s.charAt(i) == '[') {
        String m = s.substring(1, i);
        if (s.endsWith("]" + m + "]"))
          return s.substring(i + 1, s.length() - i - 1);
      }
    }
    if (s.length() > 1) {
      char c = s.charAt(0);
      if (c == '\"' || c == '\'') {
        int l = endsWith(s, c) ? s.length() - 1 : s.length();
        StringBuilder sb = new StringBuilder(l - 1);
        for (int i = 1; i < l; i++) {
          char ch = s.charAt(i);
          if (ch == '\\') {
            char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
            if (nextChar >= '0' && nextChar <= '7') {
              String code = "" + nextChar;
              i++;
              if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
                code += s.charAt(i + 1);
                i++;
                if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
                  code += s.charAt(i + 1);
                  i++;
                }
              }
              sb.append((char) Integer.parseInt(code, 8));
              continue;
            }
            switch(nextChar) {
              case '\"':
                ch = '\"';
                break;
              case '\\':
                ch = '\\';
                break;
              case 'b':
                ch = '\b';
                break;
              case 'f':
                ch = '\f';
                break;
              case 'n':
                ch = '\n';
                break;
              case 'r':
                ch = '\r';
                break;
              case 't':
                ch = '\t';
                break;
              case '\'':
                ch = '\'';
                break;
              case 'u':
                if (i >= l - 5) {
                  ch = 'u';
                  break;
                }
                int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
                sb.append(Character.toChars(code));
                i += 5;
                continue;
              default:
                ch = nextChar;
            }
            i++;
          }
          sb.append(ch);
        }
        return sb.toString();
      }
    }
    return s;
  }

  public static String toHex(byte[] bytes) {
    return bytesToHex(bytes);
  }

  public static String toHex(byte[] bytes, int ofs, int len) {
    return bytesToHex(bytes, ofs, len);
  }

  public static byte[] utf8(String s) {
    return toUtf8(s);
  }

  public static Matcher regexpMatcher(String pat, String s) {
    return compileRegexp(pat).matcher(unnull(s));
  }

  public static URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
    con.setConnectTimeout(toInt(timeout));
    con.setReadTimeout(toInt(timeout));
    if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
      print("Warning: Timeouts not set by JDK.");
    return con;
  }

  public static URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
    if (con.getConnectTimeout() == 0) {
      con.setConnectTimeout(toInt(timeout));
      if (con.getConnectTimeout() != timeout)
        print("Warning: URL connect timeout not set by JDK.");
    }
    if (con.getReadTimeout() == 0) {
      con.setReadTimeout(toInt(timeout));
      if (con.getReadTimeout() != timeout)
        print("Warning: URL read timeout not set by JDK.");
    }
    return con;
  }

  public static String getComputerID_quick() {
    return computerID();
  }

  public static File mkdirsForFile(File file) {
    File dir = file.getParentFile();
    if (dir != null) {
      dir.mkdirs();
      if (!dir.isDirectory())
        if (dir.isFile())
          throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
        else
          throw fail("Unknown IO exception during mkdirs of " + f2s(file));
    }
    return file;
  }

  public static String mkdirsForFile(String path) {
    mkdirsForFile(new File(path));
    return path;
  }

  public static void _registerIO(Object object, String path, boolean opened) {
  }

  public static Object vmBus_wrapArgs(Object... args) {
    return empty(args) ? null : l(args) == 1 ? args[0] : args;
  }

  public static void pcallFAll(Collection l, Object... args) {
    if (l != null)
      for (Object f : cloneList(l)) pcallF(f, args);
  }

  public static void pcallFAll(Iterator it, Object... args) {
    while (it.hasNext()) pcallF(it.next(), args);
  }

  public static Set vm_busListeners_live_cache;

  public static Set vm_busListeners_live() {
    if (vm_busListeners_live_cache == null)
      vm_busListeners_live_cache = vm_busListeners_live_load();
    return vm_busListeners_live_cache;
  }

  public static Set vm_busListeners_live_load() {
    return vm_generalIdentityHashSet("busListeners");
  }

  public static String loadTextFile(String fileName) {
    return loadTextFile(fileName, null);
  }

  public static String loadTextFile(File f, String defaultContents) {
    try {
      checkFileNotTooBigToRead(f);
      if (f == null || !f.exists())
        return defaultContents;
      FileInputStream fileInputStream = new FileInputStream(f);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
      return loadTextFile(inputStreamReader);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String loadTextFile(File fileName) {
    return loadTextFile(fileName, null);
  }

  public static String loadTextFile(String fileName, String defaultContents) {
    return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
  }

  public static String loadTextFile(Reader reader) throws IOException {
    StringBuilder builder = new StringBuilder();
    try {
      char[] buffer = new char[1024];
      int n;
      while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
    } finally {
      reader.close();
    }
    return str(builder);
  }

  public static File javaxDataDir_dir;

  public static File javaxDataDir() {
    return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
  }

  public static File javaxDataDir(String... subs) {
    return newFile(javaxDataDir(), subs);
  }

  public static File muricaPasswordFile() {
    return new File(javaxSecretDir(), "murica/muricaPasswordFile");
  }

  public static int roundDownTo(int x, int n) {
    return x / n * n;
  }

  public static long roundDownTo(long x, long n) {
    return x / n * n;
  }

  public static String quote(Object o) {
    if (o == null)
      return "null";
    return quote(str(o));
  }

  public static String quote(String s) {
    if (s == null)
      return "null";
    StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
    quote_impl(s, out);
    return out.toString();
  }

  public static void quote_impl(String s, StringBuilder out) {
    out.append('"');
    int l = s.length();
    for (int i = 0; i < l; i++) {
      char c = s.charAt(i);
      if (c == '\\' || c == '"')
        out.append('\\').append(c);
      else if (c == '\r')
        out.append("\\r");
      else if (c == '\n')
        out.append("\\n");
      else if (c == '\0')
        out.append("\\0");
      else
        out.append(c);
    }
    out.append('"');
  }

  public static int shorten_default = 100;

  public static String shorten(String s) {
    return shorten(s, shorten_default);
  }

  public static String shorten(String s, int max) {
    return shorten(s, max, "...");
  }

  public static String shorten(String s, int max, String shortener) {
    if (s == null)
      return "";
    if (max < 0)
      return s;
    return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener;
  }

  public static String shorten(int max, String s) {
    return shorten(s, max);
  }

  public static 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;
  }

  public static Lock downloadLock_lock = fairLock();

  public static Lock downloadLock() {
    return downloadLock_lock;
  }

  public static String getSnippetTitleOpt(String s) {
    return isSnippetID(s) ? getSnippetTitle(s) : s;
  }

  public static boolean isSubstanceLAF() {
    return substanceLookAndFeelEnabled();
  }

  public static boolean titlePopupMenu(final Component c, final Object menuMaker) {
    JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c));
    if (titleBar == null) {
      print("Can't add title right click!");
      return false;
    } else {
      componentPopupMenu(titleBar, menuMaker);
      return true;
    }
  }

  public static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
    final JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
    addActionListener(mi, new Runnable() {

      public void run() {
        try {
          callF(r, isChecked(mi));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(r, isChecked(mi))";
      }
    });
    return mi;
  }

  public static void toggleAlwaysOnTop(JFrame frame) {
    frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
  }

  public static void shootWindowGUI_external(JFrame frame) {
    call(hotwireOnce("#1007178"), "shootWindowGUI", frame);
  }

  public static void shootWindowGUI_external(final JFrame frame, int delay) {
    call(hotwireOnce("#1007178"), "shootWindowGUI", frame, delay);
  }

  public static <A> A oneOf(List<A> l) {
    return empty(l) ? null : l.get(new Random().nextInt(l.size()));
  }

  public static char oneOf(String s) {
    return empty(s) ? '?' : s.charAt(random(l(s)));
  }

  public static String oneOf(String... l) {
    return oneOf(asList(l));
  }

  public static <A> A collectionGet(Collection<A> c, int idx) {
    if (c == null || idx < 0 || idx >= l(c))
      return null;
    if (c instanceof List)
      return listGet((List<A>) c, idx);
    Iterator<A> it = c.iterator();
    for (int i = 0; i < idx; i++) if (it.hasNext())
      it.next();
    else
      return null;
    return it.hasNext() ? it.next() : null;
  }

  public static void nohupJavax(final String javaxargs) {
    {
      startThread(new Runnable() {

        public void run() {
          try {
            call(hotwireOnce("#1008562"), "nohupJavax", javaxargs);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs);";
        }
      });
    }
  }

  public static void nohupJavax(final String javaxargs, final String vmArgs) {
    {
      startThread(new Runnable() {

        public void run() {
          try {
            call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs, vmArgs);";
        }
      });
    }
  }

  public static String smartJoin(String[] args) {
    if (empty(args))
      return "";
    if (args.length == 1)
      return args[0];
    String[] a = new String[args.length];
    for (int i = 0; i < a.length; i++) a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i];
    return join(" ", a);
  }

  public static String smartJoin(List<String> args) {
    return smartJoin(toStringArray(args));
  }

  public static <A> ArrayList<A> cloneListSynchronizingOn(Collection<A> l, Object mutex) {
    if (l == null)
      return new ArrayList();
    synchronized (mutex) {
      return new ArrayList<A>(l);
    }
  }

  public static String actualUserHome_value;

  public static String actualUserHome() {
    if (actualUserHome_value == null) {
      if (isAndroid())
        actualUserHome_value = "/storage/emulated/0/";
      else
        actualUserHome_value = System.getProperty("user.home");
    }
    return actualUserHome_value;
  }

  public static File actualUserHome(String sub) {
    return newFile(new File(actualUserHome()), sub);
  }

  public static File userDir() {
    return new File(userHome());
  }

  public static File userDir(String path) {
    return new File(userHome(), path);
  }

  public static boolean possibleMD5(String s) {
    return isMD5(s);
  }

  public static boolean eqic(String a, String b) {
    if ((a == null) != (b == null))
      return false;
    if (a == null)
      return true;
    return a.equalsIgnoreCase(b);
  }

  public static boolean eqic(char a, char b) {
    if (a == b)
      return true;
    char u1 = Character.toUpperCase(a);
    char u2 = Character.toUpperCase(b);
    if (u1 == u2)
      return true;
    return Character.toLowerCase(u1) == Character.toLowerCase(u2);
  }

  public static boolean hasLetters(String s) {
    for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i)))
      return true;
    return false;
  }

  public static boolean containsLowerCase(String s) {
    for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i)))
      return true;
    return false;
  }

  public static <A> List<A> subList(List<A> l, int startIndex) {
    return subList(l, startIndex, l(l));
  }

  public static <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
    if (l == null)
      return null;
    int n = l(l);
    startIndex = Math.max(0, startIndex);
    endIndex = Math.min(n, endIndex);
    if (startIndex >= endIndex)
      return ll();
    if (startIndex == 0 && endIndex == n)
      return l;
    return l.subList(startIndex, endIndex);
  }

  public static <A> List<A> subList(List<A> l, IntRange r) {
    return subList(l, r.start, r.end);
  }

  public static char lastChar(String s) {
    return empty(s) ? '\0' : s.charAt(l(s) - 1);
  }

  public static String[] dropLast(String[] a, int n) {
    n = Math.min(n, a.length);
    String[] b = new String[a.length - n];
    System.arraycopy(a, 0, b, 0, b.length);
    return b;
  }

  public static <A> List<A> dropLast(List<A> l) {
    return subList(l, 0, l(l) - 1);
  }

  public static <A> List<A> dropLast(int n, List<A> l) {
    return subList(l, 0, l(l) - n);
  }

  public static <A> List<A> dropLast(Iterable<A> l) {
    return dropLast(asList(l));
  }

  public static String dropLast(String s) {
    return substring(s, 0, l(s) - 1);
  }

  public static String dropLast(String s, int n) {
    return substring(s, 0, l(s) - n);
  }

  public static String dropLast(int n, String s) {
    return dropLast(s, n);
  }

  public static volatile Object isAllowed_function;

  public static volatile boolean isAllowed_all = true;

  public static boolean isAllowed(String askingMethod, Object... args) {
    Object f = vm_generalMap_get("isAllowed_function");
    if (f != null && !isTrue(callF(f, askingMethod, args)))
      return false;
    return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
  }

  public static String baseClassName(String className) {
    return substring(className, className.lastIndexOf('.') + 1);
  }

  public static String baseClassName(Object o) {
    return baseClassName(getClassName(o));
  }

  public static String prependIfNempty(String prefix, String s) {
    return empty(s) ? s : prefix + s;
  }

  public static volatile boolean sleep_noSleep = false;

  public static void sleep(long ms) {
    ping();
    if (ms < 0)
      return;
    if (isAWTThread() && ms > 100)
      throw fail("Should not sleep on AWT thread");
    try {
      Thread.sleep(ms);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static void sleep() {
    try {
      if (sleep_noSleep)
        throw fail("nosleep");
      print("Sleeping.");
      sleepQuietly();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static long round(double d) {
    return Math.round(d);
  }

  public static File getProgramFile(String progID, String fileName) {
    if (new File(fileName).isAbsolute())
      return new File(fileName);
    return new File(getProgramDir(progID), fileName);
  }

  public static File getProgramFile(String fileName) {
    return getProgramFile(getProgramID(), fileName);
  }

  public static String hmsWithColons() {
    return hmsWithColons(now());
  }

  public static String hmsWithColons(long time) {
    return new SimpleDateFormat("HH:mm:ss").format(time);
  }

  public static Object vm_generalMap_put(Object key, Object value) {
    return mapPutOrRemove(vm_generalMap(), key, value);
  }

  public static Map synchroMap() {
    return synchroHashMap();
  }

  public static <A, B> Map<A, B> synchroMap(Map<A, B> map) {
    return Collections.synchronizedMap(map);
  }

  public static String joinNemptiesWithColonSpace(String... strings) {
    return joinNempties(": ", strings);
  }

  public static String joinNemptiesWithColonSpace(Collection<String> strings) {
    return joinNempties(": ", strings);
  }

  public static String tryToReadErrorStreamFromURLConnection(URLConnection conn) {
    try {
      if (conn instanceof HttpURLConnection)
        return stream2string(((HttpURLConnection) conn).getErrorStream());
      return null;
    } catch (Throwable __e) {
      return null;
    }
  }

  public static int gzInputStream_defaultBufferSize = 65536;

  public static GZIPInputStream gzInputStream(File f) {
    try {
      return gzInputStream(new FileInputStream(f));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static GZIPInputStream gzInputStream(File f, int bufferSize) {
    try {
      return gzInputStream(new FileInputStream(f), bufferSize);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static GZIPInputStream gzInputStream(InputStream in) {
    return gzInputStream(in, gzInputStream_defaultBufferSize);
  }

  public static GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
    try {
      return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

  public static String bytesToHex(byte[] bytes, int ofs, int len) {
    StringBuilder stringBuilder = new StringBuilder(len * 2);
    for (int i = 0; i < len; i++) {
      String s = "0" + Integer.toHexString(bytes[ofs + i]);
      stringBuilder.append(s.substring(s.length() - 2, s.length()));
    }
    return stringBuilder.toString();
  }

  public static byte[] toUtf8(String s) {
    try {
      return s.getBytes("UTF-8");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static Map<String, java.util.regex.Pattern> compileRegexp_cache = syncMRUCache(10);

  public static java.util.regex.Pattern compileRegexp(String pat) {
    java.util.regex.Pattern p = compileRegexp_cache.get(pat);
    if (p == null) {
      compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
    }
    return p;
  }

  public static String _computerID;

  public static Lock computerID_lock = lock();

  public static String computerID() {
    if (_computerID == null) {
      Lock __2097 = computerID_lock;
      lock(__2097);
      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(__2097);
      }
    }
    return _computerID;
  }

  public static ThreadLocal<VF1<File>> checkFileNotTooBigToRead_tl = new ThreadLocal();

  public static void checkFileNotTooBigToRead(File f) {
    callF(checkFileNotTooBigToRead_tl.get(), f);
  }

  public static File javaxSecretDir_dir;

  public static File javaxSecretDir() {
    return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
  }

  public static File javaxSecretDir(String sub) {
    return newFile(javaxSecretDir(), sub);
  }

  public static int charDiff(char a, char b) {
    return (int) a - (int) b;
  }

  public static int charDiff(String a, char b) {
    return charDiff(stringToChar(a), b);
  }

  public static String getSnippetTitle(String id) {
    try {
      if (id == null)
        return null;
      if (!isSnippetID(id))
        return "?";
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.getSnippetTitle(id);
      if (isLocalSnippetID(id))
        return localSnippetTitle(id);
      long parsedID = parseSnippetID(id);
      String url;
      if (isImageServerSnippet(parsedID))
        url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery();
      else if (isGeneralFileServerSnippet(parsedID))
        url = "http://butter.botcompany.de:8080/files/name/" + parsedID;
      else
        url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies();
      String title = trim(loadPageSilently(url));
      if (title != null)
        try {
          saveTextFileIfChanged(snippetTitle_cacheFile(id), title);
        } catch (Throwable __e) {
          print(exceptionToStringShort(__e));
        }
      return or(title, "?");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String getSnippetTitle(long id) {
    return getSnippetTitle(fsI(id));
  }

  public static boolean substanceLookAndFeelEnabled() {
    return startsWith(getLookAndFeel(), "org.pushingpixels.");
  }

  public static JComponent getTitlePaneComponent(RootPaneContainer window) {
    if (window instanceof JInternalFrame)
      return getInternalFrameTitlePaneComponent((JInternalFrame) window);
    if (!substanceLookAndFeelEnabled() || window == null)
      return null;
    JRootPane rootPane = window.getRootPane();
    if (rootPane != null) {
      Object ui = rootPane.getUI();
      return (JComponent) call(ui, "getTitlePane");
    }
    return null;
  }

  public static RootPaneContainer getPossiblyInternalFrame(Component c) {
    JInternalFrame f = getInternalFrame(c);
    if (f != null)
      return f;
    return optCast(RootPaneContainer.class, getWindow(c));
  }

  public static Class hotwireOnce(String programID) {
    return hotwireCached(programID, false);
  }

  public static <A> A listGet(List<A> l, int idx) {
    return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
  }

  public static boolean isQuoted(String s) {
    if (isNormalQuoted(s))
      return true;
    return isMultilineQuoted(s);
  }

  public static String[] toStringArray(Collection<String> c) {
    String[] a = new String[l(c)];
    Iterator<String> it = c.iterator();
    for (int i = 0; i < l(a); i++) a[i] = it.next();
    return a;
  }

  public static String[] toStringArray(Object o) {
    if (o instanceof String[])
      return (String[]) o;
    else if (o instanceof Collection)
      return toStringArray((Collection<String>) o);
    else
      throw fail("Not a collection or array: " + getClassName(o));
  }

  public static boolean isMD5(String s) {
    return l(s) == 32 && isLowerHexString(s);
  }

  public static String asString(Object o) {
    return o == null ? null : o.toString();
  }

  public static boolean isLowerCase(char c) {
    return Character.isLowerCase(c);
  }

  public static Object sleepQuietly_monitor = new Object();

  public static void sleepQuietly() {
    try {
      assertFalse(isAWTThread());
      synchronized (sleepQuietly_monitor) {
        sleepQuietly_monitor.wait();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static File getProgramDir() {
    return programDir();
  }

  public static File getProgramDir(String snippetID) {
    return programDir(snippetID);
  }

  public static long now_virtualTime;

  public static long now() {
    return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
  }

  public static <A, B> B mapPutOrRemove(Map<A, B> map, A key, B value) {
    if (map != null && key != null)
      if (value != null)
        return map.put(key, value);
      else
        return map.remove(key);
    return null;
  }

  public static String joinNempties(String sep, String... strings) {
    return joinStrings(sep, strings);
  }

  public static String joinNempties(String sep, Collection<String> strings) {
    return joinStrings(sep, strings);
  }

  public static String stream2string(InputStream in) {
    return utf8streamToString(in);
  }

  public static <A> A _registerIOWrap(A wrapper, Object wrapped) {
    return wrapper;
  }

  public static <A, B> Map<A, B> syncMRUCache(int size) {
    return synchroMap(new MRUCache(size));
  }

  public static File computerIDFile() {
    return javaxDataDir("Basic Info/computer-id.txt");
  }

  public static String makeRandomID(int length) {
    return makeRandomID(length, defaultRandomGenerator());
  }

  public static String makeRandomID(int length, Random random) {
    char[] id = new char[length];
    for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
    return new String(id);
  }

  public static String makeRandomID(Random r, int length) {
    return makeRandomID(length, r);
  }

  public static File saveTextFile(String fileName, String contents) throws IOException {
    CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
    try {
      File file = new File(fileName);
      mkdirsForFile(file);
      String tempFileName = fileName + "_temp";
      File tempFile = new File(tempFileName);
      if (contents != null) {
        if (tempFile.exists())
          try {
            String saveName = tempFileName + ".saved." + now();
            copyFile(tempFile, new File(saveName));
          } catch (Throwable e) {
            printStackTrace(e);
          }
        FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
        PrintWriter printWriter = new PrintWriter(outputStreamWriter);
        printWriter.print(contents);
        printWriter.close();
      }
      if (file.exists() && !file.delete())
        throw new IOException("Can't delete " + fileName);
      if (contents != null)
        if (!tempFile.renameTo(file))
          throw new IOException("Can't rename " + tempFile + " to " + file);
      vmBus_send("wroteFile", file);
      return file;
    } finally {
      action.done();
    }
  }

  public static File saveTextFile(File fileName, String contents) {
    try {
      saveTextFile(fileName.getPath(), contents);
      return fileName;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static char stringToChar(String s) {
    if (l(s) != 1)
      throw fail("bad stringToChar: " + s);
    return firstChar(s);
  }

  public static boolean isLocalSnippetID(String snippetID) {
    return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
  }

  public static boolean isLocalSnippetID(long snippetID) {
    return snippetID >= 1000 && snippetID <= 9999;
  }

  public static String localSnippetTitle(String snippetID) {
    if (!isLocalSnippetID(snippetID))
      return null;
    File f = localSnippetFile(snippetID);
    if (!f.exists())
      return null;
    return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed");
  }

  public static String muricaCredentialsQuery() {
    return htmlQuery(muricaCredentials());
  }

  public static boolean isGeneralFileServerSnippet(long id) {
    return id >= 1400000 && id < 1500000;
  }

  public static String standardCredentials_noCookies() {
    return standardCredentials() + "&noCookies=1";
  }

  public static boolean saveTextFileIfChanged(File f, String contents) {
    return saveTextFileIfDifferent(f, contents);
  }

  public static File snippetTitle_cacheFile(String snippetID) {
    return javaxCachesDir("Snippet Titles/" + psI(snippetID));
  }

  public static String getLookAndFeel() {
    return getClassName(UIManager.getLookAndFeel());
  }

  public static JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) {
    return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane");
  }

  public static 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...";
      }
    });
  }

  public static <A> A optCast(Class<A> c, Object o) {
    return isInstance(c, o) ? (A) o : null;
  }

  public static TreeMap<String, Class> hotwireCached_cache = new TreeMap();

  public static Lock hotwireCached_lock = lock();

  public static Class hotwireCached(String programID) {
    return hotwireCached(programID, true);
  }

  public static Class hotwireCached(String programID, boolean runMain) {
    return hotwireCached(programID, runMain, false);
  }

  public static Class hotwireCached(String programID, boolean runMain, boolean dependent) {
    Lock __2822 = hotwireCached_lock;
    lock(__2822);
    try {
      programID = formatSnippetID(programID);
      Class c = hotwireCached_cache.get(programID);
      if (c == null) {
        c = hotwire(programID);
        if (dependent)
          makeDependent(c);
        if (runMain)
          callMain(c);
        hotwireCached_cache.put(programID, c);
      }
      return c;
    } finally {
      unlock(__2822);
    }
  }

  public static boolean isNormalQuoted(String s) {
    int l = l(s);
    if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"'))
      return false;
    int j = 1;
    while (j < l) if (s.charAt(j) == '"')
      return j == l - 1;
    else if (s.charAt(j) == '\\' && j + 1 < l)
      j += 2;
    else
      ++j;
    return false;
  }

  public static boolean isMultilineQuoted(String s) {
    if (!startsWith(s, "["))
      return false;
    int i = 1;
    while (i < s.length() && s.charAt(i) == '=') ++i;
    return i < s.length() && s.charAt(i) == '[';
  }

  public static boolean isLowerHexString(String s) {
    for (int i = 0; i < l(s); i++) {
      char c = s.charAt(i);
      if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
      } else
        return false;
    }
    return true;
  }

  public static void assertFalse(Object o) {
    if (!(eq(o, false)))
      throw fail(str(o));
  }

  public static boolean assertFalse(boolean b) {
    if (b)
      throw fail("oops");
    return b;
  }

  public static boolean assertFalse(String msg, boolean b) {
    if (b)
      throw fail(msg);
    return b;
  }

  public static File programDir_mine;

  public static File programDir() {
    return programDir(getProgramID());
  }

  public static File programDir(String snippetID) {
    boolean me = sameSnippetID(snippetID, programID());
    if (programDir_mine != null && me)
      return programDir_mine;
    File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
    if (me) {
      String c = caseID();
      if (nempty(c))
        dir = newFile(dir, c);
    }
    return dir;
  }

  public static File programDir(String snippetID, String subPath) {
    return new File(programDir(snippetID), subPath);
  }

  public static String joinStrings(String sep, String... strings) {
    return joinStrings(sep, Arrays.asList(strings));
  }

  public static String joinStrings(String sep, Collection<String> strings) {
    StringBuilder buf = new StringBuilder();
    for (String s : unnull(strings)) if (nempty(s)) {
      if (nempty(buf))
        buf.append(sep);
      buf.append(s);
    }
    return str(buf);
  }

  public static String utf8streamToString(InputStream in) {
    return readerToString(utf8bufferedReader(in));
  }

  public static Random defaultRandomGenerator() {
    return ThreadLocalRandom.current();
  }

  public static List<CriticalAction> beginCriticalAction_inFlight = synchroList();

  public static class CriticalAction {

    public String description;

    public CriticalAction() {
    }

    public CriticalAction(String description) {
      this.description = description;
    }

    public void done() {
      beginCriticalAction_inFlight.remove(this);
    }
  }

  public static CriticalAction beginCriticalAction(String description) {
    ping();
    CriticalAction c = new CriticalAction(description);
    beginCriticalAction_inFlight.add(c);
    return c;
  }

  public static void cleanMeUp_beginCriticalAction() {
    int n = 0;
    while (nempty(beginCriticalAction_inFlight)) {
      int m = l(beginCriticalAction_inFlight);
      if (m != n) {
        n = m;
        try {
          print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
      sleepInCleanUp(10);
    }
  }

  public static void copyFile(File src, File dest) {
    try {
      FileInputStream inputStream = new FileInputStream(src.getPath());
      FileOutputStream outputStream = newFileOutputStream(dest.getPath());
      try {
        copyStream(inputStream, outputStream);
        inputStream.close();
      } finally {
        outputStream.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static char firstChar(String s) {
    return s.charAt(0);
  }

  public static File localSnippetFile(long snippetID) {
    return localSnippetsDir(snippetID + ".text");
  }

  public static File localSnippetFile(String snippetID) {
    return localSnippetFile(parseSnippetID(snippetID));
  }

  public static String getFileInfoField(File f, String field) {
    return getOneLineFileInfoField(f, field);
  }

  public static File dropExtension(File f) {
    return f == null ? null : fileInSameDir(f, dropExtension(f.getName()));
  }

  public static String dropExtension(String s) {
    return takeFirst(s, smartLastIndexOf(s, '.'));
  }

  public static String htmlQuery(Map params) {
    return empty(params) ? "" : "?" + makePostData(params);
  }

  public static String htmlQuery(Object... data) {
    return empty(data) ? "" : "?" + makePostData(data);
  }

  public static Object[] muricaCredentials() {
    String pass = muricaPassword();
    return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0];
  }

  public static String standardCredentials() {
    String user = standardCredentialsUser();
    String pass = standardCredentialsPass();
    if (nempty(user) && nempty(pass))
      return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
    return "";
  }

  public static boolean saveTextFileIfDifferent(File f, String contents) {
    if (eq(loadTextFile(f), contents))
      return false;
    {
      saveTextFile(f, contents);
      return true;
    }
  }

  public static Component childWithClassNameEndingWith(Component c, String suffix) {
    if (endsWith(className(c), suffix))
      return c;
    Component x;
    for (Component comp : getComponents(c)) if ((x = childWithClassNameEndingWith(comp, suffix)) != null)
      return x;
    return null;
  }

  public static Class<?> hotwire(String src) {
    assertFalse(_inCore());
    Class j = getJavaX();
    if (isAndroid()) {
      synchronized (j) {
        List<File> libraries = new ArrayList<File>();
        File srcDir = (File) call(j, "transpileMain", src, libraries);
        if (srcDir == null)
          throw fail("transpileMain returned null (src=" + quote(src) + ")");
        Object androidContext = get(j, "androidContext");
        return (Class) call(j, "loadx2android", srcDir, src);
      }
    } else {
      Class c = (Class) (call(j, "hotwire", src));
      hotwire_copyOver(c);
      return c;
    }
  }

  public static Object makeDependent_postProcess;

  public static void makeDependent(Object c) {
    if (c == null)
      return;
    assertTrue("Not a class", c instanceof Class);
    dependentClasses();
    hotwire_classes.add(new WeakReference(c));
    Object local_log = getOpt(mc(), "local_log");
    if (local_log != null)
      setOpt(c, "local_log", local_log);
    Object print_byThread = getOpt(mc(), "print_byThread");
    if (print_byThread != null)
      setOpt(c, "print_byThread", print_byThread);
    callF(makeDependent_postProcess, c);
  }

  public static <A> A callMain(A c, String... args) {
    callOpt(c, "main", new Object[] { args });
    return c;
  }

  public static void callMain() {
    callMain(mc());
  }

  public static boolean sameSnippetID(String a, String b) {
    if (!isSnippetID(a) || !isSnippetID(b))
      return false;
    return parseSnippetID(a) == parseSnippetID(b);
  }

  public static volatile String caseID_caseID;

  public static String caseID() {
    return caseID_caseID;
  }

  public static void caseID(String id) {
    caseID_caseID = id;
  }

  public static String readerToString(Reader r) {
    try {
      try {
        StringBuilder buf = new StringBuilder();
        int n = 0;
        while (true) {
          int ch = r.read();
          if (ch < 0)
            break;
          buf.append((char) ch);
          ++n;
        }
        return buf.toString();
      } finally {
        r.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static BufferedReader utf8bufferedReader(InputStream in) {
    try {
      return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static BufferedReader utf8bufferedReader(File f) {
    try {
      return utf8bufferedReader(newFileInputStream(f));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static List collect(Collection c, String field) {
    return collectField(c, field);
  }

  public static List collect(String field, Collection c) {
    return collectField(c, field);
  }

  public static void sleepInCleanUp(long ms) {
    try {
      if (ms < 0)
        return;
      Thread.sleep(ms);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static void copyStream(InputStream in, OutputStream out) {
    try {
      byte[] buf = new byte[65536];
      while (true) {
        int n = in.read(buf);
        if (n <= 0)
          return;
        out.write(buf, 0, n);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static File localSnippetsDir() {
    return javaxDataDir("Personal Programs");
  }

  public static File localSnippetsDir(String sub) {
    return newFile(localSnippetsDir(), sub);
  }

  public static String getOneLineFileInfoField(File f, String field) {
    File infoFile = associatedInfosFile(f);
    List<String> lines = lines(loadTextFile(infoFile));
    return firstStartingWithIC_drop(lines, field + ": ");
  }

  public static File fileInSameDir(File f, String newName) {
    return newFile(parentFile(f), newName);
  }

  public static <A> List<A> takeFirst(List<A> l, int n) {
    return l(l) <= n ? l : newSubListOrSame(l, 0, n);
  }

  public static <A> List<A> takeFirst(int n, List<A> l) {
    return takeFirst(l, n);
  }

  public static String takeFirst(int n, String s) {
    return substring(s, 0, n);
  }

  public static String takeFirst(String s, int n) {
    return substring(s, 0, n);
  }

  public static <A> List<A> takeFirst(int n, Iterable<A> i) {
    List l = new ArrayList();
    Iterator<A> it = i.iterator();
    for (int _repeat_375 = 0; _repeat_375 < n; _repeat_375++) {
      if (it.hasNext())
        l.add(it.next());
      else
        break;
    }
    return l;
  }

  public static int smartLastIndexOf(String s, char c) {
    if (s == null)
      return 0;
    int i = s.lastIndexOf(c);
    return i >= 0 ? i : l(s);
  }

  public static String makePostData(Map<Object, Object> map) {
    StringBuilder buf = new StringBuilder();
    for (Map.Entry<Object, Object> e : map.entrySet()) {
      String key = (String) (e.getKey());
      Object val = e.getValue();
      if (val != null) {
        String value = str(val);
        if (nempty(buf))
          buf.append("&");
        buf.append(urlencode(key)).append("=").append(urlencode((value)));
      }
    }
    return str(buf);
  }

  public static String makePostData(Object... params) {
    StringBuilder buf = new StringBuilder();
    int n = l(params);
    for (int i = 0; i + 1 < n; i += 2) {
      String key = (String) (params[i]);
      Object val = params[i + 1];
      if (val != null) {
        String value = str(val);
        if (nempty(buf))
          buf.append("&");
        buf.append(urlencode(key)).append("=").append(urlencode((value)));
      }
    }
    return str(buf);
  }

  public static String standardCredentialsUser() {
    return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username"))));
  }

  public static String standardCredentialsPass() {
    return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass"))));
  }

  public static String urlencode(String x) {
    try {
      return URLEncoder.encode(unnull(x), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

  public static List<Component> getComponents(final Component c) {
    return !(c instanceof Container) ? emptyList() : asList(swing(new F0<Component[]>() {

      public Component[] get() {
        try {
          return ((Container) c).getComponents();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret ((Container) c).getComponents();";
      }
    }));
  }

  public static boolean _inCore() {
    return false;
  }

  public static List hotwire_copyOver_after = synchroList();

  public static void hotwire_copyOver(Class c) {
    for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field));
    setOptIfNotNull(c, "mainBot", getMainBot());
    setOpt(c, "creator_class", new WeakReference(mc()));
    pcallFAll(hotwire_copyOver_after, c);
  }

  public static List<Class> dependentClasses() {
    return cleanUpAndGetWeakReferencesList(hotwire_classes);
  }

  public static List<WeakReference<Class>> hotwire_classes = synchroList();

  public static Class<?> hotwireDependent(String src) {
    Class c = hotwire(src);
    makeDependent(c);
    return c;
  }

  public static BufferedReader bufferedReader(Reader r) {
    return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
  }

  public static FileInputStream newFileInputStream(File path) throws IOException {
    return newFileInputStream(path.getPath());
  }

  public static FileInputStream newFileInputStream(String path) throws IOException {
    FileInputStream f = new FileInputStream(path);
    _registerIO(f, path, true);
    return f;
  }

  public static List collectField(Collection c, String field) {
    List l = new ArrayList();
    if (c != null)
      for (Object a : c) l.add(getOpt(a, field));
    return l;
  }

  public static List collectField(String field, Collection c) {
    return collectField(c, field);
  }

  public static File associatedInfosFile(File f) {
    return replaceExtension(f, ".infos");
  }

  public static String lines(Iterable lines) {
    return fromLines(lines);
  }

  public static String lines(Object[] lines) {
    return fromLines(asList(lines));
  }

  public static List<String> lines(String s) {
    return toLines(s);
  }

  public static String firstStartingWithIC_drop(Collection<String> l, final String prefix) {
    for (String s : unnull(l)) if (swic(s, prefix))
      return substring(s, l(prefix));
    return null;
  }

  public static String firstStartingWithIC_drop(String prefix, Collection<String> l) {
    return firstStartingWithIC_drop(l, prefix);
  }

  public static File parentFile(File f) {
    return dirOfFile(f);
  }

  public static <A> List<A> newSubListOrSame(List<A> l, int startIndex) {
    return newSubListOrSame(l, startIndex, l(l));
  }

  public static <A> List<A> newSubListOrSame(List<A> l, int startIndex, int endIndex) {
    if (l == null)
      return null;
    int n = l(l);
    startIndex = max(0, startIndex);
    endIndex = min(n, endIndex);
    if (startIndex >= endIndex)
      return ll();
    if (startIndex == 0 && endIndex == n)
      return l;
    return cloneList(l.subList(startIndex, endIndex));
  }

  public static <A> List<A> newSubListOrSame(List<A> l, IntRange r) {
    return newSubListOrSame(l, r.start, r.end);
  }

  public static File oneOfTheFiles(String... paths) {
    if (paths != null)
      for (String path : paths) if (fileExists(path))
        return newFile(path);
    return null;
  }

  public static File oneOfTheFiles(File... files) {
    if (files != null)
      for (File f : files) if (fileExists(f))
        return f;
    return null;
  }

  public static void setOptIfNotNull(Object o, String field, Object value) {
    if (value != null)
      setOpt(o, field, value);
  }

  public static Object mainBot;

  public static Object getMainBot() {
    return mainBot;
  }

  public static <A> List<A> cleanUpAndGetWeakReferencesList(List<WeakReference<A>> l) {
    if (l == null)
      return null;
    synchronized (l) {
      List<A> out = new ArrayList();
      for (int i = 0; i < l(l); i++) {
        A a = l.get(i).get();
        if (a == null)
          l.remove(i--);
        else
          out.add(a);
      }
      return out;
    }
  }

  public static File replaceExtension(File f, String extOld, String extNew) {
    return newFile(replaceExtension(f2s(f), extOld, extNew));
  }

  public static File replaceExtension(File f, String extNew) {
    return replaceExtension(f, fileExtension(f), extNew);
  }

  public static String replaceExtension(String s, String extOld, String extNew) {
    s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s);
    return s + addPrefixOptIfNempty(".", extNew);
  }

  public static String replaceExtension(String name, String extNew) {
    return replaceExtension(name, fileExtension(name), extNew);
  }

  public static String fromLines(Iterable lines) {
    StringBuilder buf = new StringBuilder();
    if (lines != null)
      for (Object line : lines) buf.append(str(line)).append('\n');
    return buf.toString();
  }

  public static String fromLines(String... lines) {
    return fromLines(asList(lines));
  }

  public static IterableIterator<String> toLines(File f) {
    return linesFromFile(f);
  }

  public static List<String> toLines(String s) {
    List<String> lines = new ArrayList<String>();
    if (s == null)
      return lines;
    int start = 0;
    while (true) {
      int i = toLines_nextLineBreak(s, start);
      if (i < 0) {
        if (s.length() > start)
          lines.add(s.substring(start));
        break;
      }
      lines.add(s.substring(start, i));
      if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
        i += 2;
      else
        ++i;
      start = i;
    }
    return lines;
  }

  public static int toLines_nextLineBreak(String s, int start) {
    for (int i = start; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c == '\r' || c == '\n')
        return i;
    }
    return -1;
  }

  public static File dirOfFile(File f) {
    return f == null ? null : f.getParentFile();
  }

  public static boolean fileExists(String path) {
    return path != null && new File(path).exists();
  }

  public static boolean fileExists(File f) {
    return f != null && f.exists();
  }

  public static String fileExtension(File f) {
    if (f == null)
      return null;
    return fileExtension(f.getName());
  }

  public static String fileExtension(String s) {
    return substring(s, smartLastIndexOf(s, '.'));
  }

  public static String dropSuffixIC(String suffix, String s) {
    return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

  public static String addPrefixOptIfNempty(String prefix, String s) {
    return addPrefixIfNotEmpty2(prefix, s);
  }

  public static CloseableIterableIterator<String> linesFromFile(File f) {
    try {
      if (!f.exists())
        return emptyCloseableIterableIterator();
      if (ewic(f.getName(), ".gz"))
        return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
      return linesFromReader(utf8bufferedReader(f));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static CloseableIterableIterator<String> linesFromFile(String path) {
    return linesFromFile(newFile(path));
  }

  public static String addPrefixIfNotEmpty2(String prefix, String s) {
    return empty(s) ? "" : addPrefix(prefix, s);
  }

  public static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {

    public Object next() {
      throw fail();
    }

    public boolean hasNext() {
      return false;
    }
  };

  public static <A> CloseableIterableIterator<A> emptyCloseableIterableIterator() {
    return emptyCloseableIterableIterator_instance;
  }

  public static CloseableIterableIterator<String> linesFromReader(Reader r) {
    final BufferedReader br = bufferedReader(r);
    return iteratorFromFunction_f0_autoCloseable(new F0<String>() {

      public String get() {
        try {
          return readLineFromReaderWithClose(br);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret readLineFromReaderWithClose(br);";
      }
    }, _wrapIOCloseable(r));
  }

  public static String addPrefix(String prefix, String s) {
    return s.startsWith(prefix) ? s : prefix + s;
  }

  public static <A> CloseableIterableIterator<A> iteratorFromFunction_f0_autoCloseable(final F0<A> f, final AutoCloseable closeable) {
    class IFF2 extends CloseableIterableIterator<A> {

      public A a;

      public boolean done = false;

      public boolean hasNext() {
        getNext();
        return !done;
      }

      public A next() {
        getNext();
        if (done)
          throw fail();
        A _a = a;
        a = null;
        return _a;
      }

      public void getNext() {
        if (done || a != null)
          return;
        a = f.get();
        done = a == null;
      }

      public void close() throws Exception {
        if (closeable != null)
          closeable.close();
      }
    }
    ;
    return new IFF2();
  }

  public static String readLineFromReaderWithClose(BufferedReader r) {
    try {
      String s = r.readLine();
      if (s == null)
        r.close();
      return s;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
    return c == null ? null : new AutoCloseable() {

      public String toString() {
        return "c.close();\r\n    _registerIO(c, null, false);";
      }

      public void close() throws Exception {
        c.close();
        _registerIO(c, null, false);
      }
    };
  }

  public static final class _MethodCache {

    public final Class c;

    public final HashMap<String, List<Method>> cache = new HashMap();

    public _MethodCache(Class c) {
      this.c = c;
      _init();
    }

    public void _init() {
      Class _c = c;
      while (_c != null) {
        for (Method m : _c.getDeclaredMethods()) if (!reflection_isForbiddenMethod(m))
          multiMapPut(cache, m.getName(), makeAccessible(m));
        _c = _c.getSuperclass();
      }
      for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
        multiMapPut(cache, m.getName(), makeAccessible(m));
    }

    public Method findMethod(String method, Object[] args) {
      try {
        List<Method> m = cache.get(method);
        if (m == null)
          return null;
        int n = m.size();
        for (int i = 0; i < n; i++) {
          Method me = m.get(i);
          if (call_checkArgs(me, args, false))
            return me;
        }
        return null;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public Method findStaticMethod(String method, Object[] args) {
      try {
        List<Method> m = cache.get(method);
        if (m == null)
          return null;
        int n = m.size();
        for (int i = 0; i < n; i++) {
          Method me = m.get(i);
          if (isStaticMethod(me) && call_checkArgs(me, args, false))
            return me;
        }
        return null;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }
  }

  public abstract static class VF2<A, B> {

    public abstract void get(A a, B b);
  }

  public static class JSection extends SingleComponentPanel {

    public JSection(Component c) {
      super(c);
    }

    public String getTitle() {
      Border border = getBorder();
      if (border instanceof TitledBorder)
        return ((TitledBorder) border).getTitle();
      return null;
    }
  }

  public static class Var<A> implements IVar<A> {

    public Var() {
    }

    public Var(A v) {
      this.v = v;
    }

    public A v;

    public synchronized void set(A a) {
      if (v != a) {
        v = a;
        notifyAll();
      }
    }

    public synchronized A get() {
      return v;
    }

    public synchronized boolean has() {
      return v != null;
    }

    public synchronized void clear() {
      v = null;
    }

    public String toString() {
      return str(get());
    }
  }

  public static class BoxBlurFilter extends AbstractBufferedImageOp {

    public int hRadius;

    public int vRadius;

    public int iterations = 1;

    public BoxBlurFilter() {
    }

    public BoxBlurFilter(int radius) {
      hRadius = vRadius = radius;
    }

    public BoxBlurFilter(int hRadius, int vRadius) {
      this.vRadius = vRadius;
      this.hRadius = hRadius;
    }

    public BufferedImage filter(BufferedImage src, BufferedImage dst) {
      int width = src.getWidth();
      int height = src.getHeight();
      if (dst == null)
        dst = createCompatibleDestImage(src, null);
      int[] inPixels = new int[width * height];
      int[] outPixels = new int[width * height];
      getRGB(src, 0, 0, width, height, inPixels);
      for (int i = 0; i < iterations; i++) {
        blur(inPixels, outPixels, width, height, hRadius);
        blur(outPixels, inPixels, height, width, vRadius);
      }
      setRGB(dst, 0, 0, width, height, inPixels);
      return dst;
    }

    public static void blur(int[] in, int[] out, int width, int height, int radius) {
      int widthMinus1 = width - 1;
      int tableSize = 2 * radius + 1;
      int[] divide = new int[256 * tableSize];
      for (int i = 0; i < 256 * tableSize; i++) divide[i] = i / tableSize;
      int inIndex = 0;
      for (int y = 0; y < height; y++) {
        int outIndex = y;
        int ta = 0, tr = 0, tg = 0, tb = 0;
        for (int i = -radius; i <= radius; i++) {
          int rgb = in[inIndex + clamp(i, 0, width - 1)];
          ta += (rgb >> 24) & 0xff;
          tr += (rgb >> 16) & 0xff;
          tg += (rgb >> 8) & 0xff;
          tb += rgb & 0xff;
        }
        for (int x = 0; x < width; x++) {
          out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16) | (divide[tg] << 8) | divide[tb];
          int i1 = x + radius + 1;
          if (i1 > widthMinus1)
            i1 = widthMinus1;
          int i2 = x - radius;
          if (i2 < 0)
            i2 = 0;
          int rgb1 = in[inIndex + i1];
          int rgb2 = in[inIndex + i2];
          ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff);
          tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16;
          tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8;
          tb += (rgb1 & 0xff) - (rgb2 & 0xff);
          outIndex += height;
        }
        inIndex += width;
      }
    }
  }

  public static final class IntRange {

    public int start, end;

    public IntRange() {
    }

    public IntRange(int start, int end) {
      this.end = end;
      this.start = start;
    }

    public boolean equals(Object o) {
      return stdEq2(this, o);
    }

    public int hashCode() {
      return stdHash2(this);
    }

    public int length() {
      return end - start;
    }

    public static String _fieldOrder = "start end";

    public String toString() {
      return "[" + start + ";" + end + "]";
    }
  }

  public static class LeftAlignedLine extends JPanel {

    public LeftAlignedLine(Component... components) {
      setLayout(LetterLayout.leftAlignedRow());
      for (Component component : components) add(component);
    }

    public void add(String text) {
      add(new JLabel(text));
    }
  }

  public abstract static class LiveValue<A> {

    public abstract Class<A> getType();

    public abstract A get();

    public abstract void onChange(Runnable l);

    public abstract void removeOnChangeListener(Runnable l);

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }
  }

  public static class AutoSegmenter {

    public int g = 3;

    public List<Rect> clips;

    public boolean[] grid;

    public int gw, gh;

    public boolean diag = false;

    public BWImage img;

    public boolean contrastMethod2 = true, blackBG;

    public float contrastThreshold = 0.5f, brightnessThreshold = 0.5f;

    public int overlap = 1;

    public AutoSegmenter() {
    }

    public AutoSegmenter(int g) {
      this.g = g;
    }

    public List<Rect> go(RGBImage img) {
      return go(new BWImage(img));
    }

    public List<Rect> go(BWImage img) {
      this.img = img;
      int w = img.getWidth(), h = img.getHeight();
      gw = w / g;
      gh = h / g;
      step1();
      List<String> result = new ArrayList();
      clips = new ArrayList();
      for (int y = 0; y < gh; y++) for (int x = 0; x < gw; x++) if (grid[y * gw + x]) {
        Rect r = fill(x, y);
        r = scaleRect(r, g);
        r = blackBG ? autoCropOfBWImage_blackBG(img, r, brightnessThreshold) : autoCropOfBWImage(img, r, brightnessThreshold);
        clips.add(r);
      }
      return clips;
    }

    public void step1() {
      int w = img.getWidth(), h = img.getHeight();
      grid = new boolean[gw * gh];
      for (int gy = 0; gy <= h - g; gy += g) next: for (int gx = 0; gx <= w - g; gx += g) {
        float min = 1, max = 0;
        int y2 = min(h, gy + g + overlap);
        int x2 = min(w, gx + g + overlap);
        for (int y = gy; y < y2; y++) for (int x = gx; x < x2; x++) {
          float b = img.getPixel(x, y);
          min = Math.min(min, b);
          max = Math.max(max, b);
          if (contrastMethod2 ? max - min >= contrastThreshold : min < brightnessThreshold && max > brightnessThreshold) {
            grid[(gy / g) * gw + (gx / g)] = true;
            continue next;
          }
        }
      }
    }

    public Rect fill(int x, int y) {
      Rect r = null;
      List<Pt> stack = new ArrayList();
      stack.add(new Pt(x, y));
      while (nempty(stack)) {
        Pt p = popLast(stack);
        x = p.x;
        y = p.y;
        if (!(x < 0 || y < 0 || x >= gw || y >= gh)) {
          int idx = y * gw + x;
          if (grid[idx]) {
            grid[idx] = false;
            Rect me = new Rect(x, y, 1, 1);
            if (r == null)
              r = me;
            else
              r = rectUnion(r, me);
            stack.add(new Pt(x - 1, y));
            stack.add(new Pt(x + 1, y));
            stack.add(new Pt(x, y - 1));
            stack.add(new Pt(x, y + 1));
          }
        }
      }
      return r;
    }

    public float visualizeGrid_darkening = 0.0f;

    public BWImage visualizeGrid() {
      step1();
      BWImage im = new BWImage(img);
      for (int y = 0; y < gh; y++) for (int x = 0; x < gw; x++) {
        if (grid[y * gw + x])
          continue;
        darkenBWImagePart(im, new Rect(x * g, y * g, g, g), visualizeGrid_darkening);
      }
      return im;
    }
  }

  public abstract static class IterableIterator<A> implements Iterator<A>, Iterable<A> {

    public Iterator<A> iterator() {
      return this;
    }

    public void remove() {
      unsupportedOperation();
    }
  }

  public abstract static class F2<A, B, C> {

    public abstract C get(A a, B b);
  }

  public static class RangeSlider extends JSlider {

    public RangeSlider() {
      initSlider();
    }

    public RangeSlider(int min, int max) {
      super(min, max);
      initSlider();
    }

    public final void initSlider() {
      setOrientation(HORIZONTAL);
    }

    @Override
    public void updateUI() {
      setUI(new RangeSliderUI(this));
      updateLabelUIs();
    }

    @Override
    public int getValue() {
      return super.getValue();
    }

    @Override
    public void setValue(int value) {
      int oldValue = getValue();
      if (oldValue == value) {
        return;
      }
      int oldExtent = getExtent();
      int newValue = Math.min(Math.max(getMinimum(), value), oldValue + oldExtent);
      int newExtent = oldExtent + oldValue - newValue;
      getModel().setRangeProperties(newValue, newExtent, getMinimum(), getMaximum(), getValueIsAdjusting());
    }

    public int getUpperValue() {
      return getValue() + getExtent();
    }

    public void setUpperValue(int value) {
      int lowerValue = getValue();
      int newExtent = Math.min(Math.max(0, value - lowerValue), getMaximum() - lowerValue);
      setExtent(newExtent);
    }

    public void setValues(int value, int upper) {
      setValue(value);
      setUpperValue(upper);
    }
  }

  public static class RangeSliderUI extends BasicSliderUI {

    public Color rangeColor = Color.GREEN;

    public Rectangle upperThumbRect;

    public boolean upperThumbSelected = false;

    public transient boolean lowerDragging = false;

    public transient boolean upperDragging = false;

    public RangeSliderUI(RangeSlider b) {
      super(b);
    }

    @Override
    public void installUI(JComponent c) {
      upperThumbRect = new Rectangle();
      super.installUI(c);
    }

    @Override
    public TrackListener createTrackListener(JSlider slider) {
      return new RangeTrackListener();
    }

    @Override
    public ChangeListener createChangeListener(JSlider slider) {
      return new ChangeHandler();
    }

    @Override
    public void calculateThumbSize() {
      super.calculateThumbSize();
      upperThumbRect.setSize(thumbRect.width, thumbRect.height);
    }

    @Override
    public void calculateThumbLocation() {
      super.calculateThumbLocation();
      if (slider.getSnapToTicks()) {
        int upperValue = slider.getValue() + slider.getExtent();
        int snappedValue = upperValue;
        int majorTickSpacing = slider.getMajorTickSpacing();
        int minorTickSpacing = slider.getMinorTickSpacing();
        int tickSpacing = 0;
        if (minorTickSpacing > 0) {
          tickSpacing = minorTickSpacing;
        } else if (majorTickSpacing > 0) {
          tickSpacing = majorTickSpacing;
        }
        if (tickSpacing != 0) {
          if ((upperValue - slider.getMinimum()) % tickSpacing != 0) {
            float temp = (float) (upperValue - slider.getMinimum()) / (float) tickSpacing;
            int whichTick = Math.round(temp);
            snappedValue = slider.getMinimum() + (whichTick * tickSpacing);
          }
          if (snappedValue != upperValue) {
            slider.setExtent(snappedValue - slider.getValue());
          }
        }
      }
      if (slider.getOrientation() == JSlider.HORIZONTAL) {
        int upperPosition = xPositionForValue(slider.getValue() + slider.getExtent());
        upperThumbRect.x = upperPosition - (upperThumbRect.width / 2);
        upperThumbRect.y = trackRect.y;
      } else {
        int upperPosition = yPositionForValue(slider.getValue() + slider.getExtent());
        upperThumbRect.x = trackRect.x;
        upperThumbRect.y = upperPosition - (upperThumbRect.height / 2);
      }
    }

    @Override
    public Dimension getThumbSize() {
      return new Dimension(12, 12);
    }

    @Override
    public void paint(Graphics g, JComponent c) {
      super.paint(g, c);
      Rectangle clipRect = g.getClipBounds();
      if (upperThumbSelected) {
        if (clipRect.intersects(thumbRect)) {
          paintLowerThumb(g);
        }
        if (clipRect.intersects(upperThumbRect)) {
          paintUpperThumb(g);
        }
      } else {
        if (clipRect.intersects(upperThumbRect)) {
          paintUpperThumb(g);
        }
        if (clipRect.intersects(thumbRect)) {
          paintLowerThumb(g);
        }
      }
    }

    @Override
    public void paintTrack(Graphics g) {
      super.paintTrack(g);
      Rectangle trackBounds = trackRect;
      if (slider.getOrientation() == JSlider.HORIZONTAL) {
        int lowerX = thumbRect.x + (thumbRect.width / 2);
        int upperX = upperThumbRect.x + (upperThumbRect.width / 2);
        int cy = (trackBounds.height / 2) - 2;
        Color oldColor = g.getColor();
        g.translate(trackBounds.x, trackBounds.y + cy);
        g.setColor(rangeColor);
        for (int y = 0; y <= 3; y++) {
          g.drawLine(lowerX - trackBounds.x, y, upperX - trackBounds.x, y);
        }
        g.translate(-trackBounds.x, -(trackBounds.y + cy));
        g.setColor(oldColor);
      } else {
        int lowerY = thumbRect.x + (thumbRect.width / 2);
        int upperY = upperThumbRect.x + (upperThumbRect.width / 2);
        int cx = (trackBounds.width / 2) - 2;
        Color oldColor = g.getColor();
        g.translate(trackBounds.x + cx, trackBounds.y);
        g.setColor(rangeColor);
        for (int x = 0; x <= 3; x++) {
          g.drawLine(x, lowerY - trackBounds.y, x, upperY - trackBounds.y);
        }
        g.translate(-(trackBounds.x + cx), -trackBounds.y);
        g.setColor(oldColor);
      }
    }

    @Override
    public void paintThumb(Graphics g) {
    }

    public final void paintLowerThumb(Graphics g) {
      Rectangle knobBounds = thumbRect;
      int w = knobBounds.width;
      int h = knobBounds.height;
      Graphics2D g2d = (Graphics2D) g.create();
      Shape thumbShape = createThumbShape(w - 1, h - 1);
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2d.translate(knobBounds.x, knobBounds.y);
      g2d.setColor(Color.CYAN);
      g2d.fill(thumbShape);
      g2d.setColor(Color.BLUE);
      g2d.draw(thumbShape);
      g2d.dispose();
    }

    public final void paintUpperThumb(Graphics g) {
      Rectangle knobBounds = upperThumbRect;
      int w = knobBounds.width;
      int h = knobBounds.height;
      Graphics2D g2d = (Graphics2D) g.create();
      Shape thumbShape = createThumbShape(w - 1, h - 1);
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2d.translate(knobBounds.x, knobBounds.y);
      g2d.setColor(Color.PINK);
      g2d.fill(thumbShape);
      g2d.setColor(Color.RED);
      g2d.draw(thumbShape);
      g2d.dispose();
    }

    public final Shape createThumbShape(int width, int height) {
      Ellipse2D shape = new Ellipse2D.Double(0, 0, width, height);
      return shape;
    }

    public final void setUpperThumbLocation(int x, int y) {
      Rectangle upperUnionRect = new Rectangle();
      upperUnionRect.setBounds(upperThumbRect);
      upperThumbRect.setLocation(x, y);
      SwingUtilities.computeUnion(upperThumbRect.x, upperThumbRect.y, upperThumbRect.width, upperThumbRect.height, upperUnionRect);
      slider.repaint(upperUnionRect.x, upperUnionRect.y, upperUnionRect.width, upperUnionRect.height);
    }

    public void scrollByBlock(int direction) {
      synchronized (slider) {
        int blockIncrement = (slider.getMaximum() - slider.getMinimum()) / 10;
        if (blockIncrement <= 0 && slider.getMaximum() > slider.getMinimum()) {
          blockIncrement = 1;
        }
        int delta = blockIncrement * ((direction > 0) ? POSITIVE_SCROLL : NEGATIVE_SCROLL);
        if (upperThumbSelected) {
          int oldValue = ((RangeSlider) slider).getUpperValue();
          ((RangeSlider) slider).setUpperValue(oldValue + delta);
        } else {
          int oldValue = slider.getValue();
          slider.setValue(oldValue + delta);
        }
      }
    }

    public void scrollByUnit(int direction) {
      synchronized (slider) {
        int delta = 1 * ((direction > 0) ? POSITIVE_SCROLL : NEGATIVE_SCROLL);
        if (upperThumbSelected) {
          int oldValue = ((RangeSlider) slider).getUpperValue();
          ((RangeSlider) slider).setUpperValue(oldValue + delta);
        } else {
          int oldValue = slider.getValue();
          slider.setValue(oldValue + delta);
        }
      }
    }

    public class ChangeHandler implements ChangeListener {

      public void stateChanged(ChangeEvent arg0) {
        if (!lowerDragging && !upperDragging) {
          calculateThumbLocation();
          slider.repaint();
        }
      }
    }

    public class RangeTrackListener extends TrackListener {

      @Override
      public void mousePressed(MouseEvent e) {
        if (!slider.isEnabled()) {
          return;
        }
        currentMouseX = e.getX();
        currentMouseY = e.getY();
        if (slider.isRequestFocusEnabled()) {
          slider.requestFocus();
        }
        boolean lowerPressed = false;
        boolean upperPressed = false;
        if (upperThumbSelected || slider.getMinimum() == slider.getValue()) {
          if (upperThumbRect.contains(currentMouseX, currentMouseY)) {
            upperPressed = true;
          } else if (thumbRect.contains(currentMouseX, currentMouseY)) {
            lowerPressed = true;
          }
        } else {
          if (thumbRect.contains(currentMouseX, currentMouseY)) {
            lowerPressed = true;
          } else if (upperThumbRect.contains(currentMouseX, currentMouseY)) {
            upperPressed = true;
          }
        }
        if (lowerPressed) {
          switch(slider.getOrientation()) {
            case JSlider.VERTICAL:
              offset = currentMouseY - thumbRect.y;
              break;
            case JSlider.HORIZONTAL:
              offset = currentMouseX - thumbRect.x;
              break;
          }
          upperThumbSelected = false;
          lowerDragging = true;
          return;
        }
        lowerDragging = false;
        if (upperPressed) {
          switch(slider.getOrientation()) {
            case JSlider.VERTICAL:
              offset = currentMouseY - upperThumbRect.y;
              break;
            case JSlider.HORIZONTAL:
              offset = currentMouseX - upperThumbRect.x;
              break;
          }
          upperThumbSelected = true;
          upperDragging = true;
          return;
        }
        upperDragging = false;
      }

      @Override
      public void mouseReleased(MouseEvent e) {
        lowerDragging = false;
        upperDragging = false;
        slider.setValueIsAdjusting(false);
        super.mouseReleased(e);
      }

      @Override
      public void mouseDragged(MouseEvent e) {
        if (!slider.isEnabled()) {
          return;
        }
        currentMouseX = e.getX();
        currentMouseY = e.getY();
        if (lowerDragging) {
          slider.setValueIsAdjusting(true);
          moveLowerThumb();
        } else if (upperDragging) {
          slider.setValueIsAdjusting(true);
          moveUpperThumb();
        }
      }

      @Override
      public boolean shouldScroll(int direction) {
        return false;
      }

      public final void moveLowerThumb() {
        int thumbMiddle = 0;
        switch(slider.getOrientation()) {
          case JSlider.VERTICAL:
            int halfThumbHeight = thumbRect.height / 2;
            int thumbTop = currentMouseY - offset;
            int trackTop = trackRect.y;
            int trackBottom = trackRect.y + (trackRect.height - 1);
            int vMax = yPositionForValue(slider.getValue() + slider.getExtent());
            if (drawInverted()) {
              trackBottom = vMax;
            } else {
              trackTop = vMax;
            }
            thumbTop = Math.max(thumbTop, trackTop - halfThumbHeight);
            thumbTop = Math.min(thumbTop, trackBottom - halfThumbHeight);
            setThumbLocation(thumbRect.x, thumbTop);
            thumbMiddle = thumbTop + halfThumbHeight;
            slider.setValue(valueForYPosition(thumbMiddle));
            break;
          case JSlider.HORIZONTAL:
            int halfThumbWidth = thumbRect.width / 2;
            int thumbLeft = currentMouseX - offset;
            int trackLeft = trackRect.x;
            int trackRight = trackRect.x + (trackRect.width - 1);
            int hMax = xPositionForValue(slider.getValue() + slider.getExtent());
            if (drawInverted()) {
              trackLeft = hMax;
            } else {
              trackRight = hMax;
            }
            thumbLeft = Math.max(thumbLeft, trackLeft - halfThumbWidth);
            thumbLeft = Math.min(thumbLeft, trackRight - halfThumbWidth);
            setThumbLocation(thumbLeft, thumbRect.y);
            thumbMiddle = thumbLeft + halfThumbWidth;
            slider.setValue(valueForXPosition(thumbMiddle));
            break;
          default:
            return;
        }
      }

      public final void moveUpperThumb() {
        int thumbMiddle = 0;
        switch(slider.getOrientation()) {
          case JSlider.VERTICAL:
            int halfThumbHeight = thumbRect.height / 2;
            int thumbTop = currentMouseY - offset;
            int trackTop = trackRect.y;
            int trackBottom = trackRect.y + (trackRect.height - 1);
            int vMin = yPositionForValue(slider.getValue());
            if (drawInverted()) {
              trackTop = vMin;
            } else {
              trackBottom = vMin;
            }
            thumbTop = Math.max(thumbTop, trackTop - halfThumbHeight);
            thumbTop = Math.min(thumbTop, trackBottom - halfThumbHeight);
            setUpperThumbLocation(thumbRect.x, thumbTop);
            thumbMiddle = thumbTop + halfThumbHeight;
            slider.setExtent(valueForYPosition(thumbMiddle) - slider.getValue());
            break;
          case JSlider.HORIZONTAL:
            int halfThumbWidth = thumbRect.width / 2;
            int thumbLeft = currentMouseX - offset;
            int trackLeft = trackRect.x;
            int trackRight = trackRect.x + (trackRect.width - 1);
            int hMin = xPositionForValue(slider.getValue());
            if (drawInverted()) {
              trackRight = hMin;
            } else {
              trackLeft = hMin;
            }
            thumbLeft = Math.max(thumbLeft, trackLeft - halfThumbWidth);
            thumbLeft = Math.min(thumbLeft, trackRight - halfThumbWidth);
            setUpperThumbLocation(thumbLeft, thumbRect.y);
            thumbMiddle = thumbLeft + halfThumbWidth;
            slider.setExtent(valueForXPosition(thumbMiddle) - slider.getValue());
            break;
          default:
            return;
        }
      }
    }
  }

  public static final class DoubleRange {

    public double start, end;

    public DoubleRange() {
    }

    public DoubleRange(double start, double end) {
      this.end = end;
      this.start = start;
    }

    public boolean equals(Object o) {
      return stdEq2(this, o);
    }

    public int hashCode() {
      return stdHash2(this);
    }

    public double length() {
      return end - start;
    }

    public static String _fieldOrder = "start end";

    public String toString() {
      return "[" + start + ";" + end + "]";
    }
  }

  public static class MRUCache<A, B> extends LinkedHashMap<A, B> {

    public int maxSize = 10;

    public MRUCache() {
    }

    public MRUCache(int maxSize) {
      this.maxSize = maxSize;
    }

    public boolean removeEldestEntry(Map.Entry eldest) {
      return size() > maxSize;
    }
  }

  public static interface IF0<A> {

    public A get();
  }

  public static class SimpleLiveValue<A> extends LiveValue<A> {

    public Class<A> type;

    public volatile A value;

    public transient List onChange = synchroList();

    public SimpleLiveValue(Class<A> type) {
      this.type = type;
    }

    public SimpleLiveValue(Class<A> type, A value) {
      this.value = value;
      this.type = type;
    }

    public Class<A> getType() {
      return type;
    }

    public A get() {
      return value;
    }

    public void onChange(Runnable l) {
      onChange.add(l);
    }

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }

    public void removeOnChangeListener(Runnable l) {
      onChange.remove(l);
    }

    public void fireChanged() {
      pcallFAll(onChange);
    }

    public void set(A a) {
      if (neq(value, a)) {
        value = a;
        fireChanged();
      }
    }
  }

  public abstract static class CloseableIterableIterator<A> extends IterableIterator<A> implements AutoCloseable {

    public void close() throws Exception {
    }
  }

  public static interface IResourceLoader {

    public String loadSnippet(String snippetID);

    public String getTranspiled(String snippetID);

    public int getSnippetType(String snippetID);

    public String getSnippetTitle(String snippetID);

    public File loadLibrary(String snippetID);

    public File pathToJavaXJar();

    public File getSnippetJar(String snippetID, String transpiledSrc);
  }

  public static class ReliableSingleThread implements Runnable {

    public Object runnable;

    public boolean trigger = false;

    public Thread thread;

    public String name = "Single Thread";

    public F0<AutoCloseable> enter;

    public ReliableSingleThread(Object runnable) {
      this.runnable = runnable;
    }

    public void trigger() {
      go();
    }

    public synchronized void go() {
      trigger = true;
      if (!running()) {
        AutoCloseable __2339 = callF(enter);
        try {
          thread = startThread(name, new Runnable() {

            public void run() {
              try {
                AutoCloseable __2340 = callF(enter);
                try {
                  _run();
                } finally {
                  _close(__2340);
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "AutoCloseable __2340 = callF(enter); try {\r\n        _run();\r\n      } finally ...";
            }
          });
        } finally {
          _close(__2339);
        }
      }
    }

    public void run() {
      go();
    }

    public void get() {
      go();
    }

    public synchronized boolean running() {
      return thread != null;
    }

    public void triggerAndWait() {
      trigger();
      while (running()) sleep(1);
    }

    public void _run() {
      while (licensed()) {
        synchronized (this) {
          if (!trigger) {
            thread = null;
            break;
          }
          trigger = false;
        }
        pcallF(runnable);
      }
    }

    public synchronized void cancel() {
      cancelAndInterruptThread(thread);
      thread = null;
    }
  }

  public static interface IVar<A> {

    public void set(A a);

    public A get();

    public boolean has();

    public void clear();
  }

  public static class T3<A, B, C> {

    public A a;

    public B b;

    public C c;

    public T3() {
    }

    public T3(A a, B b, C c) {
      this.c = c;
      this.b = b;
      this.a = a;
    }

    public T3(T3<A, B, C> t) {
      a = t.a;
      b = t.b;
      c = t.c;
    }

    public int hashCode() {
      return _hashCode(a) + 2 * _hashCode(b) - 4 * _hashCode(c);
    }

    public boolean equals(Object o) {
      if (o == this)
        return true;
      if (!(o instanceof T3))
        return false;
      T3 t = (T3) o;
      return eq(a, t.a) && eq(b, t.b) && eq(c, t.c);
    }

    public String toString() {
      return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")";
    }
  }

  public static class Pair<A, B> implements Comparable<Pair<A, B>> {

    public A a;

    public B b;

    public Pair() {
    }

    public Pair(A a, B b) {
      this.b = b;
      this.a = a;
    }

    public int hashCode() {
      return hashCodeFor(a) + 2 * hashCodeFor(b);
    }

    public boolean equals(Object o) {
      if (o == this)
        return true;
      if (!(o instanceof Pair))
        return false;
      Pair t = (Pair) o;
      return eq(a, t.a) && eq(b, t.b);
    }

    public String toString() {
      return "<" + a + ", " + b + ">";
    }

    public int compareTo(Pair<A, B> p) {
      if (p == null)
        return 1;
      int i = ((Comparable<A>) a).compareTo(p.a);
      if (i != 0)
        return i;
      return ((Comparable<B>) b).compareTo(p.b);
    }
  }

  public abstract static class AbstractBufferedImageOp implements BufferedImageOp, Cloneable {

    public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel dstCM) {
      if (dstCM == null)
        dstCM = src.getColorModel();
      return new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster(src.getWidth(), src.getHeight()), dstCM.isAlphaPremultiplied(), null);
    }

    public Rectangle2D getBounds2D(BufferedImage src) {
      return new Rectangle(0, 0, src.getWidth(), src.getHeight());
    }

    public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) {
      if (dstPt == null)
        dstPt = new Point2D.Double();
      dstPt.setLocation(srcPt.getX(), srcPt.getY());
      return dstPt;
    }

    public RenderingHints getRenderingHints() {
      return null;
    }

    public int[] getRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) {
      int type = image.getType();
      if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB)
        return (int[]) image.getRaster().getDataElements(x, y, width, height, pixels);
      return image.getRGB(x, y, width, height, pixels, 0, width);
    }

    public void setRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) {
      int type = image.getType();
      if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB)
        image.getRaster().setDataElements(x, y, width, height, pixels);
      else
        image.setRGB(x, y, width, height, pixels, 0, width);
    }

    public Object clone() {
      try {
        return super.clone();
      } catch (CloneNotSupportedException e) {
        return null;
      }
    }
  }

  public static class LetterLayout implements LayoutManager {

    public String[] lines;

    public Map<String, Component> map = new TreeMap<String, Component>();

    public RC[] rows;

    public RC[] cols;

    public Cell[][] cells;

    public int spacingX = 10, spacingY = 10;

    public int insetTop, insetBottom, insetLeft, insetRight;

    public int template;

    public boolean formWideLeftSide, formWideRightSide;

    public static final int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5;

    public boolean debug = false;

    public void setLeftBorder(int border) {
      insetLeft = border;
    }

    public void setRightBorder(int border) {
      insetRight = border;
    }

    public static JComponent withBorder(JComponent component, int border) {
      JPanel panel = new JPanel(new LetterLayout("C").setBorder(border));
      panel.add("C", component);
      return panel;
    }

    public static JPanel panel(String... lines) {
      return new JPanel(new LetterLayout(lines));
    }

    public static JPanel stalactitePanel() {
      return new JPanel(stalactite());
    }

    public static class DummyComponent extends JComponent {
    }

    public static class Cell {

      public boolean aux = false;

      public int minWidth, minHeight;

      public Component component;

      public int colspan, rowspan;

      public double weightX, weightY;
    }

    public static class RC {

      public int min;

      public double weightSum;

      public int start;

      public int minEnd;
    }

    public LetterLayout(int template) {
      this.template = template;
    }

    public LetterLayout(String... lines) {
      this.lines = lines;
    }

    public void removeLayoutComponent(Component component) {
      map.values().remove(component);
    }

    public void layoutContainer(Container container) {
      prepareLayout(container);
      if (debug)
        System.out.println("Container size: " + container.getSize());
      Insets insets = getInsets(container);
      for (int r = 0; r < rows.length; r++) {
        for (int i = 0; i < cols.length; ) {
          Cell cell = cells[i][r];
          if (cell.aux)
            ++i;
          else {
            if (cell.component != null) {
              int x1 = cols[i].start;
              int y1 = rows[r].start;
              int x2 = i + cell.colspan < cols.length ? cols[i + cell.colspan].start - spacingX : container.getWidth() - insets.right;
              int y2 = r + cell.rowspan < rows.length ? rows[r + cell.rowspan].start - spacingY : container.getHeight() - insets.bottom;
              if (debug)
                System.out.println("Layouting (" + i + ", " + r + ", " + cell.component.getClass().getName() + "): " + x1 + " " + y1 + " " + x2 + " " + y2);
              cell.component.setBounds(x1, y1, x2 - x1, y2 - y1);
            }
            i += cells[i][r].colspan;
          }
        }
      }
    }

    public final void prepareLayout(Container container) {
      applyTemplate(container);
      int numRows = lines.length, numCols = lines[0].length();
      for (int i = 1; i < numRows; i++) if (lines[i].length() != numCols)
        throw new IllegalArgumentException("Lines have varying length");
      cells = new Cell[numCols][numRows];
      rows = new RC[numRows];
      cols = new RC[numCols];
      for (int r = 0; r < numRows; r++) rows[r] = new RC();
      for (int i = 0; i < numCols; i++) cols[i] = new RC();
      for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r] = new Cell();
      for (int r = 0; r < numRows; r++) {
        String line = lines[r];
        for (int i = 0; i < numCols; ) {
          Cell cell = cells[i][r];
          if (cell.aux) {
            ++i;
            continue;
          }
          char ch = line.charAt(i);
          int iNext = i;
          do ++iNext; while (iNext < numCols && ch == line.charAt(iNext));
          int rNext = r;
          do ++rNext; while (rNext < numRows && ch == lines[rNext].charAt(i));
          cell.weightX = numCols == 1 || iNext > i + 1 ? 1.0 : 0.0;
          cell.weightY = numRows == 1 || rNext > r + 1 ? 1.0 : 0.0;
          Component c = map.get(String.valueOf(ch));
          cell.component = c;
          if (c != null) {
            cell.minWidth = c.getMinimumSize().width + spacingX;
            cell.minHeight = getMinimumHeight(c) + spacingY;
          }
          cell.colspan = iNext - i;
          cell.rowspan = rNext - r;
          if (cell.colspan == 1)
            cols[i].min = Math.max(cols[i].min, cell.minWidth);
          if (cell.rowspan == 1)
            rows[r].min = Math.max(rows[r].min, cell.minHeight);
          for (int r2 = r; r2 < rNext; r2++) for (int i2 = i; i2 < iNext; i2++) if (r2 != r || i2 != i)
            cells[i2][r2].aux = true;
          i = iNext;
        }
      }
      while (true) {
        for (int i = 0; i < numCols; i++) {
          int minStart = i == 0 ? 0 : cols[i - 1].minEnd;
          double weightStart = i == 0 ? 0.0 : cols[i - 1].weightSum;
          for (int r = 0; r < numRows; r++) {
            Cell cell = cells[i][r];
            if (!cell.aux) {
              RC rc = cols[i + cell.colspan - 1];
              rc.minEnd = Math.max(rc.minEnd, minStart + cell.minWidth);
              rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightX);
            }
          }
        }
        for (int r = 0; r < numRows; r++) {
          int minStart = r == 0 ? 0 : rows[r - 1].minEnd;
          double weightStart = r == 0 ? 0.0 : rows[r - 1].weightSum;
          for (int i = 0; i < numCols; i++) {
            Cell cell = cells[i][r];
            if (!cell.aux) {
              RC rc = rows[r + cell.rowspan - 1];
              rc.minEnd = Math.max(rc.minEnd, minStart + cell.minHeight);
              rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightY);
            }
          }
        }
        if (allWeightsZero(cols)) {
          for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightX = 1.0;
          continue;
        }
        if (allWeightsZero(rows)) {
          for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightY = 1.0;
          continue;
        }
        break;
      }
      Insets insets = getInsets(container);
      determineStarts(cols, insets.left, container.getWidth() - insets.left - insets.right + spacingX, spacingX);
      determineStarts(rows, insets.top, container.getHeight() - insets.top - insets.bottom + spacingY, spacingY);
    }

    public final boolean allWeightsZero(RC[] rcs) {
      for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0)
        return false;
      return true;
    }

    public static int getMinimumHeight(Component c) {
      return c.getMinimumSize().height;
    }

    public final void applyTemplate(Container container) {
      if (template == STALACTITE) {
        Component[] components = container.getComponents();
        lines = new String[components.length + 2];
        map.clear();
        for (int i = 0; i < components.length; i++) {
          String s = String.valueOf(makeIndexChar(i));
          map.put(s, components[i]);
          lines[i] = s;
        }
        lines[components.length] = lines[components.length + 1] = " ";
      } else if (template == FORM) {
        Component[] components = container.getComponents();
        int numRows = components.length / 2;
        lines = new String[numRows + 2];
        map.clear();
        for (int row = 0; row < numRows; row++) {
          String lower = String.valueOf(makeIndexChar(row));
          String upper = String.valueOf(makeAlternateIndexChar(row));
          Component rightComponent = components[row * 2 + 1];
          if (rightComponent instanceof DummyComponent)
            upper = lower;
          lines[row] = (formWideLeftSide ? lower + lower : lower) + (formWideRightSide ? upper + upper : upper);
          map.put(lower, components[row * 2]);
          if (!(rightComponent instanceof DummyComponent))
            map.put(upper, rightComponent);
        }
        lines[numRows] = lines[numRows + 1] = (formWideLeftSide ? "  " : " ") + (formWideRightSide ? "  " : " ");
      } else if (template == LEFT_ALIGNED_ROW) {
        lines = new String[] { makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
      } else if (template == CENTERED_ROW) {
        lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
      } else if (template == RIGHT_ALIGNED_ROW) {
        lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) };
      }
    }

    public final String makeSingleRow(Container container) {
      Component[] components = container.getComponents();
      StringBuffer buf = new StringBuffer();
      map.clear();
      for (int i = 0; i < components.length; i++) {
        String s = String.valueOf(makeAlternateIndexChar(i));
        map.put(s, components[i]);
        buf.append(s);
      }
      return buf.toString();
    }

    public static void determineStarts(RC[] rcs, int start, int totalSize, int spacing) {
      int minTotal = rcs[rcs.length - 1].minEnd;
      double weightSum = rcs[rcs.length - 1].weightSum;
      int spare = (int) ((totalSize - minTotal) / (weightSum == 0.0 ? 1.0 : weightSum));
      int x = start, minSum = 0;
      double prevWeightSum = 0.0;
      for (int i = 0; i < rcs.length; i++) {
        int width = rcs[i].minEnd - minSum + (int) ((rcs[i].weightSum - prevWeightSum) * spare) - spacing;
        rcs[i].start = x;
        x += width + spacing;
        prevWeightSum = rcs[i].weightSum;
        minSum = rcs[i].minEnd;
      }
    }

    public void addLayoutComponent(String s, Component component) {
      map.put(s, component);
    }

    public Dimension minimumLayoutSize(Container container) {
      prepareLayout(container);
      Insets insets = getInsets(container);
      Dimension result = new Dimension(insets.left + cols[cols.length - 1].minEnd + insets.right - spacingX, insets.top + rows[rows.length - 1].minEnd + insets.bottom - spacingY);
      return result;
    }

    public final Insets getInsets(Container container) {
      Insets insets = container.getInsets();
      return new Insets(insets.top + insetTop, insets.left + insetLeft, insets.bottom + insetBottom, insets.right + insetRight);
    }

    public Dimension preferredLayoutSize(Container container) {
      return minimumLayoutSize(container);
    }

    public LetterLayout setSpacing(int x, int y) {
      spacingX = x;
      spacingY = y;
      return this;
    }

    public LetterLayout setSpacing(int spacing) {
      return setSpacing(spacing, spacing);
    }

    public LetterLayout setBorder(int top, int left, int bottom, int right) {
      insetTop = top;
      insetLeft = left;
      insetBottom = bottom;
      insetRight = right;
      return this;
    }

    public LetterLayout setBorder(int inset) {
      return setBorder(inset, inset, inset, inset);
    }

    public LetterLayout setTopBorder(int inset) {
      insetTop = inset;
      return this;
    }

    public static LetterLayout stalactite() {
      return new LetterLayout(STALACTITE);
    }

    public static LetterLayout leftAlignedRow() {
      return new LetterLayout(LEFT_ALIGNED_ROW);
    }

    public static LetterLayout leftAlignedRow(int spacing) {
      return leftAlignedRow().setSpacing(spacing);
    }

    public static LetterLayout centeredRow() {
      return new LetterLayout(CENTERED_ROW);
    }

    public static LetterLayout rightAlignedRow() {
      return new LetterLayout(RIGHT_ALIGNED_ROW);
    }

    public static JPanel rightAlignedRowPanel(JComponent... components) {
      return makePanel(new LetterLayout(RIGHT_ALIGNED_ROW), components);
    }

    public static JPanel makePanel(LetterLayout letterLayout, JComponent[] components) {
      JPanel panel = new JPanel(letterLayout);
      for (JComponent component : components) {
        panel.add(component);
      }
      return panel;
    }

    public static LetterLayout form() {
      LetterLayout letterLayout = new LetterLayout(FORM);
      letterLayout.formWideLeftSide = true;
      letterLayout.formWideRightSide = true;
      return letterLayout;
    }

    public static LetterLayout formWideRightSide() {
      LetterLayout letterLayout = new LetterLayout(FORM);
      letterLayout.formWideRightSide = true;
      return letterLayout;
    }

    public static Component getDummyComponent() {
      return new DummyComponent();
    }

    public static JPanel newPanel(String... lines) {
      return new JPanel(new LetterLayout(lines));
    }

    public boolean isDebug() {
      return debug;
    }

    public void setDebug(boolean debug) {
      this.debug = debug;
    }

    public static char makeIndexChar(int idx) {
      return (char) ('a' + idx * 2);
    }

    public static char makeAlternateIndexChar(int idx) {
      return (char) ('b' + idx * 2);
    }

    public static char LEFT_CHAR = ',', RIGHT_CHAR = '.';

    public static void main(String[] args) {
      System.out.println((int) makeIndexChar(0));
      System.out.println((int) makeAlternateIndexChar(0));
      System.out.println((int) makeIndexChar(32000));
      System.out.println((int) makeAlternateIndexChar(32000));
      System.out.println((int) LEFT_CHAR);
      System.out.println((int) RIGHT_CHAR);
    }
  }

  public static boolean reflection_isForbiddenMethod(Method m) {
    return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
  }

  public static <A, B> void multiMapPut(Map<A, List<B>> map, A a, B b) {
    List<B> l = map.get(a);
    if (l == null)
      map.put(a, l = new ArrayList());
    l.add(b);
  }

  public static Field makeAccessible(Field f) {
    f.setAccessible(true);
    return f;
  }

  public static Method makeAccessible(Method m) {
    m.setAccessible(true);
    return m;
  }

  public static Set<Class> allInterfacesImplementedBy(Class c) {
    if (c == null)
      return null;
    HashSet<Class> set = new HashSet();
    allInterfacesImplementedBy_find(c, set);
    return set;
  }

  public static void allInterfacesImplementedBy_find(Class c, Set<Class> set) {
    if (c.isInterface() && !set.add(c))
      return;
    do {
      for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
    } while ((c = c.getSuperclass()) != null);
  }

  public static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length) {
      if (debug)
        print("Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++) {
      Object arg = args[i];
      if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
        if (debug)
          print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
        return false;
      }
    }
    return true;
  }

  public static Method findStaticMethod(Class c, String method, Object... args) {
    Class _c = c;
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (!m.getName().equals(method))
          continue;
        if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
          continue;
        return m;
      }
      c = c.getSuperclass();
    }
    return null;
  }

  public static boolean findStaticMethod_checkArgs(Method m, Object[] args) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length)
      return false;
    for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
      return false;
    return true;
  }

  public static Border getBorder(final JComponent c) {
    return c == null ? null : swing(new F0<Border>() {

      public Border get() {
        try {
          return c.getBorder();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getBorder();";
      }
    });
  }

  public static float clamp(float x, float a, float b) {
    return x < a ? a : x > b ? b : x;
  }

  public static double clamp(double x, double a, double b) {
    return x < a ? a : x > b ? b : x;
  }

  public static int clamp(int x, int a, int b) {
    return x < a ? a : x > b ? b : x;
  }

  public static boolean stdEq2(Object a, Object b) {
    if (a == null)
      return b == null;
    if (b == null)
      return false;
    if (a.getClass() != b.getClass())
      return false;
    for (String field : allFields(a)) if (neq(getOpt(a, field), getOpt(b, field)))
      return false;
    return true;
  }

  public static int stdHash2(Object a) {
    if (a == null)
      return 0;
    return stdHash(a, toStringArray(allFields(a)));
  }

  public static void add(BitSet bs, int i) {
    bs.set(i);
  }

  public static <A> boolean add(Collection<A> c, A a) {
    return c != null && c.add(a);
  }

  public static void add(Container c, Component x) {
    addToContainer(c, x);
  }

  public static void fill(RGBImage img, String col) {
    RGB rgb = new RGB(col);
    int w = img.getWidth(), h = img.getHeight();
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) img.setPixel(x, y, rgb);
  }

  public static Rect scaleRect(Rect r, double factorX, double factorY) {
    return new Rect(iround(r.x * factorX), iround(r.y * factorY), iround(r.w * factorX), iround(r.h * factorY));
  }

  public static Rect scaleRect(Rect r, double factor) {
    return scaleRect(r, factor, factor);
  }

  public static float autoCropOfBWImage_blackBG_threshold = 0.2f;

  public static Rect autoCropOfBWImage_blackBG(BWImage img) {
    return autoCropOfBWImage(img, new Rect(0, 0, img.getWidth(), img.getHeight()));
  }

  public static Rect autoCropOfBWImage_blackBG(BWImage img, Rect r) {
    return autoCropOfBWImage(img, r, autoCropOfBWImage_blackBG_threshold);
  }

  public static Rect autoCropOfBWImage_blackBG(BWImage img, Rect r, float threshold) {
    int x1 = r.x, y1 = r.y, x2 = r.x2(), y2 = r.y2();
    end1: while (x1 < x2) {
      for (int y = y1; y < y2; y++) if (img.getPixel(x1, y) >= threshold)
        break end1;
      x1++;
    }
    end2: while (y1 < y2) {
      for (int x = x1; x < x2; x++) if (img.getPixel(x, y1) >= threshold)
        break end2;
      y1++;
    }
    end3: while (x2 > x1) {
      for (int y = y1; y < y2; y++) if (img.getPixel(x2 - 1, y) >= threshold)
        break end3;
      x2--;
    }
    end4: while (y2 > y1) {
      for (int x = x1; x < x2; x++) if (img.getPixel(x, y2 - 1) >= threshold)
        break end4;
      y2--;
    }
    if (x2 <= x1 || y2 <= y1)
      return r;
    else
      return new Rect(x1, y1, x2 - x1, y2 - y1);
  }

  public static float autoCropOfBWImage_threshold = 0.9f;

  public static Rect autoCropOfBWImage(BWImage img) {
    return autoCropOfBWImage(img, new Rect(0, 0, img.getWidth(), img.getHeight()));
  }

  public static Rect autoCropOfBWImage(BWImage img, Rect r) {
    return autoCropOfBWImage(img, r, autoCropOfBWImage_threshold);
  }

  public static Rect autoCropOfBWImage(BWImage img, Rect r, float threshold) {
    int x1 = r.x, y1 = r.y, x2 = r.x2(), y2 = r.y2();
    end1: while (x1 < x2) {
      for (int y = y1; y < y2; y++) if (img.getPixel(x1, y) <= threshold)
        break end1;
      x1++;
    }
    end2: while (y1 < y2) {
      for (int x = x1; x < x2; x++) if (img.getPixel(x, y1) <= threshold)
        break end2;
      y1++;
    }
    end3: while (x2 > x1) {
      for (int y = y1; y < y2; y++) if (img.getPixel(x2 - 1, y) <= threshold)
        break end3;
      x2--;
    }
    end4: while (y2 > y1) {
      for (int x = x1; x < x2; x++) if (img.getPixel(x, y2 - 1) <= threshold)
        break end4;
      y2--;
    }
    if (x2 <= x1 || y2 <= y1)
      return r;
    else
      return new Rect(x1, y1, x2 - x1, y2 - y1);
  }

  public static Rect rectUnion(Rect a, Rect b) {
    if (a == null)
      return b;
    if (b == null)
      return a;
    int x = min(a.x, b.x), y = min(a.y, b.y);
    int x2 = max(a.x + a.w, b.x + b.w), y2 = max(a.y + a.h, b.y + b.h);
    return new Rect(x, y, x2 - x, y2 - y);
  }

  public static void darkenBWImagePart(BWImage img, Rect r) {
    darkenBWImagePart(img, r, 0.8f);
  }

  public static void darkenBWImagePart(BWImage img, Rect r, float factor) {
    int x2 = r.x2(), y2 = r.y2();
    for (int y = r.y; y < y2; y++) for (int x = r.x; x < x2; x++) img.setPixel(x, y, img.getPixel(x, y) * factor);
  }

  public static UnsupportedOperationException unsupportedOperation() {
    throw new UnsupportedOperationException();
  }

  public static int length(Object[] array) {
    return array == null ? 0 : array.length;
  }

  public static int length(List list) {
    return list == null ? 0 : list.size();
  }

  public static int length(String s) {
    return s == null ? 0 : s.length();
  }

  public static File loadLibrary(String snippetID) {
    return loadBinarySnippet(snippetID);
  }

  public static Class _run(String progID, String... args) {
    Class main = hotwire(progID);
    callMain(main, args);
    return main;
  }

  public static void cancelAndInterruptThread(Thread t) {
    if (t == null)
      return;
    cancelThread(t);
    t.interrupt();
  }

  public static int _hashCode(Object a) {
    return a == null ? 0 : a.hashCode();
  }

  public static String quoteBorderless(Object o) {
    if (o == null)
      return "null";
    return quoteBorderless(str(o));
  }

  public static String quoteBorderless(String s) {
    if (s == null)
      return "null";
    StringBuilder out = new StringBuilder((int) (l(s) * 1.5));
    quoteBorderless_impl(s, out);
    return out.toString();
  }

  public static void quoteBorderless_impl(String s, StringBuilder out) {
    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
        out.append(c);
    }
  }

  public static int hashCodeFor(Object a) {
    return a == null ? 0 : a.hashCode();
  }

  public static Set<String> allFields(Object o) {
    TreeSet<String> fields = new TreeSet();
    Class _c = _getClass(o);
    do {
      for (Field f : _c.getDeclaredFields()) fields.add(f.getName());
      _c = _c.getSuperclass();
    } while (_c != null);
    return fields;
  }

  public static int stdHash(Object a, String... fields) {
    if (a == null)
      return 0;
    int hash = getClassName(a).hashCode();
    for (String field : fields) hash = hash * 2 + hashCode(getOpt(a, field));
    return hash;
  }

  public static void addToContainer(final Container a, final Component b) {
    if (a != null && b != null) {
      swing(new Runnable() {

        public void run() {
          try {
            a.add(b);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "a.add(b);";
        }
      });
    }
  }

  public static void cancelThread(Thread t) {
    if (t == null)
      return;
    ping();
    synchronized (ping_actions) {
      ping_actions.put(t, "cancelled");
      ping_anyActions = true;
    }
  }

  public static int hashCode(Object a) {
    return a == null ? 0 : a.hashCode();
  }
}