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 javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import net.coobird.thumbnailator.Thumbnailator;
import static x30_pkg.x30_util.DynamicObject;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import javax.swing.undo.UndoManager;
import java.awt.geom.*;
import java.awt.datatransfer.UnsupportedFlavorException;

class main {

static void test_OneColorChecker() {
  //var img = shootScreen2();
  //var img = whiteImage(100, 100);
  var img = bwImageFromFunction(32, () -> random());
  //var img = new CheckerBoard;
  //img.cols = img.rows = 2;
  showImage(img);
  
  OneColorTheoryChecker ot = new OneColorTheoryChecker();
  var root = uRoot(img);
  var theory = ot.makeTheory(root);
  stepWithStats(64, ot.scheduler);
  print(theory.toStringWithEvidence());
}
static BWImage bwImageFromFunction(int w, IF2<Integer, Integer, Double> f) { return bwImageFromFunction(w, w, f); }
static BWImage bwImageFromFunction(int w, int h, IF2<Integer, Integer, Double> f) {
  BWImage img = new BWImage(w, h);
  for (int y = 0; y < h; y++)
    for (int x = 0; x < w; x++)
      img.setPixel(x, y, f.get(x, y).floatValue());
  return img;
}

static BWImage bwImageFromFunction(int w, IF0<Double> f) { return bwImageFromFunction(w, w, f); }
static BWImage bwImageFromFunction(int w, int h, IF0<Double> f) {
  return bwImageFromFunction(w, toIF2(f));
}


static Random random_random = new Random();

static int random(int n) {
  return random(random_random, n);
}

static int random(int n, Random r) { return random(r, n); }

static int random(Random r, int n) {
  return n <= 0 ? 0 : r.nextInt(n);
}

static double random(double max) {
  return random()*max;
}

static double random() {
  return random_random.nextInt(100001)/100000.0;
}

static double random(double min, double max) {
  return min+random()*(max-min);
}

// min <= value < max
static int random(int min, int max) {
  return min+random(max-min);
}

static int random(int min, int max, Random r) {
  return random(r, min, max);
}

static int random(Random r, int min, int max) {
  return min+random(r, max-min);
}

static <A> A random(List<A> l) {
  return oneOf(l);
}

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



static <A, B> Pair<A, B> random(Map<A, B> map) {
  return entryToPair(random(entries(map)));
}


static String showImage_defaultIcon = "#1004230"; // "#1004227";

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

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

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

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

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

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

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

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

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


  static ImageSurface showImage(String title, MakesBufferedImage img) {
    return showImage(title, img.getBufferedImage());
  }
  
  static ImageSurface showImage(ImageSurface is, MakesBufferedImage img) {
    return showImage(is, img.getBufferedImage());
  }
  
  static ImageSurface showImage(RGBImage img) {
    return showImage(img.getBufferedImage());
  }
  
  static ImageSurface showImage(RGBImage img, String title) {
    ImageSurface is = showImage(img.getBufferedImage());
    getFrame(is).setTitle(title);
    return is;
  }
  
  static ImageSurface showImage(ImageSurface surface, RGBImage img) {
    return showImage(img, surface);
  }
  
  static ImageSurface showImage(RGBImage img, ImageSurface surface) {
    if (surface == null)
      return showImage(img);
    else {
      surface.setImage(img);
      return surface;
    }
  }
  
  static ImageSurface showImage(ImageSurface surface, String title, RGBImage img) {
    return showImage(surface, img, title);
  }
  
  static ImageSurface showImage(ImageSurface surface, RGBImage img, String title) {
    return setFrameTitle(showImage(img, surface), title);
  }



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


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

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


static URecognizer.Cell uRoot(IIntegralImage img) {
  return new URecognizer(img).rootCell();
}

static URecognizer.Cell uRoot(BufferedImage img) {
  return uRoot(new IntegralImage(img));
}

static URecognizer.Cell uRoot(MakesBufferedImage img) {
  return uRoot(new IntegralImage(img));
}


static void stepWithStats(Steppable s, long maxSteps) {
  stepMaxWithStats(s, maxSteps);
}



static void stepWithStats(long maxSteps, Steppable s) {
  stepMaxWithStats(maxSteps, s);
}


static volatile StringBuffer local_log = new StringBuffer(); // not redirected




static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot

// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;

static boolean print_silent = false; // total mute if set

static Object print_byThread_lock = new Object();
static volatile ThreadLocal<Object> print_byThread; // special handling by thread - prefers F1<S, Bool>
static volatile Object print_allThreads;
static volatile Object print_preprocess;

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

static <A> A print(String s, A o) {
  print(combinePrintParameters(s, o));
  return o;
}

// slightly overblown signature to return original object...
static <A> A print(A o) {
  ping_okInCleanUp();
  if (print_silent) return o;
  String s = o + "\n";
  print_noNewLine(s);
  return o;
}

static void print_noNewLine(String s) {
  
  try {
    Object f = getThreadLocal(print_byThread_dontCreate());
    if (f == null) f = print_allThreads;
      if (f != null)
        // We do need the general callF machinery here as print_byThread is sometimes shared between modules
        if (isFalse(
          
            f instanceof F1 ? ((F1) f).get(s) :
          
          callF(f, s))) return;
  } catch (Throwable e) {
    System.out.println(getStackTrace(e));
  }
  

  print_raw(s);
}

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);
  
  vmBus_send("printed", mc(), s);
}

static void print_autoRotate() {
  
}




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


static <A, B, C> IF2<A, B, C> toIF2(IF0<C> f) {
  return f == null ? null : (a, b) -> f.get();
}


static <A> A oneOf(List<A> l) {
  return empty(l) ? null : l.get(new Random().nextInt(l.size()));
}

static char oneOf(String s) {
  return empty(s) ? '?' : s.charAt(random(l(s)));
}

static String oneOf(String... l) {
  return oneOf(asList(l));
}


static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }

static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible

static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); }
static long l(File f) { return f == null ? 0 : f.length(); }



static int l(Object o) {
  return o == null ? 0
    : o instanceof String ? l((String) o)
    : o instanceof Map ? l((Map) o)
    : o instanceof Collection ? l((Collection) o)
    : o instanceof Object[] ? l((Object[]) o)
    : o instanceof boolean[] ? l((boolean[]) o)
    : o instanceof byte[] ? l((byte[]) o)
    : o instanceof char[] ? l((char[]) o)
    : o instanceof short[] ? l((short[]) o)
    : o instanceof int[] ? l((int[]) o)
    : o instanceof float[] ? l((float[]) o)
    : o instanceof double[] ? l((double[]) o)
    : o instanceof long[] ? l((long[]) o)
    : (Integer) call(o, "size");
}











  static double l(DoubleRange r) { return r == null ? 0 : r.length(); }








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


static <A, B> Pair<A, B> entryToPair(Map.Entry<A, B> e) {
  return mapEntryToPair(e);
}


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


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

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


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

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

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


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


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

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


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

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


static int moveToTopRightCorner_inset = 20;

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

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



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

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


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

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


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

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

// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
  Object f = getOpt(mc(), "frame");
  if (f instanceof JFrame)
    return setFrameTitle((JFrame) f, title);
  return null;
}


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

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

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


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

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


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



static void stepMaxWithStats(Steppable s, long maxSteps) {
  stepAllWithStats(s, maxSteps);
}

static void stepMaxWithStats(long maxSteps, Steppable s) {
  stepMaxWithStats(s, maxSteps);
}


static String combinePrintParameters(String s, Object o) {
  return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
}


static void ping_okInCleanUp() {

  if (ping_pauseAll || ping_anyActions)
    ping_impl(true);

}


// this syntax should be removed...
static Object getThreadLocal(Object o, String name) {
  ThreadLocal t =  (ThreadLocal) (getOpt(o, name));
  return t != null ? t.get() : null;
}

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

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


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


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


static Map<Class, ArrayList<Method>> callF_cache = newDangerousWeakHashMap();


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



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



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



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





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



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


static Object callF(Runnable r) { { if (r != null) r.run(); } return null; }

static Object callF(Object f, Object... args) {
  if (f instanceof String)
    return callMCWithVarArgs((String) f, args); // possible SLOWDOWN over callMC
    
  return safeCallF(f, args);
}

static Object safeCallF(Object f, Object... args) {
  if (f instanceof Runnable) {
    ((Runnable) f).run();
    return null;
  }
  if (f == null) return null;
  
  Class c = f.getClass();
  ArrayList<Method> methods;
  synchronized(callF_cache) {
    methods = callF_cache.get(c);
    if (methods == null)
      methods = callF_makeCache(c);
  }
  
  int n = l(methods);
  if (n == 0) {
    
    throw fail("No get method in " + getClassName(c));
  }
  if (n == 1) return invokeMethod(methods.get(0), f, args);
  for (int i = 0; i < n; i++) {
    Method m = methods.get(i);
    if (call_checkArgs(m, args, false))
      return invokeMethod(m, f, args);
  }
  throw fail("No matching get method in " + getClassName(c));
}

// used internally
static ArrayList<Method> callF_makeCache(Class c) {
  ArrayList<Method> l = new ArrayList();
  Class _c = c;
  do {
    for (Method m : _c.getDeclaredMethods())
      if (m.getName().equals("get")) {
        makeAccessible(m);
        l.add(m);
      }
    if (!l.isEmpty()) break;
    _c = _c.getSuperclass();
  } while (_c != null);
  callF_cache.put(c, l);
  return l;
}


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

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

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


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


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


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

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


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




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


// f can return false to suppress regular printing
// call print_raw within f to actually print something
static AutoCloseable tempInterceptPrint(F1<String, Boolean> f) {
  return tempSetThreadLocal(print_byThread(), f);
}


static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }


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


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

static boolean empty(double[] a) { return a == null || a.length == 0; }
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean empty(byte[] a) { return a == null || a.length == 0; }
static boolean empty(short[] a) { return a == null || a.length == 0; }




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


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










// unclear semantics as to whether return null on null

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

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

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

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

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

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

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

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



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




static <A> int iteratorCount_int_close(Iterator<A> i) { try {
  int n = 0;
  if (i != null) while (i.hasNext()) { i.next(); ++n; }
  if (i instanceof AutoCloseable) ((AutoCloseable) i).close();
  return n;
} catch (Exception __e) { throw rethrow(__e); } }


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

// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
  return call(o, method, new Object[] {arg});
}

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


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


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


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


static boolean loadBufferedImage_useImageCache = true;

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();
        // fall back to loading from sourceforge
      }
  }

  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"));
    //Log.info("Cached image.");
  }

  //Log.info("Loaded image.");
  return image;
} catch (Exception __e) { throw rethrow(__e); } }

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


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

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


// get purpose 1: access a list/array/map (safer version of x.get(y))

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

// seems to conflict with other signatures
/*static <A, B> B get(Map<A, B> map, A key) {
  ret map != null ? map.get(key) : null;
}*/

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

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

// get purpose 2: access a field by reflection or a map

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

static Object get_raw(String field, Object o) {
  return get_raw(o, field);
}

static Object get_raw(Object o, String field) { try {
  if (o == null) return null;
  Field f = get_findField(o.getClass(), field);
  makeAccessible(f);
  return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }

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

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

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

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

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



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


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

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


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


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

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

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


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



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


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






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


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


static int packFrame_minw = 150, packFrame_minh = 50;

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

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


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

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

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

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

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

// make or update frame
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;
  }
}


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


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


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


static Frame getAWTFrame(final Object _o) {
  return swing(new F0<Frame>() { public Frame get() { try { 
    Object o = _o;
    /*
    ifdef HaveProcessing
      if (o instanceof PApplet) o = ((PApplet) o).getSurface();
    endifdef
    */
    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) ..."; }});
}


static Object getOpt(Object o, String field) {
  return getOpt_cached(o, field);
}

static Object getOpt(String field, Object o) {
  return getOpt_cached(o, field);
}

static Object getOpt_raw(Object o, String field) { try {
  Field f = getOpt_findField(o.getClass(), field);
  if (f == null) return null;
  makeAccessible(f);
  return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }

// access of static fields is not yet optimized
static Object getOpt(Class c, String field) { try {
  if (c == null) return null;
  Field f = getOpt_findStaticField(c, field);
  if (f == null) return null;
  makeAccessible(f);
  return f.get(null);
} catch (Exception __e) { throw rethrow(__e); } }

static Field getOpt_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}



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

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

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


static void stepAllWithStats(Steppable s) { stepAllWithStats(s, null); }
static void stepAllWithStats(Steppable s, Long maxSteps) {
  if (s == null) return;
  long n = 0;
  long time = sysNow();
  if (maxSteps == null)
    while  (s.step()) { ping(); ++n; }
  else
    while  (n < maxSteps && s.step()) { ping(); ++n; }
  time = sysNow()-time;
  print(n2(n, "step") + " in " + n2(time) + " ms");
}



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





//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map<Thread, Object> ping_actions = newWeakHashMap();
static ThreadLocal<Boolean> ping_isCleanUpThread = new ThreadLocal();

// always returns true
static boolean ping() {
  
  if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */);
  //ifndef LeanMode ping_impl(); endifndef
  return true;
}

// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
  if (ping_pauseAll && !isAWTThread()) {
    do
      Thread.sleep(ping_sleep);
    while (ping_pauseAll);
    return true;
  }
  
  if (ping_anyActions) { // don't allow sharing ping_actions
    if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
      failIfUnlicensed();
    Object action = null;
    synchronized(ping_actions) {
      if (!ping_actions.isEmpty()) {
        action = ping_actions.get(currentThread());
        if (action instanceof Runnable)
          ping_actions.remove(currentThread());
        if (ping_actions.isEmpty()) ping_anyActions = false;
      }
    }
    
    if (action instanceof Runnable)
      ((Runnable) action).run();
    else if (eq(action, "cancelled"))
      throw fail("Thread cancelled.");
  }

  return false;
} catch (Exception __e) { throw rethrow(__e); } }



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


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




static <A, B> Map<A, B> newDangerousWeakHashMap() {
  return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}

// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static <A, B> Map<A, B> newDangerousWeakHashMap(Object initFunction) {
  return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}


static Object callMCWithVarArgs(String method, Object... args) {
  return call_withVarargs(mc(), method, args);
}


static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }


static RuntimeException fail(Object... objects) { throw new Fail(objects); }


static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }



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


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


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


static Field makeAccessible(Field f) {
  try {
    f.setAccessible(true);
  } catch (Throwable e) {
    // Note: The error reporting only works with Java VM option --illegal-access=deny
    
    vmBus_send("makeAccessible_error", e, f);
    
  }
  return f;
}

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

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


// PersistableThrowable doesn't hold GC-disturbing class references in backtrace
static volatile PersistableThrowable lastException_lastException;

static PersistableThrowable lastException() {
  return lastException_lastException;
}

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


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

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

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


static <A> int indexOf(List<A> l, A a, int startIndex) {
  if (l == null) return -1;
  int n = l(l);
  for (int i = startIndex; i < n; i++)
    if (eq(l.get(i), a))
      return i;
  return -1;
}

static <A> int indexOf(List<A> l, int startIndex, A a) {
  return indexOf(l, a, startIndex);
}

static <A> int indexOf(List<A> l, A a) {
  if (l == null) return -1;
  return l.indexOf(a);
}

static int indexOf(String a, String b) {
  return a == null || b == null ? -1 : a.indexOf(b);
}

static int indexOf(String a, String b, int i) {
  return a == null || b == null ? -1 : a.indexOf(b, i);
}

static int indexOf(String a, char b) {
  return a == null ? -1 : a.indexOf(b);
}

static int indexOf(String a, int i, char b) {
  return indexOf(a, b, i);
}

static int indexOf(String a, char b, int i) {
  return a == null ? -1 : a.indexOf(b, i);
}

static int indexOf(String a, int i, String b) {
  return a == null || b == null ? -1 : a.indexOf(b, i);
}

static <A> int indexOf(A[] x, A a) {
  int n = l(x);
  for (int i = 0; i < n; i++)
    if (eq(x[i], a))
      return i;
  return -1;
}


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


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


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


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

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


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

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


static Map<String, Set> vm_busListenersByMessage_live_cache;
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; }

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




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


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


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

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


static ArrayList emptyList() {
  return new ArrayList();
  //ret Collections.emptyList();
}

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

// Try to match capacity
static ArrayList emptyList(Iterable l) {
  return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}

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

// get correct type at once
static <A> ArrayList<A> emptyList(Class<A> c) {
  return new ArrayList();
}


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);
      
    // try varargs
    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);
      
    // try varargs
    List<Method> methods = cache.cache.get(method);
    if (methods != null) methodSearch: for (Method m : methods) {
      { if (!(m.isVarArgs())) continue; }
      Object[] newArgs = massageArgsForVarArgsCall(m, args);
      if (newArgs != null)
        return invokeMethod(m, o, newArgs);
    }
    
    throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
  }
} catch (Exception __e) { throw rethrow(__e); } }


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

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


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


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



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

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


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


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


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


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


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

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


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


// TODO: test if android complains about this
static boolean isAWTThread() {
  if (isAndroid()) return false;
  if (isHeadless()) return false;
  return isAWTThread_awt();
}

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


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


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


static Object getOptDynOnly(DynamicObject o, String field) {
  if (o == null || o.fieldValues == null) return null;
  return o.fieldValues.get(field);
}


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


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


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


static int getScreenWidth() {
  return getScreenSize().width;
}


static int getScreenHeight() {
  return getScreenSize().height;
}


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

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

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

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

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

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

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

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

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


static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }

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

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

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

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

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

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


static String makeFrame_defaultIcon;
static boolean makeFrame_hideConsole = false;
static ThreadLocal<VF1<JFrame>> makeFrame_post = new ThreadLocal();

static JFrame makeFrame() {
  return makeFrame((Component) null);
}

static JFrame makeFrame(Object content) {
  return makeFrame(programTitle(), content);
}

static JFrame makeFrame(String title) {
  return makeFrame(title, null);
}

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

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);
    //callOpt(content, "requestFocus");
    //exitOnFrameClose(frame);
    
    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) ..."; }});
}


static boolean frameTooSmall(JFrame frame) {
  return frame.getWidth() < 100 || frame.getHeight() < 50;
}


static void frameStandardSize(JFrame frame) {
  frame.setBounds(300, 100, 500, 400);
}


static void setFrameContents(final Component c, final Object contents) { swing(new Runnable() {  public void run() { try { 
  JFrame frame = getFrame(c);
  if (frame == null) return;
  frame.getContentPane().removeAll();
  frame.getContentPane().setLayout(new BorderLayout());
  frame.getContentPane().add(wrap(contents));
  revalidate(frame);

} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "JFrame frame = getFrame(c);\r\n  if (frame == null) return;\r\n  frame.getContent..."; }}); }


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

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

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


static int imageIcon_cacheSize = 10;
static boolean imageIcon_verbose = false;
static Map<String, ImageIcon> imageIcon_cache;
static Lock imageIcon_lock = lock();
static ThreadLocal<Boolean> imageIcon_fixGIF = new ThreadLocal();

// not going through BufferedImage preserves animations
static ImageIcon imageIcon(String imageID) { try {
  if (imageID == null) return null;
  Lock __0 = imageIcon_lock; lock(__0); try {
  if (imageIcon_cache == null)
    imageIcon_cache = new MRUCache(imageIcon_cacheSize);
  imageID = fsI(imageID);
  ImageIcon ii = imageIcon_cache.get(imageID);
  if (ii == null) {
    if (imageIcon_verbose) print("Loading image icon: " + imageID);
    File f = loadBinarySnippet(imageID);
    
      Boolean b = imageIcon_fixGIF.get();
      if (!isFalse(b))
        ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
      else
    
    ii = new ImageIcon(f.toURI().toURL());
  } else
    imageIcon_cache.remove(imageID); // move to front of cache on access
  imageIcon_cache.put(imageID, ii);
  return ii;
} finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } }

// doesn't fix GIFs
static ImageIcon imageIcon(File f) { try {
  return new ImageIcon(f.toURI().toURL());
} catch (Exception __e) { throw rethrow(__e); } }

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


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



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

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


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

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



//static final Map<Class, HashMap<S, Field>> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);

static class getOpt_Map extends WeakHashMap {
  getOpt_Map() {
    if (getOpt_special == null) getOpt_special = new HashMap();
    clear();
  }
  
  public void clear() {
    super.clear();
    //print("getOpt clear");
    put(Class.class, getOpt_special);
    put(String.class, getOpt_special);
  }
}

static final Map<Class, HashMap<String, Field>> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
//static final Map<Class, HashMap<S, Field>> getOpt_cache = _registerWeakMap(synchroMap(new getOpt_Map));
static HashMap getOpt_special; // just a marker

/*static void getOpt_special_init(Map map) {
  map.put(Class.class, getOpt_special);
  map.put(S.class, getOpt_special);
}*/

static Map<String, Field> getOpt_getFieldMap(Object o) {
  Class c = _getClass(o);
  HashMap<String, Field> map = getOpt_cache.get(c);
  if (map == null)
    map = getOpt_makeCache(c);
  return map;
}

static Object getOpt_cached(Object o, String field) { try {
  if (o == null) return null;

  Map<String, Field> map = getOpt_getFieldMap(o);

  if (map == getOpt_special) {
    if (o instanceof Class)
      return getOpt((Class) o, field);
    /*if (o instanceof S)
      ret getOpt(getBot((S) o), field);*/
    if (o instanceof Map)
      return ((Map) o).get(field);
  }
    
  Field f = map.get(field);
  if (f != null) return f.get(o);
  
    if (o instanceof DynamicObject)
      return syncMapGet2(((DynamicObject) o).fieldValues, field);
  
  return null;
} catch (Exception __e) { throw rethrow(__e); } }

// used internally - we are in synchronized block
static HashMap<String, Field> getOpt_makeCache(Class c) {
  HashMap<String, Field> map;
  if (isSubtypeOf(c, Map.class))
    map = getOpt_special;
  else {
    map = new HashMap();
    if (!reflection_classesNotToScan().contains(c.getName())) {
      Class _c = c;
      do {
        for (Field f : _c.getDeclaredFields()) {
          makeAccessible(f);
          String name = f.getName();
          if (!map.containsKey(name))
            map.put(name, f);
        }
        _c = _c.getSuperclass();
      } while (_c != null);
    }
  }
  if (getOpt_cache != null) getOpt_cache.put(c, map);
  return map;
}


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


static String n2(long l) { return formatWithThousands(l); }
static String n2(Collection l) { return n2(l(l)); }
static String n2(Map map) { return n2(l(map)); }

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

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

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

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

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

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

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

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

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

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




static <A, B> Map<A, B> newWeakHashMap() {
  return _registerWeakMap(synchroMap(new WeakHashMap()));
}


static boolean isTrue(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  if (o == null) return false;
  if (o instanceof ThreadLocal) // TODO: remove this
    return isTrue(((ThreadLocal) o).get());
  throw fail(getClassName(o));
}

static boolean isTrue(Boolean b) {
  return b != null && b.booleanValue();
}


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


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


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

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


static List<Pair> _registerDangerousWeakMap_preList;

static <A> A _registerDangerousWeakMap(A map) {
  return _registerDangerousWeakMap(map, null);
}

static <A> A _registerDangerousWeakMap(A map, Object init) {
  
  callF(init, map);
  
  if (init instanceof String) {
    final String f =  (String) init;
    init = new VF1<Map>() { public void get(Map map) { try {  callMC(f, map) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "callMC(f, map)"; }};
  }
    
  if (javax() == null) {
    // We're in class init
    if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList();
    _registerDangerousWeakMap_preList.add(pair(map, init));
    return map;
  }
  
  call(javax(), "_registerDangerousWeakMap", map, init);
  
  return map;
}

static void _onLoad_registerDangerousWeakMap() {
  
  assertNotNull(javax());
  if (_registerDangerousWeakMap_preList == null) return;
  for (Pair p : _registerDangerousWeakMap_preList)
    _registerDangerousWeakMap(p.a, p.b);
  _registerDangerousWeakMap_preList = null;
  
}


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

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


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


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

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



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

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


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


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


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

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


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


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


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

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


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


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



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





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


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

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);
    
    // TODO: (super-rare) case where method exists static and non-static
    // with different args
    
    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); } }

// no longer synchronizes! (see #1102990)
static _MethodCache callOpt_getCache(Class c) {
  _MethodCache cache = callOpt_cache.get(c);
  if (cache == null)
    callOpt_cache.put(c, cache = new _MethodCache(c));
  return cache;
}


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


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


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

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


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



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


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

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


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


static File javaxCachesDir_dir; // can be set to work on different base dir

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

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


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


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

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

static String snippetImageURL(String snippetID, String contentType) {
  if (snippetID == null || isURL(snippetID)) return snippetID;
  long id = parseSnippetID(snippetID);
  String url;
  if (isImageServerSnippet(id))
    url = imageServerLink(id);
  else
    //url = "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=image/" + contentType;
    url = "https://botcompany.de/img/" + id;
  return url;
}


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

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


static int isAndroid_flag;

static boolean isAndroid() {
  if (isAndroid_flag == 0)
    isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
  return isAndroid_flag > 0;
}



static Boolean isHeadless_cache;

static boolean isHeadless() {
  if (isHeadless_cache != null) return isHeadless_cache;
  if (isAndroid()) return isHeadless_cache = true;
  if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
  
  // Also check if AWT actually works.
  // If DISPLAY variable is set but no X server up, this will notice.
  
  try {
    SwingUtilities.isEventDispatchThread();
    return isHeadless_cache = false;
  } catch (Throwable e) { return isHeadless_cache = true; }
}


static List<VF1<Map>> _threadInfo_makers = synchroList();

static Object _threadInfo() {
  if (empty(_threadInfo_makers)) return null;
  HashMap map = new HashMap();
  pcallFAll(_threadInfo_makers, map);
  return map;
}


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




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


static Class __javax;

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


static String programTitle() {
  return getProgramName();
}


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

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

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

// now also takes a map as single array entry
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;
}

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

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


static void _initFrame(JFrame f) {
  myFrames_list.put(f, Boolean.TRUE);
  standardTitlePopupMenu(f);
}


// c = Component or something implementing swing()
static JComponent wrap(Object swingable) {
  return _recordNewSwingComponent(wrap_2(swingable));
}

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


static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);

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


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


static <A extends Component> A revalidate(final A c) {
  if (c == null || !c.isShowing()) return c;
  { swing(new Runnable() {  public void run() { try { 
    // magic combo to actually relayout and repaint
    c.revalidate();
    c.repaint();
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "// magic combo to actually relayout and repaint\r\n    c.revalidate();\r\n    c.r..."; }}); }
  return c;
}

static void revalidate(JFrame f) { revalidate((Component) f); }
static void revalidate(JInternalFrame f) { revalidate((Component) f); }


static String defaultThreadName_name;

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


static Runnable wrapAsActivity(Object r) {
  if (r == null) return null;
  Runnable r2 = toRunnable(r);
  Object mod = dm_current_generic();
  if (mod == null) return r2;
  return new Runnable() {  public void run() { try { 
     AutoCloseable __1 =  (AutoCloseable) (rcall("enter", mod)); try {
    r2.run();
  
} finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "temp (AutoCloseable) rcall enter(mod);\r\n    r2.run();"; }};
}


// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
  return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)));
}

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

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


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


static Map<Thread, Boolean> _registerThread_threads;
static Object _onRegisterThread; // voidfunc(Thread)

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

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


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

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

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

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


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

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


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







static boolean loadBufferedImageFixingGIFs_debug = false;
static ThreadLocal<Var<byte[]>> loadBufferedImageFixingGIFs_output = new ThreadLocal();

static Image loadBufferedImageFixingGIFs(File file) { try {
  if (!file.exists()) return null;

  // Load anything but GIF the normal way
  if (!isGIF(file))
    return ImageIO.read(file);
    
  if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": checking gif");

  // Get GIF reader
  ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
  // Give it the stream to decode from
  reader.setInput(ImageIO.createImageInputStream(file));

  int numImages = reader.getNumImages(true);

  // Get 'metaFormatName'. Need first frame for that.
  IIOMetadata imageMetaData = reader.getImageMetadata(0);
  String metaFormatName = imageMetaData.getNativeMetadataFormatName();

  // Find out if GIF is bugged
  boolean foundBug = false;
  for (int i = 0; i < numImages && !foundBug; i++) {
      // Get metadata
      IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName);

      // Find GraphicControlExtension node
      int nNodes = root.getLength();
      for (int j = 0; j < nNodes; j++) {
          org.w3c.dom.Node node = root.item(j);
          if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
              // Get delay value
              String delay = ((IIOMetadataNode)node).getAttribute("delayTime");

              // Check if delay is bugged
              if (Integer.parseInt(delay) == 0) {
                  foundBug = true;
              }

              break;
          }
      }
  }

  if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
  
  // Load non-bugged GIF the normal way
  Image image;
  if (!foundBug) {
    image = Toolkit.getDefaultToolkit().createImage(f2s(file));
  } else {
    // Prepare streams for image encoding
    ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
    {
       ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream); try {
      // Get GIF writer that's compatible with reader
      ImageWriter writer = ImageIO.getImageWriter(reader);
      // Give it the stream to encode to
      writer.setOutput(ios);

      writer.prepareWriteSequence(null);

      for (int i = 0; i < numImages; i++) {
          // Get input image
          BufferedImage frameIn = reader.read(i);

          // Get input metadata
          IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName);

          // Find GraphicControlExtension node
          int nNodes = root.getLength();
          for (int j = 0; j < nNodes; j++) {
              org.w3c.dom.Node node = root.item(j);
              if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
                  // Get delay value
                  String delay = ((IIOMetadataNode)node).getAttribute("delayTime");

                  // Check if delay is bugged
                  if (Integer.parseInt(delay) == 0) {
                      // Overwrite with a valid delay value
                      ((IIOMetadataNode)node).setAttribute("delayTime", "10");
                  }

                  break;
              }
          }

          // Create output metadata
          IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
          // Copy metadata to output metadata
          metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);

          // Create output image
          IIOImage frameOut = new IIOImage(frameIn, null, metadata);

          // Encode output image
          writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
      }

      writer.endWriteSequence();
    } finally { _close(ios); }}

    // Create image using encoded data
    byte[] data = baoStream.toByteArray();
    setVar(loadBufferedImageFixingGIFs_output.get(), data);
    if (loadBufferedImageFixingGIFs_debug) print("Data size: " + l(data));
    image = Toolkit.getDefaultToolkit().createImage(data);
  }

  return image;
} catch (Exception __e) { throw rethrow(__e); } }




static void unlock(Lock lock, String msg) {
  if (lock == null) return;
  lock.unlock();
  vmBus_send("unlocked", lock, "thread" , currentThread());
  print("Unlocked: " + msg); // print afterwards to make sure the lock is always unlocked
}

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


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

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

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

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

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


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











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));
  if (o instanceof Boolean)
    return boolToInt(((Boolean) o));
  throw fail("woot not int: " + getClassName(o));
}

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


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

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


static void clear(Collection c) {
  if (c != null) c.clear();
}

static void clear(Map map) {
  if (map != null) map.clear();
}


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

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


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

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

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


static <A, B> B syncMapGet2(Map<A, B> map, A a) {
  if (map == null) return null;
  synchronized(collectionMutex(map)) {
    return map.get(a);
  }
}

static <A, B> B syncMapGet2(A a, Map<A, B> map) {
  return syncMapGet2(map, a);
}


static boolean isSubtypeOf(Class a, Class b) {
  return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}


static Set<String> reflection_classesNotToScan_value = litset(
  "jdk.internal.loader.URLClassPath"
);

static Set<String> reflection_classesNotToScan() {
  return reflection_classesNotToScan_value;
}


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


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


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

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

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

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




static List _registerWeakMap_preList;

static <A> A _registerWeakMap(A map) {
  if (javax() == null) {
    // We're in class init
    if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList();
    _registerWeakMap_preList.add(map);
    return map;
  }
  
  try {
    call(javax(), "_registerWeakMap", map);
  } catch (Throwable e) {
    printException(e);
    print("Upgrade JavaX!!");
  }
  return map;
}

static void _onLoad_registerWeakMap() {
  assertNotNull(javax());
  if (_registerWeakMap_preList == null) return;
  for (Object o : _registerWeakMap_preList)
    _registerWeakMap(o);
  _registerWeakMap_preList = null;
}


static void assertTrue(Object o) {
  if (!(eq(o, true) /*|| isTrue(pcallF(o))*/))
    throw fail(str(o));
}
  
static boolean assertTrue(String msg, boolean b) {
  if (!b)
    throw fail(msg);
  return b;
}

static boolean assertTrue(boolean b) {
  if (!b)
    throw fail("oops");
  return b;
}


static volatile boolean licensed_yes = true;

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

static void licensed_off() {
  licensed_yes = false;
}


static HashMap<String, List<Method>> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;

// varargs assignment fixer for a single string array argument
static Object callMC(String method, String[] arg) {
  return callMC(method, new Object[] {arg});
}

static Object callMC(String method, Object... args) { try {
  Method me;
  if (callMC_cache == null) callMC_cache = new HashMap(); // initializer time workaround
  synchronized(callMC_cache) {
    me = method == callMC_key ? callMC_value : null;
  }
  if (me != null) try {
    return invokeMethod(me, null, args);
  } catch (IllegalArgumentException e) {
    throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
  }

  List<Method> m;
  synchronized(callMC_cache) {
    m = callMC_cache.get(method);
  }
  if (m == null) {
    if (callMC_cache.isEmpty()) {
      callMC_makeCache();
      m = callMC_cache.get(method);
    }
    if (m == null) throw fail("Method named " + method + " not found in main");
  }
  int n = m.size();
  if (n == 1) {
    me = m.get(0);
    synchronized(callMC_cache) {
      callMC_key = method;
      callMC_value = me;
    }
    try {
      return invokeMethod(me, null, args);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
    }
  }
  for (int i = 0; i < n; i++) {
    me = m.get(i);
    if (call_checkArgs(me, args, false))
      return invokeMethod(me, null, args);
  }
  throw fail("No method called " + method + " with arguments (" + joinWithComma(getClasses(args)) + ") found in main");
} catch (Exception __e) { throw rethrow(__e); } }

static void callMC_makeCache() {
  synchronized(callMC_cache) {
    callMC_cache.clear();
    Class _c = (Class) mc(), c = _c;
    while (c != null) {
      for (Method m : c.getDeclaredMethods())
        if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
          makeAccessible(m);
          multiMapPut(callMC_cache, m.getName(), m);
        }
      c = c.getSuperclass();
    }
  }
}


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

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



static <A> A assertNotNull(A a) {
  assertTrue(a != null);
  return a;
}

static <A> A assertNotNull(String msg, A a) {
  assertTrue(msg, a != null);
  return a;
}


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



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

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

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

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

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


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



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


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

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


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


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




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


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


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

static Object collectionMutex(Object o) {
  

  if (o instanceof List) return o;
  
  String c = className(o);
  if (eq(c, "java.util.TreeMap$KeySet"))
    c = className(o = getOpt(o, "m"));
  else if (eq(c, "java.util.HashMap$KeySet"))
    c = className(o = get_raw(o, "this$0"));

  
  
  if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
    c = className(o = get_raw(o, "m"));
    
  
    
  
  return o;
}


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


static Throwable _storeException_value;

static void _storeException(Throwable e) {
  _storeException_value = e;
}


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


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


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




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

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



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


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


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

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


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

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


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

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


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


static Map vm_generalMap_map;

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


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

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


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

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



// convenience method for quickly dropping a prefix
static String substring(String s, CharSequence l) {
  return substring(s, lCharSequence(l));
}


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


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

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


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

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


static List<VF1<Map>> _threadInheritInfo_retrievers = synchroList();

static void _threadInheritInfo(Object info) {
  if (info == null) return;
  pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}


static String getProgramName_cache;

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

static void _onLoad_getProgramName() {
  { startThread(new Runnable() {  public void run() { try {  getProgramName(); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "getProgramName();"; }}); }
}


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

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

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

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

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

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

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


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

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


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

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

static boolean even(BigInteger n) {
  return even(n.intValue());
}


static void standardTitlePopupMenu(final JFrame frame) {
  // standard right-click behavior on titles
  if (!isSubstanceLAF()) return;
  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)"; }}));
    /*ifndef standardTitlePopupMenu_noShootWindow
      { menu.add(jMenuItem("Shoot Window", r { shootWindowGUI_external(frame, 500) })); }
    endifndef*/
    //addMenuItem(menu, "Bigger fonts", f swingBiggerFonts);
    //addMenuItem(menu, "Smaller fonts", f swingSmallerFonts);
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n    ifndef standardTitlePopupMenu_..."; }});
}


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


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



static Object callOpt(Object o) {
  return callF(o);
}

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


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


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

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


static Rectangle screenRectangle() {
  return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
}

static Rectangle screenRectangle(GraphicsDevice device) {
  if (device == null) return null;
  DisplayMode mode = device.getDisplayMode();
  return new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
}



static JFrame consoleFrame() {
  return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}


static void autoVMExit() {
  call(getJavaX(), "autoVMExit");
}


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

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


static Object dm_current_generic() {
  return getWeakRef(dm_current_generic_tl().get());
}


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


static void _close(AutoCloseable c) {
  if (c != null) try {
    c.close();
  } catch (Throwable e) {
    // Some classes stupidly throw an exception on double-closing
    if (c instanceof javax.imageio.stream.ImageOutputStream)
      return;
    else throw rethrow(e);
  }
}


static Runnable _topLevelErrorHandling(Runnable r) {
  if (r == null) return null;
  
  // maybe we don't want this anymore. just dm_current_generic()
  Object info = _threadInfo();
  Object mod = dm_current_generic();
  if (info == null && mod == null) return r;
  
  return new Runnable() {  public void run() { try { 
     AutoCloseable __1 =  (AutoCloseable) (rcall("enter", mod)); try {
    _threadInheritInfo(info);
    r.run();
  
} finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "temp (AutoCloseable) rcall enter(mod);\r\n    _threadInheritInfo(info);\r\n    r...."; }};
}


static Map vm_generalWeakSubMap(Object name) {
  synchronized(get(javax(), "generalMap")) {
    Map map =  (Map) (vm_generalMap_get(name));
    if (map == null)
      vm_generalMap_put(name, map = newWeakMap());
    return map;
  }
}



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


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


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


static <A extends Throwable> A printStackTrace(A e) {
  // we go to system.out now - system.err is nonsense
  print(getStackTrace(e));
  return e;
}

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

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

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


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


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


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

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



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



// If you change this, also change DiskSnippetCache_fileToLibID
static File DiskSnippetCache_file(long snippetID) {
  return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
  
  // Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
  File file = DiskSnippetCache_file(snippetID);
  return file.exists() ? file : null;
}

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

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


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



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


static byte[] isGIF_magic = bytesFromHex("47494638"); // Actual signature is longer, but we're lazy

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

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


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


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

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


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


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

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


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

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


static ClassLoader classLoaderForObject(Object o) {
  if (o instanceof ClassLoader) return ((ClassLoader) o);
  if (o == null) return null;
  return _getClass(o).getClassLoader();
}


// Note: This is actually broken. Inner classes must stay with a $ separator
static String classNameToVM(String name) {
  return name.replace(".", "$");
}


static <A> HashSet<A> litset(A... items) {
  return lithashset(items);
}




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


static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }


static <A extends Throwable> A printException(A e) {
  printStackTrace(e);
  return e;
}


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


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


static <A, B> void multiMapPut(MultiMap<A, B> mm, A key, B value) {
  if (mm != null && key != null && value != null) mm.put(key, value);
}



static Map synchronizedMap() {
  return synchroMap();
}

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


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

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

static <A> List<A> unnull(List<A> l) { return l == null ? emptyList() : l; }
static int[] unnull(int[] l) { return l == null ? emptyIntArray() : l; }
static char[] unnull(char[] l) { return l == null ? emptyCharArray() : l; }
static double[] unnull(double[] l) { return l == null ? emptyDoubleArray() : l; }

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

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

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

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


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


//ifclass Symbol



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


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


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


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


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


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


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



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


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


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



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


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


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


static <A> Set<A> synchronizedSet() {
  return synchroHashSet();
}

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


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




static void restart() {
  Object j = getJavaX();
  call(j, "cleanRestart", get(j, "fullArgs"));
}


static void duplicateThisProgram() {
  nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
}


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


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


static <A, B> List<A> keysList(Map<A, B> map) {
  return cloneListSynchronizingOn(keys(map), map);
}




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


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


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

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


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

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


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


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


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


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



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



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


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

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



static Lock downloadLock_lock = fairLock();

static Lock downloadLock() {
  return downloadLock_lock;
}


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


static boolean isSubstanceLAF() {
  return substanceLookAndFeelEnabled();
}


// menuMaker = voidfunc(JPopupMenu)
// return true if menu could be added
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; }
}


static boolean jmenuItem_newThreads = false;

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

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


// r : runnable or voidfunc(bool)
static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
  final JCheckBoxMenuItem mi = swing(() -> 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;
}

static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, IVF1<Boolean> r) {
  return jCheckBoxMenuItem(text, checked, (Object) r);
}



static void toggleAlwaysOnTop(JFrame frame) {
  frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
}


static Object callOpt_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.findMethod(method, args);
    if (me == null) {
      // TODO: varargs
      return null;
    }
    if ((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(method, args);
    if (me != null)
      return invokeMethod(me, o, args);
      
    // try varargs
    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);
    }
    
    return null;
  }
} catch (Exception __e) { throw rethrow(__e); } }


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



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


// TODO: ask JavaX instead
static String getProgramID(Class c) {
  String id = (String) getOpt(c, "programID");
  if (nempty(id))
    return formatSnippetID(id);
  return "?";
}


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


static <A> A getWeakRef(Reference<A> ref) {
  return ref == null ? null : ref.get();
}


static x30_pkg.x30_util.BetterThreadLocal<WeakReference> dm_current_generic_tl;

static x30_pkg.x30_util.BetterThreadLocal<WeakReference> dm_current_generic_tl() {
  if (dm_current_generic_tl == null)
    dm_current_generic_tl = vm_generalMap_getOrCreate("currentModule", () -> new x30_pkg.x30_util.BetterThreadLocal());
  return dm_current_generic_tl;
}


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


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


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


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

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


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

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

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

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



/** writes safely (to temp file, then rename) */
public static byte[] saveBinaryFile(String fileName, byte[] contents) { try {
  File file = new File(fileName);
  File parentFile = file.getParentFile();
  if (parentFile != null)
    parentFile.mkdirs();
  String tempFileName = fileName + "_temp";
  FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
  fileOutputStream.write(contents);
  fileOutputStream.close();
  if (file.exists() && !file.delete())
    throw new IOException("Can't delete " + fileName);

  if (!new File(tempFileName).renameTo(file))
    throw new IOException("Can't rename " + tempFileName + " to " + fileName);
    
  
  vmBus_send("wroteFile", file);
  
  return contents;
} catch (Exception __e) { throw rethrow(__e); } }

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


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



static String dataSnippetLink(String snippetID) {
  long id = parseSnippetID(snippetID);
  if (id >= 1100000 && id < 1200000)
    return imageServerURL() + id;
  if (id >= 1200000 && id < 1300000) { // Woody files, actually
    String pw = muricaPassword();
    if (empty(pw)) throw fail("Please set 'murica password by running #1008829");
    return "https://botcompany.de/files/" + id + "?_pass=" + pw; // XXX, although it typically gets hidden when printing
  }
  return fileServerURL() + "/" + id /*+ "?_pass=" + muricaPassword()*/;
}


static String tb_mainServer_default = "http://code.botcompany.de:8081";
static Object tb_mainServer_override; // func -> S

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

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

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


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


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

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

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/*Long*/(); } catch (Throwable e) { printStackTrace(e); }
    String pat = "  {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
    copyStreamWithPrints(inputStream, buf, pat);
    inputStream.close();
    buf.close();
    file.delete();
    renameFile_assertTrue(ftemp, file);
  } finally {
    if (buf != null) buf.close();
  }
} catch (Exception __e) { throw rethrow(__e); } }



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

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


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


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

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


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


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


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


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


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


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


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


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


static <A> HashSet<A> lithashset(A... items) {
  HashSet<A> set = new HashSet();
  for (A a : items) set.add(a);
  return set;
}


static int[] emptyIntArray_a = new int[0];
static int[] emptyIntArray() { return emptyIntArray_a; }


static char[] emptyCharArray = new char[0];
static char[] emptyCharArray() { return emptyCharArray; }


static double[] emptyDoubleArray = new double[0];
static double[] emptyDoubleArray() { return emptyDoubleArray; }


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


static Object[] emptyObjectArray_a = new Object[0];
static Object[] emptyObjectArray() { return emptyObjectArray_a; }


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


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


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



// TODO: OurSyncCollections
static <A> Set<A> synchroHashSet() {
  return Collections.synchronizedSet(new HashSet<A>());
}





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

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


// Try to get the quoting right...

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

static String smartJoin(List<String> args) {
  return smartJoin(toStringArray(args));
}


static <A> ArrayList<A> cloneListSynchronizingOn(Collection<A> l, Object mutex) {
  if (l == null) return new ArrayList();
  synchronized(mutex) {
    return new ArrayList<A>(l);
  }
}


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

// convenience shortcut for keys_gen
static Set keys(Object map) {
  return keys((Map) map);
}




  static <A, B> Set<A> keys(MultiMap<A, B> mm) {
    return mm.keySet();
  }







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


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


static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll((IVF1<Throwable>) (__1 -> printStackTrace2(__1))));
static boolean _handleException_showThreadCancellations = false;

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) {
    if (_handleException_showThreadCancellations)
      System.out.println(getStackTrace_noRecord(e2));
    return;
  }

  for (Object f : cloneList(_handleException_onException)) try {
    callF(f, e);
  } catch (Throwable e3) {
    try {
      printStackTrace2(e3); // not using pcall here - it could lead to endless loops
    } catch (Throwable e4) {
      System.out.println(getStackTrace(e3));
      System.out.println(getStackTrace(e4));
    }
  }
}


static String getSnippetTitle(String id) {
  if (id == null) return null;
  if (!isSnippetID(id)) return "?";
  
  
  IResourceLoader rl = vm_getResourceLoader();
  if (rl != null)
    return rl.getSnippetTitle(id);
  
  
  return getSnippetTitle_noResourceLoader(id);
}
  
static String getSnippetTitle_noResourceLoader(String id) { try {
  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); } }

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



static boolean substanceLookAndFeelEnabled() {
  return startsWith(getLookAndFeel(), "org.pushingpixels.");
}


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 /*SubstanceRootPaneUI*/ ui = rootPane.getUI();
		return (JComponent) call(ui, "getTitlePane");
	}
	return null;
}


static RootPaneContainer getPossiblyInternalFrame(Component c) {
  JInternalFrame f = getInternalFrame(c);
  if (f != null) return f;
  return optCast(RootPaneContainer.class, getWindow(c));
}




static ThreadLocal<MouseEvent> componentPopupMenu_mouseEvent;

static void componentPopupMenu_init() {
  { swing(new Runnable() {  public void run() { try { 
    if (componentPopupMenu_mouseEvent == null)
      componentPopupMenu_mouseEvent = (ThreadLocal<MouseEvent>) vm_generalMap_get("mouseEvent");
    if (componentPopupMenu_mouseEvent == null)
      vm_generalMap_put("componentPopupMenu_mouseEvent" , componentPopupMenu_mouseEvent = new ThreadLocal());
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (componentPopupMenu_mouseEvent == null)\r\n      componentPopupMenu_mouseEve..."; }}); }
}

// menuMaker = voidfunc(JPopupMenu)
static void componentPopupMenu(final JComponent component, final Object menuMaker) {
  if (component == null || menuMaker == null) return;
  { swing(new Runnable() {  public void run() { try { 
    Object adapter = componentPopupMenu_initForComponent(component);
    ((List) _get(adapter, "maker")).add(menuMaker);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "Object adapter = componentPopupMenu_initForComponent(component);\r\n    ((List)..."; }}); }
}

static Object componentPopupMenu_initForComponent(final JComponent component) {
  return component == null ? null : swing(new F0<Object>() { public Object get() { try { 
    componentPopupMenu_init();
    Object adapter = findComponentPopupMenuListener_gen(component);
    if (adapter == null) {
      componentPopupMenu_Adapter a = new componentPopupMenu_Adapter();
      component.addMouseListener(a);
      adapter = a;
    }
    return adapter;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "componentPopupMenu_init();\r\n    O adapter = findComponentPopupMenuListener_ge..."; }});
}

static class componentPopupMenu_Adapter extends MouseAdapter {
  List maker = new ArrayList();
  boolean internalFrameLeftButtonMagic = false;
  
  Point pressedAt;

  public void mousePressed(MouseEvent e) {
    displayMenu(e);
    pressedAt = internalFrameLeftButtonMagic && e.getClickCount() == 1 && internalFrameActive(e.getComponent()) ? e.getLocationOnScreen() : null;
  }
  
  public void mouseReleased(MouseEvent e) {
    // TODO: show a little less often on left mouse click
    if (internalFrameLeftButtonMagic && eq(pressedAt, e.getLocationOnScreen()))
      displayMenu2(e);
    else
      displayMenu(e);
  }

  void displayMenu(MouseEvent e) {
    if (e.getSource() instanceof JInternalFrame) return;
    if (e.isPopupTrigger()) displayMenu2(e);
  }
    
  void displayMenu2(MouseEvent e) {
    JPopupMenu menu = new JPopupMenu();
    int emptyCount = menu.getComponentCount();
    
     AutoCloseable __1 = tempSetTL(componentPopupMenu_mouseEvent, e); try {
    for (Object menuMaker : maker)
      pcallF(menuMaker, menu);
      
    vmBus_send("showingPopupMenu", e.getComponent(), menu);
    
    // show menu if any items in it
    if (menu.getComponentCount() != emptyCount)
      menu.show(e.getComponent(), e.getX(), e.getY());
  } finally { _close(__1); }}
}




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

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


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


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


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


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

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 __1 = holdInstance(instanceToHold); try {
      callF(runnable);
    } finally { _close(__1); }
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n      callF(runnable..."; }});
  } catch (Throwable __e) { messageBox(__e); }}};
}


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

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

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


static boolean isChecked(JCheckBox checkBox) {
  return checkBox != null && (boolean) swing(new F0<Boolean>() { public Boolean get() { try {  return checkBox.isSelected();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret checkBox.isSelected();"; }});
}

static boolean isChecked(JCheckBoxMenuItem mi) {
  return mi != null && (boolean) swing(new F0<Boolean>() { public Boolean get() { try {  return mi.isSelected();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret mi.isSelected();"; }});
}

static boolean isChecked(JRadioButton rb) {
  return rb != null && (boolean) swing(() -> rb.isSelected());
}


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

// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
  ret nuObject(_getClass(realm, className), args);
}*/

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

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

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


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


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

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


static <A> A vm_generalMap_getOrCreate(Object key, F0<A> create) {
  return vm_generalMap_getOrCreate(key, f0ToIF0(create));
}

static <A> A vm_generalMap_getOrCreate(Object key, IF0<A> create) {
  Map generalMap = vm_generalMap();
  if (generalMap == null) return null; // must be x30 init
  
  synchronized(generalMap) { // should switch to locks here
    A a =  (A) (vm_generalMap_get(key));
    if (a == null)
      vm_generalMap_put(key, a = create == null ? null : create.get());
    return a;
  }
}



static int loadPage_defaultTimeout = 60000;
static ThreadLocal<String> loadPage_charset = new ThreadLocal();
static boolean loadPage_allowGzip = true, loadPage_debug;
static boolean loadPage_anonymous = false; // don't send computer ID
static int loadPage_verboseness = 100000;
static int loadPage_retries = 1; //60; // seconds
static ThreadLocal<Boolean> loadPage_silent = new ThreadLocal();
static volatile int loadPage_forcedTimeout; // ms
static ThreadLocal<Integer> loadPage_forcedTimeout_byThread = new ThreadLocal(); // ms
static ThreadLocal<Map<String, List<String>>> loadPage_responseHeaders = new ThreadLocal();
static ThreadLocal<Map<String, String>> loadPage_extraHeaders = new ThreadLocal();
static ThreadLocal<Long> loadPage_sizeLimit = new ThreadLocal();

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

public static String loadPageSilently(URL url) { try {
  if (!networkAllowanceTest(str(url))) throw fail("Not allowed: " + url);
    
  IOException e = null;
  for (int tries = 0; tries < loadPage_retries; tries++)
    try {
      URLConnection con = loadPage_openConnection(url);
      return loadPage(con, url);
    } catch (IOException _e) {
      e = _e;
      if (loadPage_debug)
        print(exceptionToStringShort(e));
      if (tries < loadPage_retries-1) sleepSeconds(1);
    }
  throw e;
} catch (Exception __e) { throw rethrow(__e); } }

static String loadPage_preprocess(String url) {  
  if (url.startsWith("tb/")) // don't think we use this anymore
    url = tb_mainServer() + "/" + url;
  if (url.indexOf("://") < 0)
    url = "http://" + url;
  return url;
}

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

static String loadPage(URL url) {
  return loadPage(url.toExternalForm());
}

static String loadPage(URLConnection con, URL url) throws IOException {
  return loadPage(con, url, true);
}

static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
  Map<String, String> extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
  Long limit = optPar(loadPage_sizeLimit);
  if (addHeaders) try {
    if (!loadPage_anonymous)
      setHeaders(con);
    if (loadPage_allowGzip)
      con.setRequestProperty("Accept-Encoding", "gzip");
    con.setRequestProperty("X-No-Cookies", "1");
    for (String key : keys(extraHeaders))
      con.setRequestProperty(key, extraHeaders.get(key));
  } catch (Throwable e) {} // fails if within doPost
  
  
  vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
  
  loadPage_responseHeaders.set(con.getHeaderFields());
  InputStream in = null;
  try {
    in = urlConnection_getInputStream(con);
  //vm_generalSubMap("InputStream per thread").put(currentThread(), in);
  if (loadPage_debug)
    print("Put stream in map: " + currentThread());
    String contentType = con.getContentType();
    if (contentType == null) {
      //printStruct("Headers: ", con.getHeaderFields());
      throw new IOException("Page could not be read: " + hideCredentials(url));
    }
    //print("Content-Type: " + contentType);
    String charset = loadPage_charset == null ? null : loadPage_charset.get();
    if (charset == null) charset = loadPage_guessCharset(contentType);
    
    if ("gzip".equals(con.getContentEncoding())) {
      if (loadPage_debug)
        print("loadPage: Using gzip.");
      in = newGZIPInputStream(in);
    }
    Reader r;
    try {
      r = new InputStreamReader(in, unquote(charset));
    } catch (UnsupportedEncodingException e) {
      print(toHex(utf8(charset)));
      throw e;
    }
    
    boolean silent = isTrue(loadPage_silent.get());
    StringBuilder buf = new StringBuilder();
    int n = 0;
    while (limit == null || n < limit) {
      ping();
      int ch = r.read();
      if (ch < 0)
        break;
      buf.append((char) ch);
      ++n;
      if (!silent && (n % loadPage_verboseness) == 0)
        print("  " + n + " chars read");
    }
    return buf.toString();
  } finally {
    if (loadPage_debug)
      print("loadPage done");
    //vm_generalSubMap("InputStream per thread").remove(currentThread());
    
    vm_generalSubMap("URLConnection per thread").remove(currentThread());
    
    if (in != null) in.close();
  }
}

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);
  /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
  //return or(match, "ISO-8859-1");
  return or(match, "UTF-8");
}

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


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


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) {
    //printShortException(e);
  }
  
}


static <A> A println(A a) {
  return print(a);
}


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

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

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

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


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


static volatile boolean muricaPassword_pretendNotAuthed = false;

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


static String fileServerURL() {
  return "https://botcompany.de/files";
}


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

static String loadTextFile(File f, String defaultContents) { return loadTextFile(f, defaultContents, "UTF-8"); }
static String loadTextFile(File f, String defaultContents, String encoding) { try {
  
  checkFileNotTooBigToRead(f);
  
  if (f == null || !f.exists()) return defaultContents;

  FileInputStream fileInputStream = new FileInputStream(f);
  InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding);
  return loadTextFile(inputStreamReader);
} catch (Exception __e) { throw rethrow(__e); } }

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

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

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


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

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



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



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(100000, total))));
    total += n;
  }
} catch (Exception __e) { throw rethrow(__e); } }


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


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


static byte[] loadBinaryFilePart(File file, long start, long end) { try {
  RandomAccessFile raf = new RandomAccessFile(file, "r");
  int n = toInt(min(raf.length(), end-start));
  byte[] buffer = new byte[n];
  try {
    raf.seek(start);
    raf.readFully(buffer, 0, n);
    return buffer;
  } finally {
    raf.close();
  }
} catch (Exception __e) { throw rethrow(__e); } }


static <A> A popLast(List<A> l) {
  return liftLast(l);
}

static <A> List<A> popLast(int n, List<A> l) {
  return liftLast(n, l);
}


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




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


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


// supports the usual quotings (", variable length double brackets) except ' quoting
static boolean isQuoted(String s) {
  
  
  if (isNormalQuoted(s)) return true; // use the exact version
  
  return isMultilineQuoted(s);
}


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

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();
}
  
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 == '\t')
      out.append("\\t");
    else if (c == '\0')
      out.append("\\0");
    else
      out.append(c);
  }
  out.append('"');
}


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

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



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') {
      // ok
    } else
      return false;
  }
  return true;
}


static Throwable printStackTrace2(Throwable e) {
  // we go to system.out now - system.err is nonsense
  print(getStackTrace2(e));
  return e;
}

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

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



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


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

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


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


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


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


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


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


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


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


static String getLookAndFeel() {
  return getClassName(UIManager.getLookAndFeel());
}


static JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) {
  return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane");
}



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


static <A> A optCast(Class<A> c, Object o) {
  return isInstance(c, o) ? (A) o : null;
}


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

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

static Object _get(String field, Object o) {
  return get(o, field);
}
static <A> A _get(A[] l, int idx) {
  return idx >= 0 && idx < l(l) ? l[idx] : null;
}


static Object findComponentPopupMenuListener_gen(final JComponent c) {
  return c == null ? null : swing(new F0<Object>() { public Object get() { try { 
    return firstWithClassShortNamed("componentPopupMenu_Adapter", c.getMouseListeners());
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret firstWithClassShortNamed('componentPopupMenu_Adapter, c.getMouseListeners..."; }});
}


static boolean internalFrameActive(Component c) {
  final JInternalFrame f = getInternalFrame(c);
  return f != null && swing(new F0<Boolean>() { public Boolean get() { try {  return f.isSelected();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret f.isSelected();"; }});
}


static <A> AutoCloseable tempSetTL(ThreadLocal<A> tl, A a) {
  return tempSetThreadLocal(tl, a);
}

static <A> AutoCloseable tempSetTL(x30_pkg.x30_util.BetterThreadLocal<A> tl, A a) {
  return tempSetThreadLocalIfNecessary(tl, a);
}


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


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

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

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

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

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

/*static JTextArea onEnter(final JTextArea ta, fO action) {
  addKeyListener(ta, enterKeyListener(action));
  ret ta;
}*/

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


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

static Class classForName(String name) { try {
  if (classForName_cache == null) return Class.forName(name); // in class init
  Class c = classForName_cache.get(name);
  if (c == null)
    classForName_cache.put(name, c = Class.forName(name));
  return c;
} catch (Exception __e) { throw rethrow(__e); } }


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

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

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

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



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


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


static <A> IF0<A> f0ToIF0(F0<A> f) {
  return f == null ? null : () -> f.get();
}


static boolean networkAllowanceTest(String url) {
  
  
  return isAllowed("networkAllowanceTest", url);
  
}


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


static <A> A printWithTime(A a) {
  return printWithTime("", a);
}

static <A> A printWithTime(String s, A a) {
  print(hmsWithColons() + ": " + s, a);
  return a;
}


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



static InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
  UnknownHostException lastException = null;
  for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++)  {
    try {
      if (con instanceof HttpURLConnection)
        if (((HttpURLConnection) con).getResponseCode() == 500)
          throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
      return con.getInputStream();
    } catch (UnknownHostException e) {
      lastException = e;
      print("Retrying because of: " + e);
      continue;
    }
  }
  throw lastException;
}


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

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


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);
          // Octal escape?
          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;
          // Hex Unicode: u????
          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; // added by Stefan
          }
          i++;
        }
        sb.append(ch);
      }
      return sb.toString();
    }
  }
    
  return s; // not quoted - return original
}


static String toHex(byte[] bytes) {
  return bytesToHex(bytes);
}

static String toHex(byte[] bytes, int ofs, int len) {
  return bytesToHex(bytes, ofs, len);
}



static byte[] utf8(String s) {
  return toUtf8(s);
}


static Matcher regexpMatcher(String pat, String s) {
  return compileRegexp(pat).matcher(unnull(s));
}


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


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


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


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

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


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


static File javaxDataDir_dir; // can be set to work on different base dir

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

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


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


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

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


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

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


// TODO: optimize to x-(x%n) in case that's the same thing
// (or x-mod(x,n)?)
static int roundDownTo(int n, int x) {
  return x/n*n;
}

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


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

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

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


static int shorten_default = 100;

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

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

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

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


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


static <A> A liftLast(List<A> l) {
  if (empty(l)) return null;
  int i = l(l)-1;
  A a = l.get(i);
  l.remove(i);
  return a;
}

static <A> List<A> liftLast(int n, List<A> l) {
  int i = l(l)-n;
  List<A> part = cloneSubList(l, i);
  removeSubList(l, i);
  return part;
}




static TreeMap<String, Class> hotwireCached_cache = new TreeMap();
static Lock hotwireCached_lock = lock();

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

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

static Class hotwireCached(String programID, boolean runMain, boolean dependent) {
  Lock __0 = hotwireCached_lock; lock(__0); 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(__0); } }


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


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) == '[';
}


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


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

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


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

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


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


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

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


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

static String htmlQuery(Object... data) {
  return empty(data) ? "" : "?" + makePostData(data);
}


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


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


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


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

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


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


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


static <A> A firstWithClassShortNamed(String shortName, Iterable<A> l) {
  if (l != null) for (A o : l)
    if (eq(shortClassName(o), shortName))
      return o;
  return null;
}

static <A> A firstWithClassShortNamed(String shortName, A[] l) {
  if (l != null) for (A o : l)
    if (eq(shortClassName(o), shortName))
      return o;
  return null;
}


static <A> AutoCloseable tempSetThreadLocalIfNecessary(ThreadLocal<A> tl, A a) {
  if (tl == null) return null;
  A prev = tl.get();
  if (eq(prev, a)) return null;
  tl.set(a);
  return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}

static <A> AutoCloseable tempSetThreadLocalIfNecessary(x30_pkg.x30_util.BetterThreadLocal<A> tl, A a) {
  if (tl == null) return null;
  A prev = tl.get();
  if (eq(prev, a)) return null;
  tl.set(a);
  return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}


static KeyListener enterKeyListener(final Object action) {
  return new KeyAdapter() {
    public void keyPressed(KeyEvent ke) {
      if (ke.getKeyCode() == KeyEvent.VK_ENTER)
        pcallF(action);
    }
  };
}


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


static AbstractAction abstractAction(String name, final Object runnable) {
  return new AbstractAction(name) {
    public void actionPerformed(ActionEvent evt) {
      pcallF(runnable);
    }
  };
}


static volatile Object isAllowed_function; // func(S, O[]) -> bool
static volatile boolean isAllowed_all = true;

static boolean isAllowed(String askingMethod, Object... args) {
  // check on VM level
  Object f = vm_generalMap_get("isAllowed_function");
  if (f != null && !isTrue(callF(f, askingMethod, args))) return false;
  
  // check locally
  return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
}


static volatile boolean sleep_noSleep = false;

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

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


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

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




static String hmsWithColons() {
  return hmsWithColons(now());
}

static String hmsWithColons(long time) {
  return new SimpleDateFormat("HH:mm:ss").format(time);
}



static String joinNemptiesWithColonSpace(String... strings) {
  return joinNempties(": ", strings);
}

static String joinNemptiesWithColonSpace(Collection<String> strings) {
  return joinNempties(": ", strings);
}


static String tryToReadErrorStreamFromURLConnection(URLConnection conn) { try {
  if (conn instanceof HttpURLConnection)
    return stream2string(((HttpURLConnection) conn).getErrorStream()); // TODO: ensure some max length
  return null;
} catch (Throwable __e) { return null; } }


static int gzInputStream_defaultBufferSize = 65536;

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

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

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

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


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

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


  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 String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

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



static byte[] toUtf8(String s) { try {
  return s.getBytes(utf8charset());
} catch (Exception __e) { throw rethrow(__e); } }


static Map<String, java.util.regex.Pattern> compileRegexp_cache = syncMRUCache(10);

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


static String _computerID;
static Lock computerID_lock = lock();

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


static File javaxSecretDir_dir; // can be set to work on different base dir

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

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


static File programDir_mine; // set this to relocate program's data

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

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

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


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

static CharSequence subCharSequence(CharSequence s, int x, int y) {
  if (s == null) return null;
  if (x < 0) x = 0;
  if (x >= s.length()) return "";
  if (y < x) y = x;
  if (y > s.length()) y = s.length();
  return s.subSequence(x, y);
}


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

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


static <A> List<A> cloneSubList(List<A> l, int startIndex, int endIndex) {
  return newSubList(l, startIndex, endIndex);
}

static <A> List<A> cloneSubList(List<A> l, int startIndex) {
  return newSubList(l, startIndex);
}


static void removeSubList(List l, int from, int to) {
  if (l != null) subList(l, from, to).clear();
}

static void removeSubList(List l, int from) {
  if (l != null) subList(l, from).clear();
}




// custom mainClass only works with hotwire_here
static Class<?> hotwire(String src) { return hotwire(src, __1 -> mainClassNameForClassLoader(__1)); }
static Class<?> hotwire(String src, IF1<ClassLoader, String> calculateMainClass) {
  assertFalse(_inCore());
  Class j = getJavaX();
  if (isAndroid()) {
    synchronized(j) { // hopefully this goes well...
      List<File> libraries = new ArrayList<File>();
      File srcDir = (File) call(j, "transpileMain", src, libraries);
      if (srcDir == null)
        throw fail("transpileMain returned null (src=" + quote(src) + ")");
    
      Object androidContext = get(j, "androidContext");
      return (Class) call(j, "loadx2android", srcDir, src);
    }
  } else {
    
    
    Class c =  (Class) (call(j, "hotwire", src));
    hotwire_copyOver(c);
    return c;
    
  }
}


static Object makeDependent_postProcess;

static void makeDependent(Object c) {
  if (c == null) return;
  assertTrue("Not a class", c instanceof Class);
  dependentClasses(); // cleans up the list
  hotwire_classes.add(new WeakReference(c));
  
  Object local_log = getOpt(mc(), "local_log");
  if (local_log != null)
    setOpt(c, "local_log", local_log);
    
  /*if (isTrue(getOpt(c, 'ping_actions_shareable)))
    setOpt(c, +ping_actions);*/
    
  Object print_byThread = getOpt(mc(), "print_byThread");
  if (print_byThread != null)
    setOpt(c, "print_byThread", print_byThread);
    
  callF(makeDependent_postProcess, c);
}



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

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


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


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


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


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

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


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


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


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

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

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

static CharSequence takeFirst(int n, CharSequence s) { return subCharSequence(s, 0, n); }

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

static <A> List<A> takeFirst(int n, Iterable<A> i) {
  if (i == null) return null;
  return i == null ? null : takeFirst(n, i.iterator());

}

static int[] takeFirst(int n, int[] a) {
  return takeFirstOfIntArray(n, a);
}


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

static <A> int smartLastIndexOf(List<A> l, A sub) {
  int i = lastIndexOf(l, sub);
  return i < 0 ? l(l) : i;
}


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(/*escapeMultichars*/(value)));
    }
  }
  return str(buf);
}

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(/*escapeMultichars*/(value)));
    }
  }
  return str(buf);

}



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


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


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


/** writes safely (to temp file, then rename) */
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();
  }
}

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


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


static String shortClassName(Object o) {
  if (o == null) return null;
  Class c = o instanceof Class ? (Class) o : o.getClass();
  String name = c.getName();
  return shortenClassName(name);
}


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

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


static Object sleepQuietly_monitor = new Object();

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


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

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


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



static String joinNempties(String sep, Object... strings) {
  return joinStrings(sep, strings);
}

static String joinNempties(String sep, Iterable strings) {
  return joinStrings(sep, strings);
}


static String stream2string(InputStream in) {
  return utf8streamToString(in);
}


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


static <A> A[] dropLast(A[] a) { return dropLast(a, 1); }
static <A> A[] dropLast(A[] a, int n) {
  if (a == null) return null;
  n = Math.min(n, a.length);
  A[] b = arrayOfSameType(a, a.length-n);
  System.arraycopy(a, 0, b, 0, b.length);
  return b;
}

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

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

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

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

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

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





static Charset utf8charset_cache;
static Charset utf8charset() { if (utf8charset_cache == null) utf8charset_cache = utf8charset_load(); return utf8charset_cache; }

static Charset utf8charset_load() {
  return Charset.forName("UTF-8");
}


static <A, B> Map<A, B> syncMRUCache(int size) {
  return synchroMap(new MRUCache(size));
}


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


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

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

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


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


static volatile String caseID_caseID;

static String caseID() { return caseID_caseID; }

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


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


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

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


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

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

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

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






static void assertFalse(Object o) {
  if (!(eq(o, false) /*|| isFalse(pcallF(o))*/))
    throw fail(str(o));
}
  
static boolean assertFalse(boolean b) {
  if (b) throw fail("oops");
  return b;
}

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



static boolean _inCore() {
  return false;
}


static List hotwire_copyOver_after = synchroList();

static void hotwire_copyOver(Class c) {
  // TODO: make a mechanism for making such "inheritable" fields
  for (String field : ll("print_log", "print_silent", "androidContext", "_userHome"))
    setOptIfNotNull(c, field, getOpt(mc(), field));
    
  
  
  setOptIfNotNull(c, "mainBot" , getMainBot());
  setOpt(c, "creator_class" , new WeakReference(mc()));
  pcallFAll(hotwire_copyOver_after, c);
}


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


static Field setOpt_findField(Class c, String field) {
  HashMap<String, Field> map;
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  return map.get(field);
}

static void setOpt(Object o, String field, Object value) { try {
  if (o == null) return;
  
  
  
  Class c = o.getClass();
  HashMap<String, Field> map;
  
  if (getOpt_cache == null)
    map = getOpt_makeCache(c); // in class init
  else synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  
  if (map == getOpt_special) {
    if (o instanceof Class) {
      setOpt((Class) o, field, value);
      return;
    }
    
    // It's probably a subclass of Map. Use raw method
    setOpt_raw(o, field, value);
    return;
  }
  
  Field f = map.get(field);
  
  if (f != null)
    { smartSet(f, o, value); return; } // possible improvement: skip setAccessible
  
    if (o instanceof DynamicObject)
      { setDyn(((DynamicObject) o), field, value); return; }
  
  if (o instanceof IMeta)
    setDyn(((IMeta) o), field, value);
} catch (Exception __e) { throw rethrow(__e); } }

static void setOpt(Class c, String field, Object value) {
  if (c == null) return;
  try {
    Field f = setOpt_findStaticField(c, field); // TODO: optimize
    if (f != null)
      smartSet(f, null, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
  
static Field setOpt_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
        makeAccessible(f);
        return f;
      }
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}


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


static String lines(Iterable lines) { return fromLines(lines); }
static String lines(Object[] lines) { return fromLines(asList(lines)); }
static List<String> lines(String s) { return toLines(s); }

// convenience map call
static <A> String lines(Iterable<A> l, IF1<A, String> f) {
  return mapToLines(l, f);
}


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

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


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


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

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




static int[] takeFirstOfIntArray(int[] b, int n) {
  return subIntArray(b, 0, n);
}

static int[] takeFirstOfIntArray(int n, int[] b) {
  return takeFirstOfIntArray(b, n);
}


static int lastIndexOf(String a, String b) {
  return a == null || b == null ? -1 : a.lastIndexOf(b);
}

static int lastIndexOf(String a, char b) {
  return a == null ? -1 : a.lastIndexOf(b);
}

// starts searching from i-1
static <A> int lastIndexOf(List<A> l, int i, A a) {
  if (l == null) return -1;
  for (i = min(l(l), i)-1; i >= 0; i--)
    if (eq(l.get(i), a))
      return i;
  return -1;
}

static <A> int lastIndexOf(List<A> l, A a) {
  if (l == null) return -1;
  for (int i = l(l)-1; i >= 0; i--)
    if (eq(l.get(i), a))
      return i;
  return -1;
}


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

static File oneOfTheFiles(File... files) {
  return oneOfTheFiles(asList(files));
}

static File oneOfTheFiles(Iterable<File> files) {
  if (files != null) for (File f : files)
    if (fileExists(f))
      return f;
  return null;
}


static List<CriticalAction> beginCriticalAction_inFlight = synchroList();

static class CriticalAction {
  String description;
  
  CriticalAction() {}
  CriticalAction(String description) {
  this.description = description;}
  
  void done() {
    beginCriticalAction_inFlight.remove(this);
  }
}

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

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


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


static String shortenClassName(String name) {
  if (name == null) return null;
  int i = lastIndexOf(name, "$");
  if (i < 0) i = lastIndexOf(name, ".");
  return i < 0 ? name : substring(name, i+1);
}


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


static String joinStrings(String sep, Object... strings) {
  return joinStrings(sep, Arrays.asList(strings));
}

static String joinStrings(String sep, Iterable strings) {
  StringBuilder buf = new StringBuilder();
  for (Object o : unnull(strings)) { 
    String s = strOrNull(o);
    if (nempty(s)) {
      if (nempty(buf)) buf.append(sep);
      buf.append(s);
    }
  }
  return str(buf);
}


static String utf8streamToString(InputStream in) {
  return readerToString(utf8bufferedReader(in));
}


static <A> A[] arrayOfSameType(A[] a, int n) {
  return newObjectArrayOfSameType(a, n);
}


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


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




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

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



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


static Object mainBot;

static Object getMainBot() {
  return mainBot;
}


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


static void setOpt_raw(Object o, String field, Object value) { try {
  if (o == null) return;
  if (o instanceof Class) setOpt_raw((Class) o, field, value);
  else {
    Field f = setOpt_raw_findField(o.getClass(), field);
    if (f != null) {
      makeAccessible(f);
      smartSet(f, o, value);
    }
  }
} catch (Exception __e) { throw rethrow(__e); } }

static void setOpt_raw(Class c, String field, Object value) { try {
  if (c == null) return;
  Field f = setOpt_raw_findStaticField(c, field);
  if (f != null) {
    makeAccessible(f);
    smartSet(f, null, value);
  }
} catch (Exception __e) { throw rethrow(__e); } }
  
static Field setOpt_raw_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}

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


static void smartSet(Field f, Object o, Object value) throws Exception {
  try {
    f.set(o, value);
  } catch (Exception e) {
    Class type = f.getType();
    
    // take care of common case (long to int)
    if (type == int.class && value instanceof Long)
      { f.set(o, ((Long) value).intValue()); return; }
      
    if (type == boolean.class && value instanceof String)
      { f.set(o, isTrueOrYes(((String) value))); return; }
    
    if (type == LinkedHashMap.class && value instanceof Map)
      { f.set(o, asLinkedHashMap((Map) value)); return; }
    
    
    throw e;
  }
}


static <A extends DynamicObject> A setDyn(A o, String key, Object value) {
  setDynObjectValue(o, key, value);
  return o;
}

static void setDyn(IMeta o, String key, Object value) {
  metaMapPut(o, key, value);
}


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

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

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

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


// usually L<S>
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();
}

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


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

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

static int toLines_nextLineBreak(String s, int start) {
  int n = s.length();
  for (int i = start; i < n; i++) {
    char c = s.charAt(i);
    if (c == '\r' || c == '\n')
      return i;
  }
  return -1;
}


static List<String> mapToLines(Map map) {
  List<String> l = new ArrayList();
  for (Object key : keys(map))
    l.add(str(key) + " = " + str(map.get(key)));
  return l;
}

static String mapToLines(Map map, Object f) {
  return lines(map(map, f));
}

static String mapToLines(Object f, Map map) {
  return lines(map(map, f));
}

static String mapToLines(Object f, Iterable l) {
  return lines(map(f, l));
}

static <A> String mapToLines(Iterable<A> l, IF1<A, String> f) {
  return mapToLines((Object) f, l);
}

static <A> String mapToLines(IF1<A, String> f, Iterable<A> l) {
  return mapToLines((Object) f, l);
}

static <A, B> String mapToLines(Map<A, B> map, IF2<A, B, String> f) {
  return lines(map(map, f));
}


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


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



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


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




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

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


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

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

/*ifclass Concept
static L collect(Class c, S field) {
  ret collect(list(c), field);
}
endif
TODO: make translator ignore stuff in ifclass until resolved
*/


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


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


static String readerToString(Reader r) { try {
  if (r == null) return null;
  try {
    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 {
    r.close();
  }  
} catch (Exception __e) { throw rethrow(__e); } }


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

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


static <A> A[] newObjectArrayOfSameType(A[] a) { return newObjectArrayOfSameType(a, a.length); }
static <A> A[] newObjectArrayOfSameType(A[] a, int n) {
  return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
}




static boolean isTrueOrYes(Object o) {
  return isTrueOpt(o) || o instanceof String && (eqicOneOf(((String) o), "1", "t", "true") || isYes(((String) o)));
}


static <A, B> LinkedHashMap<A, B> asLinkedHashMap(Map<A, B> map) {
  if (map instanceof LinkedHashMap) return (LinkedHashMap) map;
  LinkedHashMap<A, B> m = new LinkedHashMap();
  if (map != null) synchronized(collectionMutex(map)) {
    m.putAll(map);
  }
  return m;
}


static void setDynObjectValue(DynamicObject o, String field, Object value) {
  dynamicObject_setRawFieldValue(o, field, value);
}


static void metaMapPut(IMeta o, Object key, Object value) {
  if (o == null || key == null) return;
  Map map = convertObjectMetaToMap(o);
  syncMapPutOrRemove(map, key, value);
}

// untested...
static void metaMapPut(IMeta o, Object key, Object value, IMapImplementationPolicy policy) {
  if (o == null || key == null) return;
  if (policy == null) { metaMapPut(o, key, value); return; }
  
  // no shortcuts in this function, always get mutex & lock
   var mutex = tempMetaMutex(o); try {
  synchronized(mutex.get()) {
    Object meta = o._getMeta();
    
    // create map if necessary
    Map map = null;
    if (meta instanceof Map)
      map = ((Map) meta);
    else if (meta != null)
      map = policy.put(map, "previousMeta" , meta);
      
    // putOrRemove through policy
    if (value != null)
      map = policy.put(map, key, value);
    else
      map = policy.remove(map, key);
      
    if (map != meta) o._setMeta(map);
  }
} finally { _close(mutex); }}


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

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


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


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


static CloseableIterableIterator<String> linesFromFile(File f) { return linesFromFile(f, null); }
static CloseableIterableIterator<String> linesFromFile(File f, IResourceHolder resourceHolder) { try {
  if (!f.exists()) return emptyCloseableIterableIterator();
  
  if (ewic(f.getName(), ".gz"))
    return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder);
  
  return linesFromReader(utf8bufferedReader(f), resourceHolder);
} catch (Exception __e) { throw rethrow(__e); } }

static CloseableIterableIterator<String> linesFromFile(String path) { return linesFromFile(path, null); }
static CloseableIterableIterator<String> linesFromFile(String path, IResourceHolder resourceHolder) {
  return linesFromFile(newFile(path), resourceHolder);
}


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

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


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

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


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

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

// map: func(key, value) -> list element
static List map(Map map, Object f) {
  List x = new ArrayList();
  if (map != null) for  (Object _e : map.entrySet()) { ping(); 
    Map.Entry e = (Map.Entry) _e;
    x.add(callF(f, e.getKey(), e.getValue()));
  }
  return x;
}

static <A, B, C> List<C> map(Map<A, B> map, IF2<A, B, C> f) {
  return map(map, (Object) f);
}


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


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

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


static BufferedReader bufferedReader(Reader r) { return bufferedReader(r, 8192); }
static BufferedReader bufferedReader(Reader r, int bufSize) {
  if (r == null) return null;
  return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r);
}


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

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




static boolean isTrueOpt(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  return false;
}


static boolean eqicOneOf(String s, String... l) {
  for (String x : l) if (eqic(s, x)) return true; return false;
}


static List<String> isYes_yesses = litlist("y", "yes", "yeah", "y", "yup", "yo", "corect", "sure", "ok", "afirmative"); // << collapsed words, so "corect" means "correct"

static boolean isYes(String s) {
  return isYes_yesses.contains(collapseWord(toLowerCase(firstWord2(s))));
}


static void dynamicObject_setRawFieldValue(DynamicObject o, Object key, Object value) {
  if (o == null) return;
  
  // double sync, but should be OK here because of locking order o > o.fieldValues
  synchronized(o) {
    o.fieldValues = syncMapPut2_createLinkedHashMap((LinkedHashMap) o.fieldValues, key, value);
  }
}


static Map convertObjectMetaToMap(IMeta o) { return convertObjectMetaToMap(o, () -> new LinkedHashMap()); }
static Map convertObjectMetaToMap(IMeta o, IF0<Map> createEmptyMap) {
  if (o == null) return null;
  
  // The following shortcut depends on the assumption that a meta field never reverts
  // to null when it was a map
  
    Object meta = o._getMeta();
    if (meta instanceof Map) return ((Map) meta);
  
  
  // non-shortcut path (create meta)
   var mutex = tempMetaMutex(o); try {
  var actualMutex = mutex.get();
  synchronized(actualMutex) {
    meta = o._getMeta();
    if (meta instanceof Map) return ((Map) meta);
    Map map = createEmptyMap.get();
    if (meta != null) map.put("previousMeta" , meta);
    o._setMeta(map);
    return map;
  }
} finally { _close(mutex); }}


static <A, B> void syncMapPutOrRemove(Map<A, B> map, A key, B value) {
  syncMapPut2(map, key, value);
}


static IAutoCloseableF0 tempMetaMutex(IMeta o) {
  return o == null ? null : o._tempMetaMutex();
}


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


static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
  public Object next() { throw fail(); }
  public boolean hasNext() { return false; }
};

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


static CloseableIterableIterator<String> linesFromReader(Reader r) { return linesFromReader(r, null); }
static CloseableIterableIterator<String> linesFromReader(Reader r, IResourceHolder resourceHolder) {
  final BufferedReader br = bufferedReader(r);
  return holdResource(resourceHolder, iteratorFromFunction_f0_autoCloseable(new F0<String>() { public String get() { try {  return readLineFromReaderWithClose(br);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret readLineFromReaderWithClose(br);"; }}, _wrapIOCloseable(r)));
}




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


static String collapseWord(String s) {
  if (s == null) return "";
  StringBuilder buf = new StringBuilder();
  for (int i = 0; i < l(s); i++)
    if (i == 0 || !charactersEqualIC(s.charAt(i), s.charAt(i-1)))
      buf.append(s.charAt(i));
  return buf.toString();
}


static List<String> toLowerCase(List<String> strings) {
  List<String> x = new ArrayList();
  for (String s : strings)
    x.add(s.toLowerCase());
  return x;
}

static String[] toLowerCase(String[] strings) {
  String[] x = new String[l(strings)];
  for (int i = 0; i < l(strings); i++)
    x[i] = strings[i].toLowerCase();
  return x;
}

static String toLowerCase(String s) {
  return s == null ? "" : s.toLowerCase();
}


static String firstWord2(String s) {
  s = xltrim(s);
  if (empty(s)) return "";
  if (isLetterOrDigit(first(s)))
    return takeCharsWhile(s, "isLetterOrDigit");
  else return "" + first(s);
}


static <A, B> LinkedHashMap<A, B> syncMapPut2_createLinkedHashMap(LinkedHashMap<A, B> map, A key, B value) {
  if (key != null)
    if (value != null) {
      if (map == null) map = new LinkedHashMap();
      synchronized(collectionMutex(map)) { map.put(key, value); }
    } else if (map != null) synchronized(collectionMutex(map)) { map.remove(key); }
  return map;
}


static <A, B> void syncMapPut2(Map<A, B> map, A key, B value) {
  if (map != null && key != null) synchronized(collectionMutex(map)) {
    if (value != null) map.put(key, value);
    else map.remove(key);
  }
}


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


static <A extends AutoCloseable> A holdResource(IResourceHolder holder, A a) {
  { if (holder != null) holder.add(a); }
  return a;
}


static <A> CloseableIterableIterator<A> iteratorFromFunction_f0_autoCloseable(final F0<A> f, final AutoCloseable closeable) {
  class IFF2 extends CloseableIterableIterator<A> {
    A a;
    boolean done = false;
    
    public boolean hasNext() {
      getNext();
      return !done;
    }
    
    public A next() {
      getNext();
      if (done) throw fail();
      A _a = a;
      a = null;
      return _a;
    }
    
    void getNext() {
      if (done || a != null) return;
      a = f.get();
      done = a == null;
    }
    
    public void close() throws Exception {
      if (closeable != null) closeable.close();
    }
  };
  return new IFF2();
}


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


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





static boolean charactersEqualIC(char c1, char c2) {
  if (c1 == c2) return true;
  char u1 = Character.toUpperCase(c1);
  char u2 = Character.toUpperCase(c2);
  if (u1 == u2) return true;
  return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}



static String xltrim(String s) {
  int i = 0;
  while (i < s.length() && contains(" \t\r\n", s.charAt(i)))
    ++i;
  return substr(s, i);
}


// pred: char -> bool
static String takeCharsWhile(String s, Object pred) {
  int i = 0;
  while (i < l(s) && isTrue(callF(pred, s.charAt(i)))) ++i;
  return substring(s, 0, i);
}

static String takeCharsWhile(IF1<Character, Boolean> f, String s) {
  return takeCharsWhile(s, f);
}




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

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

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

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

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




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

static String substr(String s, int x, int y) {
  return substring(s, x, y);
}




// immutable, has strong refs
// Do not run in a synchronized block - it goes wrong in the presence
// of elaborate classloaders (like in Gazelle BEA)
// see #1102990 and #1102991
final static class _MethodCache {
  final Class c;
  final HashMap<String, List<Method>> cache = new HashMap();
  
  _MethodCache(Class c) {
  this.c = c; _init(); }
  
  void _init() {
    Class _c = c;
    while (_c != null) {
      for (Method m : _c.getDeclaredMethods())
        if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
          multiMapPut(cache, m.getName(), makeAccessible(m));
      _c = _c.getSuperclass();
    }
    
    // add default methods - this might lead to a duplication
    // because the overridden method is also added, but it's not
    // a problem except for minimal performance loss.
    for (Class intf : allInterfacesImplementedBy(c))
      for (Method m : intf.getDeclaredMethods())
        if (m.isDefault() && !reflection_isForbiddenMethod(m))
          multiMapPut(cache, m.getName(), makeAccessible(m));

    
  }
  
  // Returns only matching methods
  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); } }
  
  Method findStaticMethod(String method, Object[] args) { try {
    List<Method> m = cache.get(method);
    if (m == null) return null;
    int n = m.size();
    for (int i = 0; i < n; i++) {
      Method me = m.get(i);
      if (isStaticMethod(me) && call_checkArgs(me, args, false))
        return me;
    }
    return null;
  } catch (Exception __e) { throw rethrow(__e); } }
}
static abstract class VF1<A> implements IVF1<A> {
  public abstract void get(A a);
}
static class OneColorTheoryChecker {
  
  
  
  ProbabilisticScheduler scheduler = new ProbabilisticScheduler();
  
  class OneColorTheory extends BodyOfEvidence<String> implements IFieldsToList{
  String text;
  URecognizer.Cell cell;
  RGB color;
  OneColorTheory() {}
  OneColorTheory(String text, URecognizer.Cell cell, RGB color) {
  this.color = color;
  this.cell = cell;
  this.text = text;}

public boolean equals(Object o) {
if (!(o instanceof OneColorTheory)) return false;
    OneColorTheory __0 =  (OneColorTheory) o;
    return eq(text, __0.text) && eq(cell, __0.cell) && eq(color, __0.color);
}

  public int hashCode() {
    int h = -674300926;
    h = boostHashCombine(h, _hashCode(text));
    h = boostHashCombine(h, _hashCode(cell));
    h = boostHashCombine(h, _hashCode(color));
    return h;
  }
  public Object[] _fieldsToList() { return new Object[] {text, cell, color}; }

    public String toString() {
      return renderProbabilityGuess() + ": " + dollarVarsMeanFields(text, this);
    }
    
    OneColorTheory branch(Object... __) { return this; }
  }
  
  // create the theory object and initiate the reasoning
  // you have to step the scheduler afterwards to get results
  OneColorTheory makeTheory(URecognizer.Cell cell) {
    var color = cell.averageColor();

    var theory = new OneColorTheory("Color of every pixel in $cell is $color.", cell, color);
  
    testOneColorTheory(cell, theory);
    return theory;
  }

  void noteCellColor(URecognizer.Cell cell, OneColorTheory theory) {
    var desc = "Pixel check at " + cell;
    if (theory.hasEvidenceFromSource(desc)) return;
    var strength = doubleRatio(cell.area(), theory.cell.area()); // how much do we have to say about the cell in the theory?
    var p = colorDistanceToProbability(cell.averageColor(), theory.color);
    addExampleToTheory(theory, desc, p, strength);
  }
  
  double colorDistanceToProbability(RGB col1, RGB col2) {
    double sim = colorSimilarity(col1, col2), sqr = sqr(sim);
    printFunctionCall("colorDistanceToProbability", "col1", col1, "col2", col2, "sim", sim, "sqr", sqr);
    return sqr;
  }
  
  void testOneColorTheory(URecognizer.Cell cell, OneColorTheory theory) {  
    noteCellColor(cell, theory);
  
    scheduler.atRelative(dontZoomTooFar(cell), new Runnable() {  public void run() { try { 
      for (var split : usefulSplits(cell))
        scheduler.atRelative(split.probability(), new Runnable() {  public void run() { try { 
          for (var cell : split.get())
            testOneColorTheory(cell, theory.branch("description" , "recursion to " + cell));
        
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "for (var cell : split.get())\r\n            testOneColorTheory(cell, theory.bra..."; }});
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "for (var split : usefulSplits(cell))\r\n        scheduler.atRelative(split.prob..."; }});
  }
  
  List<WithProbability<URecognizer.Cell[]>> usefulSplits(URecognizer.Cell cell) {
    return map(__27 -> withProbability1(__27), llNonNulls(cell.split(0, 2), cell.split(1, 2)));
  }
  
  // probability penalty .25 for zooming in 3 steps
  double dontZoomTooFar(URecognizer.Cell cell) {
    return 0.75;
  }
  
  void addExampleToTheory(BodyOfEvidence<String> theory, String desc, double probabilityOfTheory, double strengthOfEvidence) {
    theory.addEvidence(desc, probabilityOfTheory, /* scheduler.currentProbability()* */ strengthOfEvidence);
  }
}
static class Matches {
  String[] m;
  
  Matches() {}
  Matches(String... m) {
  this.m = m;}
  
  String get(int i) { return i < m.length ? m[i] : null; }
  String unq(int i) { return unquote(get(i)); }
  
  String tlc(int i) { return unq(i).toLowerCase(); }
  boolean bool(int i) { return "true".equals(unq(i)); }
  String rest() { return m[m.length-1]; } // for matchStart
  int psi(int i) { return Integer.parseInt(unq(i)); }
  
  public String toString() { return "Matches(" + joinWithComma(quoteAll(asList(m))) + ")"; }
  
  public int hashCode() { return _hashCode(toList(m)); }
  public boolean equals(Object o) { return o instanceof Matches && arraysEqual(m, ((Matches) o).m); }
}

static class Var<A> implements IVar<A>, ISetter<A> {
  Var() {}
  Var(A v) {
  this.v = v;}

  
  A v; // you can access this directly if you use one thread
  
  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(this.get()); }
}
static interface IMeta {
  // see class "Meta" for the bla bla
  
  public void _setMeta(Object meta);
  public Object _getMeta();
  default public IAutoCloseableF0 _tempMetaMutex() {
    return new IAutoCloseableF0() {
      public Object get() { return IMeta.this; }
      public void close() {}
    };
  }
}
// a variant of thread where you can get the Runnable target later.
// Also notes its existence on the VM bus.
// We should use this exclusively instead of Thread.

static class BetterThread extends Thread {
  Runnable target;
  
  BetterThread(Runnable target) {
  this.target = target; _created(); }
  BetterThread(Runnable target, String name) { super(name);
  this.target = target; _created(); }
  
  void _created() { vmBus_send("threadCreated", this); }
  
  public void run() {
    try {
      vmBus_send("threadStarted", this);
      if (target != null) target.run();
    } finally {
      vmBus_send("threadEnded", this); 
    }
  }
  
  Runnable getTarget() { return target; }
}
 // thumbnailator


static class ImageSurface extends Surface {
  BufferedImage image;
  double zoomX = 1, zoomY = 1, zoomFactor = 1.5;
  private Rectangle selection;
  List tools = new ArrayList();
  Object overlay; // voidfunc(Graphics2D)
  Runnable onSelectionChange;
  static boolean verbose = false;
  boolean noMinimumSize = true;
  String titleForUpload;
  Object onZoom;
  boolean specialPurposed = false; // true = don't show image changing commands in popup menu
  boolean zoomable = true;
  boolean noAlpha = false; // set to true to speed up drawing if you don't use alpha
  Object interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
  Object onNewImage;
  BufferedImage imageToDraw; // if you want to draw a different image
  File file; // where image was loaded from
 
  public ImageSurface() {
    this(dummyImage());
  }
  
  static BufferedImage dummyImage() {
    return new RGBImage(1, 1, new int[] { 0xFFFFFF }).getBufferedImage();
  }

  ImageSurface(MakesBufferedImage image) {
    this(image != null ? image.getBufferedImage() : dummyImage());
  }
  
  ImageSurface(BufferedImage image) {
    setImage(image);
    clearSurface = false;

    componentPopupMenu2(this, ImageSurface_popupMenuMaker());
    new ImageSurfaceSelector(this);
    
    jHandleFileDrop(this, new VF1<File>() { public void get(File f) { try {  setImage(loadBufferedImage(f)) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "setImage(loadBufferedImage(f))"; }});
  }

  public ImageSurface(RGBImage image, double zoom) {
    this(image);
    setZoom(zoom);
  }

  // point is already in image coordinates
  protected void fillPopupMenu(JPopupMenu menu, final Point point) {
    if (zoomable) {
      JMenuItem miZoomReset = new JMenuItem("Zoom 100%");
      miZoomReset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          setZoom(1.0);
          centerPoint(point);
        }
      });
      menu.add(miZoomReset);
  
      JMenuItem miZoomIn = new JMenuItem("Zoom in");
      miZoomIn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          zoomIn(zoomFactor);
          centerPoint(point);
        }
      });
      menu.add(miZoomIn);
  
      JMenuItem miZoomOut = new JMenuItem("Zoom out");
      miZoomOut.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          zoomOut(zoomFactor);
          centerPoint(point);
        }
      });
      menu.add(miZoomOut);
  
      JMenuItem miZoomToWindow = new JMenuItem("Zoom to window");
      miZoomToWindow.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          zoomToDisplaySize();
        }
      });
      menu.add(miZoomToWindow);
      addMenuItem(menu, "Show full screen", new Runnable() {  public void run() { try {  showFullScreen() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "showFullScreen()"; }});
      
      addMenuItem(menu, "Point: " + point.x + "," + point.y + " (image: " + image.getWidth() + "*" + image.getHeight() + ")", null);
  
      menu.addSeparator();
    }

    addMenuItem(menu, "Load image...", new Runnable() {  public void run() { try {  selectFile("Load image",
      new VF1<File>() { public void get(File f) { try {  setImage(loadImage2(f)) ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "setImage(loadImage2(f))"; }}) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "selectFile(\"Load image\",\r\n      new VF1<File>() { public void get(File f) cte..."; }});
    addMenuItem(menu, "Save image...", new Runnable() {  public void run() { try {  saveImage() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "saveImage()"; }});
    addMenuItem(menu, "Upload image...", new Runnable() {  public void run() { try {  uploadTheImage() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "uploadTheImage()"; }});
    addMenuItem(menu, "Copy image to clipboard", new Runnable() {  public void run() { try {  copyImageToClipboard(getImage()) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "copyImageToClipboard(getImage())"; }});
    if (!specialPurposed) {
      addMenuItem(menu, "Paste image from clipboard", new Runnable() {  public void run() { try {  loadFromClipboard() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "loadFromClipboard()"; }});
      addMenuItem(menu, "Load image snippet...", new Runnable() {  public void run() { try { 
        selectImageSnippet(new VF1<String>() { public void get(String imageID) { try { 
          setImage(loadImage2(imageID))
        ; } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "setImage(loadImage2(imageID))"; }});
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "selectImageSnippet(new VF1<String>() { public void get(String imageID) ctex {..."; }});
    }
    if (selection != null)
      addMenuItem(menu, "Crop", new Runnable() {  public void run() { try {  crop() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "crop()"; }});
    if (!specialPurposed)
      addMenuItem(menu, "No image", new Runnable() {  public void run() { try {  noImage() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "noImage()"; }});
  }
  
  void noImage() { setImage((BufferedImage) null); }
  
  void crop() {
    if (selection == null) return;
    BufferedImage img = cloneClipBufferedImage(getImage(), selection);
    selection = null;
    setImage(img);
  }
  
  void loadFromClipboard() {
    BufferedImage img = getImageFromClipboard();
    if (img != null)
      setImage(img);
  }

  void saveImage() {
    RGBImage image = new RGBImage(getImage(), null);
    JFileChooser fileChooser = new JFileChooser(getProgramDir());
    if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
      try {
        image.save(file = fileChooser.getSelectedFile());
      } catch (IOException e) {
        popup(e);
      }
    }
  }

  public void render(int w, int h, Graphics2D g) {
    if (verbose) _print("render");
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolationMode);
    g.setColor(Color.white);
    BufferedImage image = or(imageToDraw, this.image);
    if (image == null)
      g.fillRect(0, 0, w, h);
    else {
      int iw = getZoomedWidth(), ih = getZoomedHeight();
      boolean alpha = !noAlpha && hasTransparency(image);
      if (alpha) g.fillRect(0, 0, w, h);
      if (eq(interpolationMode, "thumbnailator"))
        g.drawImage(Thumbnailator.createThumbnail(image, iw, ih), 0, 0, null);
      else if (interpolationMode == RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR || zoomX >= 1 || zoomY >= 1)
        g.drawImage(image, 0, 0, iw, ih, null);
      else
        g.drawImage(resizeImage(image, iw, ih), 0, 0, null); // smoother
      
      if (!alpha) {
        g.fillRect(iw, 0, w-iw, h);
        g.fillRect(0, ih, iw, h-ih);
      }
    }

    if (overlay != null) {
      if (verbose) _print("render overlay");
      pcallF(overlay, g);
    }

    if (selection != null) {
      if (verbose) _print("render selection");
      // drawRect is inclusive, selection is exclusive, so... whatever, tests show it's cool.
      drawSelectionRect(g, selection, Color.green, Color.white);
    }
  }

  public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white) {
    drawSelectionRect(g, selection, green, white, zoomX, zoomY);
  }
  
  public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white, double zoomX, double zoomY) {
    g.setColor(green);
    int top = (int) (selection.y * zoomY);
    int bottom = (int) ((selection.y+selection.height) * zoomY);
    int left = (int) (selection.x * zoomX);
    int right = (int) ((selection.x+selection.width) * zoomX);
    g.drawRect(left-1, top-1, right-left+1, bottom-top+1);
    g.setColor(white);
    g.drawRect(left - 2, top - 2, right - left + 3, bottom - top + 3);
  }

  public ImageSurface setZoom(double zoom) {
    setZoom(zoom, zoom);
    return this;
  }

  public void setZoom(double zoomX, double zoomY) {
    if (this.zoomX == zoomX && this.zoomY == zoomY) return;
    if (verbose) _print("Setting zoom");
    this.zoomX = zoomX;
    this.zoomY = zoomY;
    revalidate();
    repaint();
    centerPoint(new Point(getImage().getWidth()/2, getImage().getHeight()/2));

    pcallF(onZoom);
  }

  public Dimension getMinimumSize() {
    if (noMinimumSize) return new Dimension(1, 1);
    int w = getZoomedWidth();
    int h = getZoomedHeight();
    Dimension min = super.getMinimumSize();
    return new Dimension(Math.max(w, min.width), Math.max(h, min.height));
  }

  private int getZoomedHeight() {
    return (int) (image.getHeight() * zoomY);
  }

  private int getZoomedWidth() {
    return (int) (image.getWidth() * zoomX);
  }

  public void setImage(MakesBufferedImage image) {
    setImage(image == null ? null : image.getBufferedImage());
  }
  
  public void setImage(final BufferedImage img) {
    { swing(new Runnable() {  public void run() { try { 
      BufferedImage newImage = img != null ? img : dummyImage();
      BufferedImage oldImage = image;
      image = newImage;
      if (!imagesHaveSameSize(oldImage, newImage)) {
        if (verbose) _print("New image size");
        revalidate(); // do we need this?
      }
      repaint();
      pcallF(onNewImage);
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "BufferedImage newImage = img != null ? img : dummyImage();\r\n      BufferedIma..."; }}); }
  }
  
  void setImageAndZoomToDisplay(BufferedImage img) {
    setImage(img);
    zoomToDisplaySize();
  }

  public BufferedImage getImage() {
    return image;
  }

  public double getZoomX() {
    return zoomX;
  }

  public double getZoomY() {
    return zoomY;
  }

  public Dimension getPreferredSize() {
    return new Dimension(getZoomedWidth(), getZoomedHeight());
  }

  /** returns a scrollpane with the scroll-mode prevent-garbage-drawing fix applied */
  public JScrollPane makeScrollPane() {
    JScrollPane scrollPane = new JScrollPane(this);
    scrollPane.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
    return scrollPane;
  }

  public void zoomToWindow() { zoomToDisplaySize(); }
  public void zoomToDisplaySize() { swing(new Runnable() {  public void run() { try { 
    if (image == null) return;
    Dimension display = getDisplaySize();
    double xRatio = (display.width-5)/(double) image.getWidth();
    double yRatio = (display.height-5)/(double) image.getHeight();
    setZoom(min(xRatio, yRatio));
    revalidate();
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (image == null) return;\r\n    Dimension display = getDisplaySize();\r\n    do..."; }}); }

  /** tricky magic to get parent scroll pane */
  private Dimension getDisplaySize() {
    Container c = getParent();
    while (c != null) {
      if (c instanceof JScrollPane)
        return c.getSize();
      c = c.getParent();
    }
    return getSize();
  }
  
  public void setSelection(Rect r) {
    setSelection(toRectangle(r));
  }

  public void setSelection(Rectangle r) {
    if (neq(selection, r)) {
      selection = r;
      pcallF(onSelectionChange);
      repaint();
    }
  }

  public Rectangle getSelection() {
    return selection;
  }

  public RGBImage getRGBImage() {
    return new RGBImage(getImage());
  }
  
  // p is in image coordinates
  void centerPoint(Point p) {
    JScrollPane sp = enclosingScrollPane(this);
    if (sp == null) return;
      
    p = new Point((int) (p.x*getZoomX()), (int) (p.y*getZoomY()));
    final JViewport viewport = sp.getViewport();
    Dimension viewSize = viewport.getExtentSize();
    
    //_print("centerPoint " + p);
    int x = max(0, p.x-viewSize.width/2);
    int y = max(0, p.y-viewSize.height/2);
    
    //_print("centerPoint " + p + " => " + x + "/" + y);
    p = new Point(x,y);
    //_print("centerPoint " + p);
    final Point _p = p;
    awtLater(new Runnable() {  public void run() { try { 
      viewport.setViewPosition(_p);
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "viewport.setViewPosition(_p);"; }});
  }
  
  Pt pointFromEvent(MouseEvent e) {
    return pointFromComponentCoordinates(new Pt(e.getX(), e.getY()));
  }
  
  Pt pointFromComponentCoordinates(Pt p) {
    return new Pt((int) (p.x/zoomX), (int) (p.y/zoomY));
  }
  
  Pt pointToComponentCoordinates(double x, double y) {
    return new Pt((int) (x*zoomX), (int) (y*zoomY));
  }
  
  void uploadTheImage() {
    call(hotwire(/*#1007313*/"#1016427"), "go", getImage(), titleForUpload);
  }
  
  void showFullScreen() {
    showFullScreenImageSurface(getImage());
  }
  
  void zoomIn(double f) { setZoom(getZoomX()*f, getZoomY()*f); }
  void zoomOut(double f) { setZoom(getZoomX()/f, getZoomY()/f); }
  
  ImageSurface setFile(File f) { file = f; return this; }
}

// static function allows garbage collection 
static VF2<ImageSurface, JPopupMenu> ImageSurface_popupMenuMaker() {
  return new VF2<ImageSurface, JPopupMenu>() { public void get(ImageSurface is, JPopupMenu menu) { try { 
    Point p = is.pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint();
    is.fillPopupMenu(menu, p);
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "Point p = is.pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint();\r..."; }};
}
static final class BWImage implements MakesBufferedImage, IBWImage {
  int width, height;
  byte[] pixels;

  // color returned when getPixel is called with a position outside the actual image
  float borderColor = 0.0f;
  
  // for unstructure()
  BWImage() {}

  // BLACK!
  BWImage(int width, int height) {
  this.height = height;
  this.width = width;
    pixels = new byte[width*height];
  }

  BWImage(int width, int height, float brightness) {
  this.height = height;
  this.width = width;
    pixels = new byte[width*height];
    fillArrayUnlessZero(pixels, _toByte(brightness));
  }
  
  BWImage(int width, int height, float[] pixels) {
    this.pixels = new byte[pixels.length];
  this.height = height;
  this.width = width;
    for (int i = 0; i < pixels.length; i++)
      this.pixels[i] = _toByte(pixels[i]);
  }

  public BWImage(int width, int height, byte[] pixels) {
    this.height = height;
    this.width = width;
    this.pixels = pixels;
  }

  public BWImage(BWImage image) {
    width = image.getWidth();
    height = image.getHeight();
    byte[] pixels = this.pixels = new byte[width*height];
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        pixels[y*width+x] = image.getByte(x, y);
  }

  // TODO: optimize!
  BWImage(RGBImage image) {
    width = image.getWidth();
    height = image.getHeight();
    byte[] pixels = this.pixels = new byte[height*width];
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++) {
        RGB rgb = image.getRGB(x, y);
        pixels[y*width+x] = BWImage._toByte(rgb.getBrightness());
      }
  }

  /*public BWImage(BufferedImage image) {
    this(new RGBImage(image));
  }*/

  BWImage(BufferedImage image) { try {
 width = image.getWidth();
    height = image.getHeight();
    int[] pixels = new int[width*height];
    byte[] bytePixels = this.pixels = new byte[width*height];
    PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
    if (!pixelGrabber.grabPixels())
      throw fail("Could not grab pixels");
    int n = width*height;
    
    for (int i = 0; i < n; i++) {
      //bytePixels[i] = pixelToByte(pixels[i]);
      int packed = pixels[i];
      /*float r = ((packed >> 16) & 0xFF)/255f;
      float g = ((packed >> 8) & 0xFF)/255f;
      float b = (packed & 0xFF)/255f;
      bytePixels[i] = (byte) iround((r+g+b)/3.0f*255f);*/
      int r = ((packed >> 16) & 0xFF);
      int g = ((packed >> 8) & 0xFF);
      int b = (packed & 0xFF);
      bytePixels[i] = (byte) ((r+g+b+1)/3);
    }
  } catch (Exception __e) { throw rethrow(__e); } }
  
  // TODO: does it exactly match the other method? (asRGB+getBrightness+_toByte)
  static byte pixelToByte(int packed) {
    /*int r = (packed >> 16) & 0xFF;
    int g = (packed >> 8) & 0xFF;
    int b = packed & 0xFF;
    ret (byte) ((r+g+b)/3.0f);*/
    float r = ((packed >> 16) & 0xFF)/255f;
    float g = ((packed >> 8) & 0xFF)/255f;
    float b = (packed & 0xFF)/255f;
    return (byte) ((r+g+b)/3.0f*255f);
  }

  public byte getByte(int x, int y) {
    return inRange(x, y) ? getByte_noRangeCheck(x, y) : _toByte(borderColor);
  }
  
  int getInt(int x, int y) {
    return ubyteToInt(getByte(x, y));
  }

  public double averageBrightness() {
    double sum = 0;
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        sum += getPixel(x, y);
    return (sum/(double) (height*width));
  }

  public float minimumBrightness() {
    float min = 1;
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        min = Math.min(min, getPixel(x, y));
    return min;
  }

  public float maximumBrightness() {
    float max = 0;
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        max = Math.max(max, getPixel(x, y));
    return max;
  }

  float getPixel(int x, int y) {
    return inRange(x, y) ? _toFloat(getByte(x,y )) : borderColor;
  }
  
  public float getFloatPixel(int x, int y) { return getPixel(x, y); }
  
  float getPixel(Pt p) { return getPixel(p.x, p.y); }

  static byte _toByte(float pixel) {
    return (byte) (pixel*255f);
  }

  static float _toFloat(byte pixel) {
    return (((int) pixel) & 255)/255f;
  }

  private boolean inRange(int x, int y) {
    return x >= 0 && x < width && y >= 0 && y < height;
  }

  public int getWidth() { return width; }
  int w() { return width; }

  public int getHeight() { return height; }
  int h() { return height; }

  public RGBImage toRGB() {
    int[] rgbs = new int[width*height];
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++) {
        int b = getByte(x, y) & 0xFF;
        rgbs[y*width+x] = 0xFF000000 | b*0x010101;
      }
    return new RGBImage(width, height, rgbs);
  }
  
  public RGBImage toRGB_slow() {
    RGB[] rgbs = new RGB[width*height];
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++) {
        float p = getPixel(x, y);
        rgbs[y*width+x] = new RGB(p, p, p);
      }
    return new RGBImage(width, height, rgbs);
  }


  public BWImage clip(int x, int y, int w, int h) {
    return clip(new Rectangle(x, y, w, h));
  }

  private Rectangle fixClipRect(Rectangle r) {
    return r.intersection(new Rectangle(0, 0, width, height));
  }

  BWImage clip(Rect r) {
    return clip(r.getRectangle());
  }
  
  /** this should be multithread-safe */
  public BWImage clip(Rectangle r) {
    r = fixClipRect(r);
    byte[] newPixels = new byte[r.height*r.width];
    for (int y = 0; y < r.height; y++)
      for (int x = 0; x < r.width; x++)
        newPixels[y*r.width+x] = getByte(r.x+x, r.y+y);
    return new BWImage(r.width, r.height, newPixels);
  }

  public void setPixel(int x, int y, float brightness) {
    setByte(x, y, _toByte(fixPixel(brightness)));
  }
  
  // i = 0 to 255
  public void setInt(int x, int y, int i) {
    setByte(x, y, (byte) limitToUByte(i));
  }
  
  public void setByte(int x, int y, byte b) {
    if (x >= 0 && x < width && y >= 0 && y < height)
      pixels[y*width+x] = b;
  }

  byte getByte_noRangeCheck(int x, int y) {
    return pixels[y*width+x];
  }

  public void setByte(int x, int y, int brightness) {
    setByte(x, y, (byte) brightness);
  }

  private float fixPixel(float pixel) {
    return Math.max(0, Math.min(1, pixel));
  }

  public float getBorderColor() {
    return borderColor;
  }

  public void setBorderColor(float borderColor) {
    this.borderColor = borderColor;
  }

  public boolean anyPixelBrighterThan(double threshold) {
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++)
        if (getPixel(x, y) > threshold)
          return true;
    return false;
  }
  
  public BufferedImage getBufferedImage() {
    //ret toRGB().getBufferedImage();
    
    // TYPE_BYTE_GRAY is buggy - see #1015235
    BufferedImage bufferedImage = new BufferedImage(width, height, /*BufferedImage.TYPE_BYTE_GRAY*/BufferedImage.TYPE_INT_RGB);
    for (int y = 0; y < height; y++)
      for (int x = 0; x < width; x++) {
        int b = ((int) getByte(x, y) & 0xFF);
        bufferedImage.setRGB(x, y, b*0x010101);
      }
    return bufferedImage; 
  }
  
  byte[] getBytes() {
    return pixels;
  }
}
static interface IResourceLoader {
  String loadSnippet(String snippetID);
  String getTranspiled(String snippetID); // with libs
  int getSnippetType(String snippetID);
  String getSnippetTitle(String snippetID);
  File loadLibrary(String snippetID);
  
  default File pathToJavaXJar() { return pathToJavaxJar_noResourceLoader(); }
  
  // may return null, then caller compiles themselves
  default File getSnippetJar(String snippetID, String transpiledSrc) { return null; }
}
static interface Steppable {
  public boolean step(); // return false if done
}
static class proxy_InvocationHandler implements InvocationHandler {
  Object target;
  
  proxy_InvocationHandler() {}
  proxy_InvocationHandler(Object target) {
  this.target = target;}
  
  public Object invoke(Object proxy, Method method, Object[] args) {
    return call(target, method.getName(), unnull(args));
  }
}
static interface IIntegralImage extends MakesBufferedImage {
  public int getWidth();
  public int getHeight();

  // get value for 1 channel
  // normal range [0; pixelCount*256)
  public double getIntegralValue(int x, int y, int channel);
    
  // gets value of the 3 channels
  // normal range [0; pixelCount*256*3)
  default double getIntegralValue(int x, int y) {
    return getIntegralValue(x, y, 0)
      + getIntegralValue(x, y, 1)
      + getIntegralValue(x, y, 2);
  }
  
  default double rectSum(int x1, int y1, int x2, int y2, int channel) {
    double bottomLeft  = getIntegralValue(x1-1, y2-1, channel);
    double bottomRight = getIntegralValue(x2-1, y2-1, channel);
    double topLeft     = getIntegralValue(x1-1, y1-1, channel);
    double topRight    = getIntegralValue(x2-1, y1-1, channel);
    return bottomRight+topLeft-topRight-bottomLeft;
  }
  
  default double rectSum(int x1, int y1, int x2, int y2) {
    double bottomLeft  = getIntegralValue(x1-1, y2-1);
    double bottomRight = getIntegralValue(x2-1, y2-1);
    double topLeft     = getIntegralValue(x1-1, y1-1);
    double topRight    = getIntegralValue(x2-1, y1-1);
    return bottomRight+topLeft-topRight-bottomLeft;
  }
  
  default IIntegralImage clip(int x, int y, int w, int h) {
    return new IIVirtualClip(this, x, y, w, h);
  }
  
  default double averageBrightness() {
    int w = getWidth(), h = getHeight();
    return doubleRatio(getIntegralValue(w-1, h-1), w*h*3*255.0);
  }
}
static class Fail extends RuntimeException implements IFieldsToList{
  Object[] objects;
  Fail() {}
  Fail(Object... objects) {
  this.objects = objects;}
  public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + objects + ")"; }public Object[] _fieldsToList() { return new Object[] {objects}; }
}
static class Pair<A, B> implements Comparable<Pair<A, B>> {
  A a;
  B b;

  Pair() {}
  Pair(A a, B b) {
  this.b = b;
  this.a = a;}
  
  public int hashCode() {
    return hashCodeFor(a) + 2*hashCodeFor(b);
  }
  
  public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof Pair)) return false;
    Pair t = (Pair) o;
    return eq(a, t.a) && eq(b, t.b);
  }
  
  public String toString() {
    return "<" + a + ", " + b + ">";
  }
  
  public int compareTo(Pair<A, B> p) {
    if (p == null) return 1;
    int i = ((Comparable<A>) a).compareTo(p.a);
    if (i != 0) return i;
    return ((Comparable<B>) b).compareTo(p.b);
  }
}
static interface IResourceHolder {
  <A extends AutoCloseable> A add(A a);
}
static interface IAutoCloseableF0<A> extends IF0<A>, AutoCloseable {}
static abstract class F0<A> {
  abstract A get();
}
static abstract class F1<A, B> {
  abstract B get(A a);
}
// you still need to implement hasNext() and next()
static abstract class IterableIterator<A> implements Iterator<A>, Iterable<A> {
  public Iterator<A> iterator() {
    return this;
  }
  
  public void remove() {
    unsupportedOperation();
  }
}
static interface MakesBufferedImage extends WidthAndHeight {
  BufferedImage getBufferedImage();
  
  public default void drawAt(Graphics2D g, int x, int y) {
    g.drawImage(getBufferedImage(), x, y, null);
  }
}
static class BetterLabel extends JLabel {
  boolean autoToolTip = true;
  
  BetterLabel() {
    // Listeners given out to componentPopupMenu must not directly
    // reference the outer object (-> weak map problem).
    final WeakReference < BetterLabel > me = new WeakReference<>(this);
    componentPopupMenu(this, BetterLabel_menuItems(me));
  }
  
  BetterLabel(String text) {
    this();
    this.setText(text);
  }
  
  public void setText(String text) {
    super.setText(text);
    if (autoToolTip)
      if (!swic(text, "<html>")) // HTML labels make super-huge, confusing tool tips
        setToolTipText(nullIfEmpty(text));
  }
}

// moved outside of class for GC reasons (see above)
static VF1<JPopupMenu> BetterLabel_menuItems(final WeakReference<BetterLabel> me) {
  return new VF1<JPopupMenu>() { public void get(JPopupMenu menu) { try { 
    addMenuItem(menu, "Copy text to clipboard", new Runnable() {  public void run() { try { 
      copyTextToClipboard(me.get().getText());
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "copyTextToClipboard(me.get().getText());"; }});
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n      copyTextToClipboard(me..."; }};
}
// elements are put to front when added (not when accessed)
static class MRUCache<A, B> extends LinkedHashMap<A, B> {
  int maxSize = 10;

  MRUCache() {}
  MRUCache(int maxSize) {
  this.maxSize = maxSize;}
  
  protected boolean removeEldestEntry(Map.Entry eldest) {
    return size() > maxSize;
  }
  
  Object _serialize() {
    return ll(maxSize, cloneLinkedHashMap(this));
  }
  
  static MRUCache _deserialize(List l) {
    MRUCache m = new MRUCache();
    m.maxSize = (int) first(l);
    m.putAll((LinkedHashMap) second(l));
    return m;
  }
}
static interface IF0<A> {
  A get();
}
static abstract class CloseableIterableIterator<A> extends IterableIterator<A> implements AutoCloseable {
  public void close() throws Exception {}
}
static interface IF2<A, B, C> {
  C get(A a, B b);
}

static interface IF1<A, B> {
  B get(A a);
}
final static class IntegralImage implements IIntegralImage {
  int w, h;
  int[] data; // 3 ints per pixel
  
  IntegralImage(RGBImage img) {
    init(img);
  }
  
  void init(RGBImage img) {
    w = img.w();
    h = img.h();
    if (longMul(w, h) > 8000000) throw fail("Image too big: " + w + "*" + h);
    data = new int[w*h*3];
    int i = 0;
    for (int y = 0; y < h; y++) {
      int sumR = 0, sumG = 0, sumB = 0;
      for (int x = 0; x < w; x++) {
        int rgb = img.getInt(x, y);
        sumR += (rgb >> 16) & 0xFF;
        sumG += (rgb >> 8) & 0xFF;
        sumB += rgb & 0xFF;
        data[i] = y > 0 ? sumR + data[i-w*3] : sumR;
        data[i+1] = y > 0 ? sumG + data[i-w*3+1] : sumG;
        data[i+2] = y > 0 ? sumB + data[i-w*3+2] : sumB;
        i += 3;
      }
    }
  }
  
  IntegralImage(MakesBufferedImage img) {
    if (img instanceof RGBImage)
      init(((RGBImage) img));
    else
      init(toBufferedImage(img));
  }
  
  IntegralImage(BufferedImage img) {
    init(img);
  }
  
  void init(BufferedImage img) {
    w = img.getWidth();
    h = img.getHeight();
    if (longMul(w, h) > 8000000) throw fail("Image too big: " + w + "*" + h);
    int[] pixels = pixelsOfBufferedImage(img);
    data = new int[w*h*3];
    int i = 0, j = 0, sumR = 0, sumG = 0, sumB = 0;
    for (int x = 0; x < w; x++) {
      int rgb = pixels[j++];
      data[i++] = (sumR += (rgb >> 16) & 0xFF);
      data[i++] = (sumG += (rgb >> 8) & 0xFF);
      data[i++] = (sumB += rgb & 0xFF);
    }
    for (int y = 1; y < h; y++) {
      sumR = sumG = sumB = 0;
      for (int x = 0; x < w; x++) {
        int rgb = pixels[j++];
        sumR += (rgb >> 16) & 0xFF;
        sumG += (rgb >> 8) & 0xFF;
        sumB += rgb & 0xFF;
        data[i] = sumR + data[i-w*3];
        data[i+1] = sumG + data[i-w*3+1];
        data[i+2] = sumB + data[i-w*3+2];
        i += 3;
      }
    }
  }
  
  // gets the integral value at x/y for given RGB channel
  public double get(int x, int y, int channel) { return getIntegralValue(x, y, channel); }
public double getIntegralValue(int x, int y, int channel) {
    return x < 0 || y < 0 || x >= w || y >= h ? 0
      : data[(y*w+x)*3+channel];
  }
  
  // gets sum of the 3 channels
  public double get(int x, int y) { return getIntegralValue(x, y); }
public double getIntegralValue(int x, int y) {
    if (x < 0 || y < 0 || x >= w || y >= h) return 0;
    int i = (y*w+x)*3;
    return data[i]+data[i+1]+data[i+2];
  }
  
  public String toString() {
    return "IntegralImage " + w + "*" + h + ", brightness: " + averageBrightness();
  }
  
  public BufferedImage getBufferedImage() { return integralImageToBufferedImage(this); }
  public int getWidth() { return w; }
  public int getHeight() { return h; }
  int w() { return w; }
  int h() { return h; }
  
  // serialization
  
  Object _serialize() { return litobjectarray(w, h, data); }
  static IntegralImage _deserialize(Object[] l) { return new IntegralImage((int) l[0], (int) l[1], (int[]) l[2]); }
  IntegralImage(int w, int h, int[] data) {
  this.data = data;
  this.h = h;
  this.w = w;}
}
static class PersistableThrowable extends DynamicObject {
  String className;
  String msg;
  String stacktrace;
  
  PersistableThrowable() {}
  PersistableThrowable(Throwable e) {
    if (e == null)
      className = "Crazy Null Error";
    else {
      className = getClassName(e).replace('/', '.');
      msg = e.getMessage();
      stacktrace = getStackTrace_noRecord(e);
    }
  }
  
  public String toString() {
    return nempty(msg) ? className + ": " + msg : className;
  }
}
// U for stands for the "Ultra-Fast Recognition" family of recognizers
static class URecognizer {
  IIntegralImage image;
  
  URecognizer() {}
  URecognizer(IIntegralImage image) {
  this.image = image;}
  URecognizer(BufferedImage image) {
    this.image = new IntegralImage(image);
  }
  
  // returns 0, 1 or 2
  int posterizeToInt(double x) {
    return ifloor(clampZeroToOne(x)*3);
  }

  // returns 0, .5 or 1
  double posterizeInPlace(double x) {
    return posterizeToInt(x)*.5;
  }
  
  class Cell {
    // Which part of the image we are looking at (x/y)
    // dimension 0 = x, dimension 1 = y
    DoubleRange[] clip = new DoubleRange[2];
  
    // color transformations in place
    DoubleRange[] colorClips = new DoubleRange[3];
  
    Cell copy() {
      return copyTo(new Cell());
    }
    
    Cell copyTo(Cell c) {
      arrayCopy(clip, c.clip);
      arrayCopy(colorClips, c.colorClips);
      return c;
    }
  
    Rect rectInImage() {
      return rectMinSize(1, 1, toRect_floor(doubleRectFromRanges(clip[0], clip[1])));
    }
    
    double area() { return rectArea(rectInImage()); }
  
    // get color of cell
  
    double color(int channel) {
      double color = ii_averageBrightnessOfArea(image, rectInImage(), channel);
      return transformBetweenDoubleRanges(color, colorClips[channel], zeroToOne());
    }
    
    // unposterized color of all 3 channels
    double[] colors() {
      double[] c = new double[3];
      for (int i = 0; i < 3; i++)
        c[i] = color(i);
      return c;
    }
    
    RGB averageColor() { return rgb(); }
RGB rgb() {
      return new RGB(colors());
    }
    
    public String toString() {
      return rectInImage() + ", color: " + map(asList(colors()), x -> formatDoubleX(x, 4));
    }
  
    int posterizedIntColor(int channel) {
      return posterizeToInt(color(channel));
    }
  
    // get sub-cells
    
    Cell[] cellArray(int n) {
      return new Cell[n];
    }
    
    Cell[] split(int dimension) { return split(dimension, 3); }
Cell[] split(int dimension, int n) {
      Cell[] cells = cellArray(n);
      for (int i = 0; i < n; i++) cells[i] = slice(dimension, doubleRatio(i, n), doubleRatio(i+1, n));
      return cells;
    }
  
    Cell slice(int dimension, double a, double b) {
      Cell c = copy();
      c.clip[dimension] = transformBetweenDoubleRanges(new DoubleRange(a, b), zeroToOne(), clip[dimension]);
      return c;
    }
    
    // index = 0 to 2
    Cell third(int dimension, int index) {
      return slice(dimension, index/3.0, (index+1)/3.0);
    }
    
    // convert to B/W
    
    BWCell channel(int channel) {
      BWCell c = new BWCell();
      copyTo(c);
      c.colorToBW = rgb -> rgb[channel];
      return c;
    }
    
    BWCell brightness() {
      BWCell c = new BWCell();
      copyTo(c);
      return c;
    }
    
    double get() { return averageBrightness(); }
double averageBrightness() {
      return brightness().color();
    }
    
    double getWidth() { return clip[0].length(); }
    double getHeight() { return clip[1].length(); }
  }

  class BWCell extends Cell {
    IF1<double[], Double> colorToBW = rgb -> (rgb[0]+rgb[1]+rgb[2])/3;
    
    double color() {
      return colorToBW.get(colors());
    }
    
    BWCell copy() {
      BWCell c = new BWCell();
      copyTo(c);
      return c;
    }
    
    void copyTo(BWCell c) {
      super.copyTo(c);
      c.colorToBW = colorToBW;
    }
    
    public String toString() {
      return rectInImage() + ", Color: " + formatDoubleX(color(), 4);
    }
  
    // lift methods
    
    BWCell[] cellArray(int n) {
      return new BWCell[n];
    }
    
    BWCell slice(int dimension, double a, double b) {
      return (BWCell) super.slice(dimension, a, b);
    }
    
    BWCell[] split(int dimension) {
      return (BWCell[]) super.split(dimension);
    }
    
    BWCell third(int dimension, int index) {
      return (BWCell) super.third(dimension, index);
    }
  }
  
  // make the root cell
  Cell cell() { return rootCell(); }
Cell rootCell() {
    Cell c = new Cell();
    c.clip[0] = doubleRange(0, image.getWidth());
    c.clip[1] = doubleRange(0, image.getHeight());
    for (int i = 0; i < 3; i++) c.colorClips[i] = doubleRange(0, 255);
    return c;
  }
  
  int outlierPosition(BWCell[] cells) {
    double a = cells[0].color();
    double b = cells[1].color();
    double c = cells[2].color();
    double ab = abs(a-b), bc = abs(b-c), ac = abs(a-c);
    if (bc < min(ab, ac)) return 0; // b and c close together
    if (ac < min(ab, bc)) return 1; // a and c close together
    if (ab < min(ac, bc)) return 2; // a and b close together
    return -1; // unknown
  }
}
static interface IVF1<A> {
  void get(A a);
}
static interface IVar<A> extends IF0<A> {
  void set(A a);
  A get();
  
  default boolean has() { return get() != null; }
  default void clear() { set(null); }
  
}
static class RGBImage implements MakesBufferedImage {
  transient BufferedImage bufferedImage;
  File file;
  int width, height;
  int[] pixels;

  RGBImage() {}

  RGBImage(BufferedImage image) {
    this(image, null);
  }

  RGBImage(BufferedImage image, File file) {
    this.file = file;
    bufferedImage = image;
    width = image.getWidth();
    height = image.getHeight();
    pixels = new int[width*height];
    PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
    try {
      if (!pixelGrabber.grabPixels())
        throw new RuntimeException("Could not grab pixels");
      cleanPixels(); // set upper byte to 0
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }

  /** We assume it's a file name to load from */
  RGBImage(String file) throws IOException {
    this(new File(file));
  }

  RGBImage(Dimension size, Color color) {
    this(size.width, size.height, color);
  }

  RGBImage(Dimension size, RGB color) {
    this(size.width, size.height, color);
  }

  private void cleanPixels() {
    for (int i = 0; i < pixels.length; i++)
      pixels[i] &= 0xFFFFFF;
  }

  RGBImage(int width, int height, int[] pixels) {
    this.width = width;
    this.height = height;
    this.pixels = pixels;
  }

  RGBImage(int w, int h, RGB[] pixels) {
    this.width = w;
    this.height = h;
    this.pixels = asInts(pixels);
  }

  public static int[] asInts(RGB[] pixels) {
    int[] ints = new int[pixels.length];
    for (int i = 0; i < pixels.length; i++)
      ints[i] = pixels[i] == null ? 0 : pixels[i].getColor().getRGB();
    return ints;
  }

  public RGBImage(int w, int h) {
    this(w, h, Color.black);
  }
  
  RGBImage(int w, int h, RGB rgb) {
    this.width = w;
    this.height = h;
    this.pixels = new int[w*h];
    int col = rgb.asInt();
    if (col != 0)
      for (int i = 0; i < pixels.length; i++)
        pixels[i] = col;
  }

  RGBImage(RGBImage image) {
    this(image.width, image.height, copyPixels(image.pixels));
  }

  RGBImage(int width, int height, Color color) {
    this(width, height, new RGB(color));
  }

  RGBImage(File file) throws IOException {
    this(javax.imageio.ImageIO.read(file));
  }
  
  RGBImage(MakesBufferedImage img) {
    this(toBufferedImage(img));
  }

  private static int[] copyPixels(int[] pixels) {
    int[] copy = new int[pixels.length];
    System.arraycopy(pixels, 0, copy, 0, pixels.length);
    return copy;
  }

  public int getIntPixel(int x, int y) {
    if (inRange(x, y))
      return pixels[y * width + x];
    else
      return 0xFFFFFF;
  }

  public static RGB asRGB(int packed) {
    int r = (packed >> 16) & 0xFF;
    int g = (packed >> 8) & 0xFF;
    int b = packed & 0xFF;
    return new RGB(r / 255f, g / 255f, b / 255f);
  }

  public RGB getRGB(int x, int y) {
    if (inRange(x, y))
      return asRGB(pixels[y * width + x]);
    else
      return new RGB(0xFFFFFF);
  }

  /** alias of getRGB - I kept typing getPixel instead of getRGB all the time, so I finally created it */
  RGB getPixel(int x, int y) {
    return getRGB(x, y);
  }
  
  RGB getPixel(Pt p) { return getPixel(p.x, p.y); }

  public int getWidth() { return width; }
  public int getHeight() { return height; }
  int w() { return width; }
  int h() { return height; }

  /** Attention: cached, i.e. does not change when image itself changes */
  /** @NotNull */
  public BufferedImage getBufferedImage() {
    if (bufferedImage == null) {
      bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      //bufferedImage.setData(Raster.createRaster(new SampleModel()));
      for (int y = 0; y < height; y++)
        for (int x = 0; x < width; x++)
          bufferedImage.setRGB(x, y, pixels[y*width+x]);
    }
    return bufferedImage;
  }

  RGBImage clip(Rect r) {
    return r == null ? null : clip(r.getRectangle());
  }
  
  RGBImage clip(Rectangle r) {
    r = fixClipRect(r);
    if (r.x == 0 && r.y == 0 && r.width == width && r.height == height) return this;
    int[] newPixels;
    try {
      newPixels = new int[r.width*r.height];
    } catch (RuntimeException e) {
      System.out.println(r);
      throw e;
    }
    for (int y = 0; y < r.height; y++) {
      System.arraycopy(pixels, (y+r.y)*width+r.x, newPixels, y*r.width, r.width);
    }
    return new RGBImage(r.width, r.height, newPixels);
  }

  private Rectangle fixClipRect(Rectangle r) {
    r = r.intersection(new Rectangle(0, 0, width, height));
    if (r.isEmpty())
      r = new Rectangle(r.x, r.y, 0, 0);
    return r;
  }

  public File getFile() {
    return file;
  }

  /** can now also do GIF (not just JPEG) */
  public static RGBImage load(String fileName) {
    return load(new File(fileName));
  }

  /** can now also do GIF (not just JPEG) */
  public static RGBImage load(File file) {
    try {
      BufferedImage bufferedImage = javax.imageio.ImageIO.read(file);
      return new RGBImage(bufferedImage);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public int getInt(int x, int y) {
    return pixels[y * width + x];
  }

  public void save(File file) throws IOException {
    String name = file.getName().toLowerCase();
    String type;
    if (name.endsWith(".png")) type = "png";
    else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) type = "jpeg";
    else throw new IOException("Unknown image extension: " + name);
    javax.imageio.ImageIO.write(getBufferedImage(), type, file);
  }

  public static RGBImage dummyImage() {
    return new RGBImage(1, 1, new int[] {0xFFFFFF});
  }

  public int[] getPixels() {
    return pixels;
  }
  
  void setPixel(int x, int y, int r, int g, int b) {
    if (x >= 0 && y >= 0 && x < width && y < height)
      pixels[y*width+x] = (limitToUByte(r) << 16) | (limitToUByte(g) << 8) | limitToUByte(b);
  }

  public void setPixel(int x, int y, RGB rgb) {
    if (x >= 0 && y >= 0 && x < width && y < height)
      pixels[y*width+x] = rgb.asInt();
  }

  public void set(int x, int y, Color color) { setPixel(x, y, color); }
public void setPixel(int x, int y, Color color) {
    setPixel(x, y, new RGB(color));
  }
  
  void setInt(int x, int y, int rgb) {
    setPixel(x, y, rgb);
  }

  public void setPixel(int x, int y, int rgb) {
    if (x >= 0 && y >= 0 && x < width && y < height)
      pixels[y*width+x] = rgb;
  }
  
  void setPixel(Pt p, RGB rgb) { setPixel(p.x, p.y, rgb); }
  void setPixel(Pt p, Color color) { setPixel(p.x, p.y, color); }

  public RGBImage copy() {
    return new RGBImage(this);
  }

  public boolean inRange(int x, int y) {
    return x >= 0 && y >= 0 && x < width && y < height;
  }

  public Dimension getSize() {
    return new Dimension(width, height);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    RGBImage rgbImage = (RGBImage) o;

    if (height != rgbImage.height) return false;
    if (width != rgbImage.width) return false;
    if (!Arrays.equals(pixels, rgbImage.pixels)) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = width;
    result = 31 * result + height;
    result = 31 * result + Arrays.hashCode(pixels);
    return result;
  }

  public String getHex(int x, int y) {
    return getPixel(x, y).getHexString();
  }

  public RGBImage clip(int x, int y, int width, int height) {
    return clip(new Rectangle(x, y, width, height));
  }

  public RGBImage clipLine(int y) {
    return clip(0, y, width, 1);
  }

  public int numPixels() {
    return width*height;
  }
  
  void uncacheBufferedImage() {
    bufferedImage = null;
  }
}

static interface IMapImplementationPolicy {
  public <A, B> Map<A, B> makeSingletonMap(A key, B value);
  public <A, B> Map<A, B> put(Map<A, B> map, A key, B value);
  public <A, B> Map<A, B> remove(Map<A, B> map, Object key);
}


final static class Rect {
  int x, y, w, h;
  
  Rect() {}
  Rect(Rectangle r) {
    x = r.x;
    y = r.y;
    w = r.width;
    h = r.height;
  }
  Rect(int x, int y, int w, int h) {
  this.h = h;
  this.w = w;
  this.y = y;
  this.x = x;}
  Rect(Pt p, int w, int h) {
  this.h = h;
  this.w = w; x = p.x; y = p.y; }
  Rect(Rect r) { x = r.x; y = r.y; w = r.w; h = r.h; }
  
  Rectangle getRectangle() {
    return new Rectangle(x, y, w, h);
  }
  
  public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
  
  public String toString() {
    return x + "," + y + " / " + w + "," + h;
  }
  
  int x1() { return x; }
  int y1() { return y; }
  int x2() { return x + w; }
  int y2() { return y + h; }
  
  boolean contains(Pt p) {
    return contains(p.x, p.y);
  }
  
  boolean contains(int _x, int _y) {
    return _x >= x && _y >= y && _x < x+w && _y < y+h;
  }
  
  boolean empty() { return w <= 0 || h <= 0; }
}
static interface IBWImage {
  int getWidth();
  int getHeight();
  float getFloatPixel(int x, int y);
}
static abstract class VF2<A, B> {
  abstract void get(A a, B b);
}
static class Pt implements Comparable<Pt> {
  int x, y;
  
  Pt() {}
  Pt(Point p) {
    x = p.x;
    y = p.y;
  }
  Pt(int x, int y) {
  this.y = y;
  this.x = x;}
  
  Point getPoint() {
    return new Point(x, y);
  }
  
  public boolean equals(Object o) {
    return o instanceof Pt && x == ((Pt) o).x && y == ((Pt) o).y;
  }
  
  public int hashCode() {
    return boostHashCombine(x, y);
  }
  
  // compare in scan order
  public int compareTo(Pt p) {
    if (y != p.y) return cmp(y, p.y);
    return cmp(x, p.x);
  }
  
  public String toString() {
    return x + ", " + y;
  }
}
static interface ISetter<A> {
 void set(A a);
}

static class BodyOfEvidence<Src> {
  // values are: WithProbability(strengthOfEvidence, probabilityOfTheory)
  // will only hold one piece of evidence per src object
  Map<Src, WithProbability<Double>> examples = syncMap();
  double strengthSum, probabilitySum;
  
  Object mutex() { return examples; }
  
  double currentProbabilityGuess() {
    synchronized(mutex()) {
      return doubleRatio(probabilitySum, strengthSum);
    }
  }
  
  String renderProbabilityGuess() {
    return "Current probability guess (evidence count " + n2(l(examples)) + "): " + formatDouble3X(currentProbabilityGuess()) + " with strength " + formatDouble3(strengthSum);
  }
  
  boolean hasEvidenceFromSource(Src src) { return examples.containsKey(src); }
  
  boolean addEvidence(Src src, double probabilityOfTheory, double strengthOfEvidence) {
    synchronized(mutex()) {
      if (hasEvidenceFromSource(src)) return false;
      examples.put(src, withProbability(strengthOfEvidence, probabilityOfTheory));
      probabilitySum += probabilityOfTheory*strengthOfEvidence;
      strengthSum += strengthOfEvidence;
      return true;
    }
  }
  
  String toStringWithEvidence() {
    return toString() + "\n\n"
      + pnlToString(mapToList(examples, (src, e) ->
        (e.get() == 0.5 ? "     " : e.get() > 0.5 ? "   PRO" : " CONTRA")
        + ": " + e + " - " + src));
  }
}

static class RGB {
  public float r, g, b; // can't be final cause persistence
  
  RGB() {}
  
  public RGB(float r, float g, float b) {
    this.r = r;
    this.g = g;
    this.b = b;
  }

  public RGB(double r, double g, double b) {
    this.r = (float) r;
    this.g = (float) g;
    this.b = (float) b;
  }
  
  public RGB(double[] rgb) {
    this(rgb[0], rgb[1], rgb[2]);
  }

  public RGB(int rgb) {
    this(new Color(rgb));
  }
  
  public RGB(double brightness) {
    this.r = this.g = this.b = max(0f, min(1f, (float) brightness));
  }

  public RGB(Color color) {
    this.r = color.getRed()/255f;
    this.g = color.getGreen()/255f;
    this.b = color.getBlue()/255f;
  }

  // TODO: 3-char version
  public RGB(String hex) {
    int i = l(hex)-6;
    r = Integer.parseInt(hex.substring(i, i+2), 16)/255f;
    g = Integer.parseInt(hex.substring(i+2, i+4), 16)/255f;
    b = Integer.parseInt(hex.substring(i+4, i+6), 16)/255f;
  }

  public float getComponent(int i) {
    return i == 0 ? r : i == 1 ? g : b;
  }

  public Color getColor() {
    return new Color(r, g, b);
  }

  public static RGB newSafe(float r, float g, float b) {
    return new RGB(Math.max(0, Math.min(1, r)), Math.max(0, Math.min(1, g)), Math.max(0, Math.min(1, b)));
  }

  int asInt() { return getColor().getRGB() & 0xFFFFFF; }
  int getInt() { return getColor().getRGB() & 0xFFFFFF; }
  int asIntWithAlpha() { return rgbInt(redInt(), greenInt(), blueInt()) | 0xFF000000; }

  public float getBrightness() {
    return (r+g+b)/3.0f;
  }

  public String getHexString() {
    return Integer.toHexString(asInt() | 0xFF000000).substring(2).toUpperCase();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof RGB)) return false;

    RGB rgb = (RGB) o;

    if (Float.compare(rgb.b, b) != 0) return false;
    if (Float.compare(rgb.g, g) != 0) return false;
    if (Float.compare(rgb.r, r) != 0) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = (r != +0.0f ? Float.floatToIntBits(r) : 0);
    result = 31 * result + (g != +0.0f ? Float.floatToIntBits(g) : 0);
    result = 31 * result + (b != +0.0f ? Float.floatToIntBits(b) : 0);
    return result;
  }

  public boolean isBlack() {
    return r == 0f && g == 0f && b == 0f;
  }

  public boolean isWhite() {
    return r == 1f && g == 1f && b == 1f;
  }

  public String toString() {
    return getHexString();
  }
  
  int redInt() { return iround(r*255); }
  int greenInt() { return iround(g*255); }
  int blueInt() { return iround(b*255); }
}
abstract static class Surface extends JPanel {
  public boolean clearSurface = true;
  private boolean clearOnce = false;

  Surface() {
    setDoubleBuffered(false);
  }

  Graphics2D createGraphics2D(int width, int height, Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setBackground(getBackground());
    if (clearSurface || clearOnce) {
      g2.clearRect(0, 0, width, height);
      clearOnce = false;
    }
    return g2;
  }

  public abstract void render(int w, int h, Graphics2D g);

  public void paintImmediately(int x,int y,int w, int h) {
    RepaintManager repaintManager = null;
    boolean save = true;
    if (!isDoubleBuffered()) {
      repaintManager = RepaintManager.currentManager(this);
      save = repaintManager.isDoubleBufferingEnabled();
      repaintManager.setDoubleBufferingEnabled(false);
    }
    super.paintImmediately(x, y, w, h);

    if (repaintManager != null)
      repaintManager.setDoubleBufferingEnabled(save);
  }

  public void paint(Graphics g) {
    Dimension d = getSize();
    Graphics2D g2 = createGraphics2D(d.width, d.height, g);
    render(d.width, d.height, g2);
    g2.dispose();
  }
}

static class IIVirtualClip extends Meta implements IIntegralImage {
  RegisteredReference < IIntegralImage > fullImage = new RegisteredReference<>(this);
  int x1, y1, w, h;
  
  IIVirtualClip() {}
  IIVirtualClip(IIntegralImage fullImage, int x1, int y1, int w, int h) {
    this.fullImage.set(fullImage);
  this.h = h;
  this.w = w;
  this.y1 = y1;
  this.x1 = x1;
  }
  
  public int getWidth() { return w; }
  public int getHeight() { return h; }

  public double getIntegralValue(int x, int y, int channel) {
    return fullImage.get().getIntegralValue(x+x1, y+y1, channel);
  }
    
  public double getIntegralValue(int x, int y) {
    return fullImage.get().getIntegralValue(x+x1, y+y1);
  }
  
  public BufferedImage getBufferedImage() {
    return clipBufferedImage(fullImage.get().getBufferedImage(), x1, y1, w, h);
  }
}
final static class DoubleRange {
  double start, end;
  
  DoubleRange() {}
  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); }
  
  double length() { return end-start; }
  
  static String _fieldOrder = "start end";
  
  public String toString() { return "[" + start + ";" + end + "]"; }
}
static class ProbabilisticScheduler implements IProbabilisticScheduler, Steppable {
  TreeSetWithDuplicates < Entry > entries = new TreeSetWithDuplicates<>(byProbability());

  long stepCount;
  boolean verbose = false;
  
  // must be >= 0. probability 0 is never executed
  double cutoffProbabilityOnAdd = 0;
  double cutoffProbabilityOnExecute = 0;
  
  Comparator<Entry> byProbability() { return (a, b) -> cmp(b.probability, a.probability); }
  
  ThreadLocal<Double> threadProbability = new ThreadLocal();
  
  static class Entry {
  Entry() {}
    double probability;
    Runnable action;
    
    Entry(double probability, Runnable action) {
  this.action = action;
  this.probability = probability;}
    
    public void run() { action.run(); }

    public String toString() {
      return str(new WithProbability(probability, action));
    }
  }
  
  public void at(double probability, Runnable action) { add(probability, action); }
public void add(double probability, Runnable action) {
    if (action == null) return;
    if (probability <= cutoffProbabilityOnAdd) return;
    entries.add(new Entry(probability, action));
  }
  
  public boolean step() {
    return stepFirstUnstepped();
  }
  
  Entry nextSteppable() {
    Entry s = first(entries);
    if (s != null && s.probability <= cutoffProbabilityOnExecute) return null;
    return s;
  }
  
  // returns false when done stepping
  boolean stepFirstUnstepped() {
    Entry s = nextSteppable(); if (s == null) return false;
    if (verbose) print("Current scheduler probability: " + s.probability);
    entries.remove(s);
    ++stepCount;
     AutoCloseable __1 = tempSetTL(threadProbability, s.probability); try {
    s.run();
    return true;
  } finally { _close(__1); }}
  
  void reset() {
    entries.clear();
  }

  public void run() {
    stepAll(this);
  }
  
  void run(int maxSteps) {
    stepMax(maxSteps, this);
  }

  void printStats() {
    Entry first = entries.first(), last = entries.last();
    Entry next = nextSteppable();
    print("ProbabilisticScheduler. "
      + nEntries(entries)
      + ", highest probability in queue: " + (first == null ? "-" : first.probability)
      + ", lowest probability in queue: " + (last == null ? "-" : last.probability)
      + ", cutoff probability: " + cutoffProbabilityOnAdd + "/" + cutoffProbabilityOnExecute
      + ", " + (next == null ? "done" : "next step: " + next.action));
  }
  
  // Get probability of this thread's Runnable.
  // Or 1.0 when we are coming from "outside" (so you don't _have_ to
  // run your first step through the scheduler).
  public double current() { return currentProbability(); }
public double currentProbability() {
    return or(threadProbability.get(), 1.0);
  }
  
  IProbabilisticScheduler freeze() {
    double prob = currentProbability();
    return new IProbabilisticScheduler() {
      public void at(double probability, Runnable action) {
        ProbabilisticScheduler.this.at(prob*probability, action);
      }
      
      public double currentProbability() {
        return prob;
      }
      
      public long stepCount() { return stepCount; }
    };
  }
  
  double remainingProbability() {
    Entry s = nextSteppable();
    return s == null ? 0.0 : s.probability;
  }
  
  public long stepCount() { return stepCount; }
}
static interface IFieldsToList {
  Object[] _fieldsToList();
}
static class ImageSurfaceSelector extends MouseAdapter {
  ImageSurface is;
  Point startingPoint;
  boolean enabled = true;
  static boolean verbose = false;

  ImageSurfaceSelector(ImageSurface is) {
  this.is = is;
    if (containsInstance(is.tools, ImageSurfaceSelector.class)) return;
    is.tools.add(this);
    is.addMouseListener(this);
    is.addMouseMotionListener(this);
  }

  public void mousePressed(MouseEvent evt) {
    if (verbose) print("mousePressed");
    if (evt.getButton() != MouseEvent.BUTTON1) return;
    if (enabled)
      startingPoint = getPoint(evt);
  }

  public void mouseDragged(MouseEvent e) {
    if (verbose) print("mouseDragged");
    if (startingPoint != null) {
      Point endPoint = getPoint(e);
      Rectangle r = new Rectangle(startingPoint, new Dimension(endPoint.x-startingPoint.x+1, endPoint.y-startingPoint.y+1));
      normalize(r);
      r.width = min(r.width, is.getImage().getWidth()-r.x);
      r.height = min(r.height, is.getImage().getHeight()-r.y);
      is.setSelection(r);
    }
    if (verbose) print("mouseDragged done");
  }

  public static void normalize(Rectangle r) {
    if (r.width < 0) {
      r.x += r.width;
      r.width = -r.width;
    }
    if (r.height < 0) {
      r.y += r.height;
      r.height = -r.height;
    }
  }

  public void mouseReleased(MouseEvent e) {
    if (verbose) print("mouseReleased");
    mouseDragged(e);
    if (getPoint(e).equals(startingPoint))
      is.setSelection((Rectangle) null);
    startingPoint = null;
  }
  
  Point getPoint(MouseEvent e) {
    return new Point((int) (e.getX()/is.getZoomX()), (int) (e.getY()/is.getZoomY()));
  }
}
static interface WidthAndHeight {
  int getWidth();
  int getHeight();
}
static class WithProbability<A> extends Var<A> implements Comparable<WithProbability<A>> {
  double probability; // assumed between 0 and 1
  
  WithProbability() {}
  WithProbability(double probability, A a) { super(a);
  this.probability = probability; }
  
  public String toString() {
    return "p=" + renderedProbability() + ": " + str(get());
  }
  
  String renderedProbability() {
    return formatDouble_noLeadingZero(probability, 2);
  }
  
  double probability() { return probability; }
  
  public int hashCode() {
    return boostHashCombine(main.hashCode(probability), main.hashCode(get()));
  }
  
  public boolean equals(Object o) {
    if (o instanceof WithProbability) {
      return probability == ((WithProbability) o).probability && eq(get(), ((WithProbability) o).get());
    }
    return false;
  }
  
  // Higher probability comes first!
  public int compareTo(WithProbability<A> wp) {
    return wp == null ? 1
      : cmp(wp.probability, probability);
  }
}


static interface IProbabilisticScheduler {
  // schedule an action at an absolute probability
  void at(double probability, Runnable action);
  
  // schedule an action at a probability relative to
  // currentProbability()
  default void schedule(double probability, Runnable action) { atRelative(probability, action); }
default void atRelative(double probability, Runnable action) {
    at(currentProbability()*probability, action);
  }
  
  double currentProbability();
  long stepCount();
}
// Meta - a "minimal" approach to adding meta-level to Java objects

static class Meta implements IMeta {
  // We allocate one extra field for each Java object to make it
  // reasoning-compatible. We couldn't go for 0 extra fields and
  // there are no half fields in Java... so there you go.
  // Also, if you don't use any meta data, you are probably not
  // reasoning about anything. The point of reasoning in JavaX is
  // to attach information to objects directly used in the program.
  
  // Possible information contained in the meta field:
  //   Origin, destination, security level, sender, cost center,
  //   purpose, list of reifications, ...
  
  // So here it is. The field.
  // We also have IMeta to retrofit foreign classes (rare but
  // probably useful)
  
  // generic meta value of any kind (e.g. Map with extra field values
  // for the object).
  // volatile to avoid synchronization; but you can also synchronize on
  // _tempMetaMutex() which is usually the object itself. Still considering
  // whether that is actually a good idea.
  volatile Object meta;
  
  // ...and the interface methods
  public void _setMeta(Object meta) { this.meta = meta; }
  public Object _getMeta() { return meta; }
}
// TreeSet variant allowing multiple elements which are considered
// equal by the comparator but not by eq().
// All operations O(log n) with n being the number of _different_ elements.
static class TreeSetWithDuplicates<A> extends AbstractSet<A> {
  NavigableSet<CompactLinkedHashSet<A>> sets;
  Comparator<A> comparator;
  int size;
  
  TreeSetWithDuplicates() { this((Comparator<A>) null); }
  
  TreeSetWithDuplicates(Comparator<A> comparator) {
  this.comparator = comparator;
    sets = new TreeSet<CompactLinkedHashSet<A>>(
      comparator == null
        ? (setA, setB) -> cmp(main.first(setA), main.first(setB))
        : (setA, setB) -> comparator.compare(main.first(setA), main.first(setB))
    );
  }
  protected TreeSetWithDuplicates(NavigableSet<CompactLinkedHashSet<A>> sets) {
  this.sets = sets;}
  
  /*swappable*/ CompactLinkedHashSet<A> makeInnerSet() {
    return new CompactLinkedHashSet();
  }
  
  public boolean add(A a) {
    var probe = probe(a);
    CompactLinkedHashSet<A> found = navigableSet_find(sets, probe);
    if (found != null) {
      if (!found.add(a)) return false;
    } else
      sets.add(probe);
    ++size;
    return true;
  }
  
  public boolean remove(Object a) {
    CompactLinkedHashSet<A> newSet = makeInnerSet();
    newSet.add((A) a);
    CompactLinkedHashSet<A> found = navigableSet_find(sets, newSet);
    if (found == null) return false;
    if (l(found) == 1)
      sets.remove(found);
    else
      found.remove(a);
    --size;
    return true;
  }
  
  A first() {
    return main.first(main.first(sets));
  }
  
  A last() {
    var last = sets.last();
    return last == null ? null : last.last();
  }
  
  public IterableIterator<A> iterator() {
    return nestedIterator(sets, __1 -> __1.iterator());
  }
  
  public int size() { return size; }
  
  // may return null
  Set<A> tiedForFirst() { return main.first(sets); }
  
  CompactLinkedHashSet<A> probe(Object a) {
    return addAndReturnCollection(makeInnerSet(), (A) a);
  }
  
  public boolean contains(Object a) {
    return navigableSet_find(sets, probe(a)) != null;
  }
}
static class RegisteredReference<A> implements IRef<A> {
  Meta owner; // all we require is a meta field
  A value;
  
  RegisteredReference() {
    //if (!dynamicObjectIsLoading()) registerRef();
  }
  
  /*void registerRef {
    vmBus_send registeringReference(this);
  }*/
  
  // Note that the single-argument constructor takes an owner, not a value
  RegisteredReference(Meta owner) {
    this(owner, null);
  }
  
  RegisteredReference(Meta owner, A value) {
  this.value = value;
  this.owner = owner;
    index();
    //registerRef();
  }
  
  // get owning object (source)
  Meta owner() { return owner; }

  // get target
  public A get() { return value; }
  boolean has() { return value != null; }
  
  boolean set(A a) {
    if (a == value) return false;
    unindex();
    value = a;
    index();
    return true;
  }
  
  void setIfEmpty(A a) {
    if (!has()) set(a);
  }
  
  void set(IRef<A> ref) { set(ref == null ? null : ref.get()); }
  void clear() { set((A) null); }
  
  // can override
  boolean validRef() { return true; }
  
  // TODO: sync all the indexing and unindexing!?
  void index() { 
    if (!validRef()) return;
    var br = lookupInterface(IHasBackRefs.class, get());
    { if (br != null) br._registerBackRef(this); }
  }

  void unindex() {
    if (!validRef()) return;
    var br = lookupInterface(IHasBackRefs.class, get());
    { if (br != null) br._unregisterBackRef(this); }
  }
  
  // not used yet
  void change() {}

  public String toString() {
    return
      
        str(value);
  }
}


static interface IHasBackRefs {
  public void _registerBackRef(IRef ref);
  public void _unregisterBackRef(IRef ref);
}
static interface IRef<A> extends IF0<A> {
  // called by the referencee to atomically replace itself
  // Passing oldValue to avoid race conditions
  public default void replaceValue(A oldValue, A newValue) {}
}
// -has fast nextElement() and prevElement()
// -design allows for more functions like reordering the list
// -Saves up to 34% in space over LinkedHashSet
//    (e.g. 22% for a set of 1,000 Ints)
static class CompactLinkedHashSet<A> extends AbstractSet<A> {
  UnsynchronizedCompactHashSet<Entry<A>> entries = new UnsynchronizedCompactHashSet();
  Entry<A> head, tail;
  
  static class Entry<A> {
    A value;
    Entry<A> prev, next;
    
    public int hashCode() {
      return main.hashCode(value);
    }
    
    // "magic" equals function for CompactHashSet lookup without temp object
    public boolean equals(Object o) {
      return o == this || eq(value, o);
    }
  }
  
  public boolean add(A a) {
    if (entries.contains(a)) return false;
    Entry<A> n = new Entry();
    n.value = a;
    n.prev = tail;
    if (tail != null) tail.next = n;
    tail = n;
    if (head == null) head = n;
    entries.add(n);
    return true;
  }
  
  public boolean remove(Object a) {
    return remove(entries.find(a));
  }
  
  public boolean remove(Entry<A> node) {
    if (node == null) return false;
    if (node.next != null) node.next.prev = node.prev; else tail = node.prev;
    if (node.prev != null) node.prev.next = node.next; else head = node.next;
    entries.remove(node);
    return true;
  }
  
  public int size() { return entries.size(); }
  
  public IterableIterator<A> iterator() {
    return new IterableIterator<A>() {
      Entry<A> entry = head;
      public boolean hasNext() { return entry != null; }
      public A next() {
        A a = entry.value;
        entry = entry.next;
        return a;
      }
    };
  }
  
  public boolean contains(Object a) {
    return entries.contains(a);
  }
  
  public A prevElement(A a) {
    Entry<A> e = entries.find(a);
    if (e == null || e.prev == null) return null;
    return e.prev.value;
  }
  
  public A nextElement(A a) {
    Entry<A> e = entries.find(a);
    if (e == null || e.next == null) return null;
    return e.next.value;
  }
  
  public A first() { return head == null ? null : head.value; }
  public A last() { return tail == null ? null : tail.value; }
}


/*
 * #!
 * Ontopia Engine
 * #-
 * Copyright (C) 2001 - 2013 The Ontopia Project
 * #-
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * !#
 */

// modified by Stefan Reich

// Implements the Set interface more compactly than
// java.util.HashSet by using a closed hashtable.

// Note: equals is always called on the _stored_ object, not the one
// passed as an argument to find(), contains() etc.
// (In case you want to put special magic in your equals() function)

static class UnsynchronizedCompactHashSet<A> extends java.util.AbstractSet<A> {
  protected final static int INITIAL_SIZE = 3;
  public final static double LOAD_FACTOR = 0.75;

  protected final static Object nullObject = new Object();
  protected final static Object deletedObject = new Object();
  protected int elements;
  protected int freecells;
  protected A[] objects;
  
  protected int modCount;
  
  
  UnsynchronizedCompactHashSet() {
    this(INITIAL_SIZE);
  }

  UnsynchronizedCompactHashSet(int size) {
    // NOTE: If array size is 0, we get a
    // "java.lang.ArithmeticException: / by zero" in add(Object).
    objects = (A[]) new Object[(size==0 ? 1 : size)];
    elements = 0;
    freecells = objects.length;
    
      modCount = 0;
    
  }

  UnsynchronizedCompactHashSet(Collection<A> c) {
    this(c.size());
    addAll(c);
  }

  @Override
  public Iterator<A> iterator() {
    return new CompactHashIterator<A>();
  }

  @Override
  public int size() {
    return elements;
  }

  @Override
  public boolean isEmpty() {
    return elements == 0;
  }

  @Override
  public boolean contains(Object o) {
    return find(o) != null;
  }
  
  A find(Object o) {
    if (o == null) o = nullObject;
    
    int hash = o.hashCode();
    int index = (hash & 0x7FFFFFFF) % objects.length;
    int offset = 1;

    // search for the object (continue while !null and !this object)
    while(objects[index] != null &&
          !(objects[index].hashCode() == hash &&
            objects[index].equals(o))) {
      index = ((index + offset) & 0x7FFFFFFF) % objects.length;
      offset = offset*2 + 1;

      if (offset == -1)
        offset = 2;
    }

    return objects[index];
  }
  
  boolean removeIfSame(Object o) {
    A value = find(o);
    if (value == o) {
      remove(value);
      return true;
    }
    return false;
  }

  @Override
  public boolean add(Object o) {
    if (o == null) o = nullObject;

    int hash = o.hashCode();
    int index = (hash & 0x7FFFFFFF) % objects.length;
    int offset = 1;
    int deletedix = -1;
    
    // search for the object (continue while !null and !this object)
    while(objects[index] != null &&
          !(objects[index].hashCode() == hash &&
            objects[index].equals(o))) {

      // if there's a deleted object here we can put this object here,
      // provided it's not in here somewhere else already
      if (objects[index] == deletedObject)
        deletedix = index;
      
      index = ((index + offset) & 0x7FFFFFFF) % objects.length;
      offset = offset*2 + 1;

      if (offset == -1)
        offset = 2;
    }
    
    if (objects[index] == null) { // wasn't present already
      if (deletedix != -1) // reusing a deleted cell
        index = deletedix;
      else
        freecells--;

      
        modCount++;
      
      elements++;

      // here we face a problem regarding generics:
      // add(A o) is not possible because of the null Object. We cant do 'new A()' or '(A) new Object()'
      // so adding an empty object is a problem here
      // If (! o instanceof A) : This will cause a class cast exception
      // If (o instanceof A) : This will work fine

      objects[index] = (A) o;
      
      // do we need to rehash?
      if (1 - (freecells / (double) objects.length) > LOAD_FACTOR)
        rehash();
      return true;
    } else // was there already 
      return false;
  }
  
  @Override
  public boolean remove(Object o) {
    if (o == null) o = nullObject;
    
    int hash = o.hashCode();
    int index = (hash & 0x7FFFFFFF) % objects.length;
    int offset = 1;
    
    // search for the object (continue while !null and !this object)
    while(objects[index] != null &&
          !(objects[index].hashCode() == hash &&
            objects[index].equals(o))) {
      index = ((index + offset) & 0x7FFFFFFF) % objects.length;
      offset = offset*2 + 1;

      if (offset == -1)
        offset = 2;
    }

    // we found the right position, now do the removal
    if (objects[index] != null) {
      // we found the object

      // same problem here as with add
      objects[index] = (A) deletedObject;
      
        modCount++;
      
      elements--;
      return true;
    } else
      // we did not find the object
      return false;
  }
  
  @Override
  public void clear() {
    elements = 0;
    for (int ix = 0; ix < objects.length; ix++)
      objects[ix] = null;
    freecells = objects.length;
    
      modCount++;
    
  }

  @Override
  public Object[] toArray() {
    Object[] result = new Object[elements];
    Object[] objects = this.objects;
    int pos = 0;
    for (int i = 0; i < objects.length; i++)
      if (objects[i] != null && objects[i] != deletedObject) {
        if (objects[i] == nullObject)
          result[pos++] = null;
        else
          result[pos++] = objects[i];
      }
    // unchecked because it should only contain A
    return result;
  }

  // not sure if this needs to have generics
  @Override
  public <T> T[] toArray(T[] a) {
    int size = elements;
    if (a.length < size)
      a = (T[])java.lang.reflect.Array.newInstance(
                                 a.getClass().getComponentType(), size);
    A[] objects = this.objects;
    int pos = 0;
    for (int i = 0; i < objects.length; i++)
      if (objects[i] != null && objects[i] != deletedObject) {
        if (objects[i] == nullObject)
          a[pos++] = null;
        else
          a[pos++] = (T) objects[i];
      }
    return a;
  }
  
  protected void rehash() {
    int garbagecells = objects.length - (elements + freecells);
    if (garbagecells / (double) objects.length > 0.05)
      // rehash with same size
      rehash(objects.length);
    else
      // rehash with increased capacity
      rehash(objects.length*2 + 1);
  }
  
  protected void rehash(int newCapacity) {
    int oldCapacity = objects.length;
    @SuppressWarnings("unchecked")
    A[] newObjects = (A[]) new Object[newCapacity];

    for (int ix = 0; ix < oldCapacity; ix++) {
      Object o = objects[ix];
      if (o == null || o == deletedObject)
        continue;
      
      int hash = o.hashCode();
      int index = (hash & 0x7FFFFFFF) % newCapacity;
      int offset = 1;

      // search for the object
      while(newObjects[index] != null) { // no need to test for duplicates
        index = ((index + offset) & 0x7FFFFFFF) % newCapacity;
        offset = offset*2 + 1;

        if (offset == -1)
          offset = 2;
      }

      newObjects[index] = (A) o;
    }

    objects = newObjects;
    freecells = objects.length - elements;
  }
  
  private class CompactHashIterator<T> implements Iterator<T> {
    private int index;
    private int lastReturned = -1;

    
      private int expectedModCount;
    

    @SuppressWarnings("empty-statement")
    public CompactHashIterator() {
        for (index = 0; index < objects.length &&
                        (objects[index] == null ||
                        objects[index] == deletedObject); index++)
          ;
        
          expectedModCount = modCount;
        
    }

    @Override
    public boolean hasNext() {
        return index < objects.length;
    }

    @SuppressWarnings("empty-statement")
    @Override
    public T next() {
        /*if (modCount != expectedModCount)
          throw new ConcurrentModificationException();*/
        int length = objects.length;
        if (index >= length) {
          lastReturned = -2;
          throw new NoSuchElementException();
        }
  
        lastReturned = index;
        for (index += 1; index < length &&
                         (objects[index] == null ||
                          objects[index] == deletedObject); index++)
          ;
        if (objects[lastReturned] == nullObject)
          return null;
        else
          return (T) objects[lastReturned];
    }

    @Override
    public void remove() {
        
          if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        
        if (lastReturned == -1 || lastReturned == -2)
          throw new IllegalStateException();
        // delete object
        if (objects[lastReturned] != null && objects[lastReturned] != deletedObject) {
          objects[lastReturned] = (A) deletedObject;
          elements--;
          
            modCount++;
            expectedModCount = modCount; // this is expected; we made the change
          
        }
    }
  }
  
  int capacity() { return objects.length; }
  
  // returns true if there was a shrink
  boolean shrinkToFactor(double factor) {
    if (factor > LOAD_FACTOR)
      throw fail("Shrink factor must be equal to or smaller than load factor: " + factor + " / " + LOAD_FACTOR);
    int newCapacity = max(INITIAL_SIZE, iround(size()/factor));
    if (newCapacity >= capacity()) return false;
    rehash(newCapacity);
    return true;
  }
}


static boolean isAbstract(Class c) {
  return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}

static boolean isAbstract(Method m) {
  return (m.getModifiers() & Modifier.ABSTRACT) != 0;
}


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


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

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


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

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


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

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



static int boostHashCombine(int a, int b) {
  return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}


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


static String dollarVarsMeanFields(String text, Object object) {
  return replaceDollarVars(text, var ->
    !hasFieldNamed(object, var) ? null : str(getOpt(object, var)));
}


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


static float colorSimilarity(RGB a, RGB b) {
  return 1-colorDistance(a, b);
}

// 0xRRGGBB - result is between 0 and 1
static float colorSimilarity(int a, int b) {
  return 1-colorDistance(a, b);
}


static int sqr(int i) {
  return i*i;
}

static long sqr(long l) {
  return l*l;
}

static double sqr(double d) {
  return d*d;
}

static float sqr(float f) {
  return f*f;
}


static void printFunctionCall(String fname, Object... args) {
  print(formatFunctionCall(fname, args));
}


static <A> WithProbability<A> withProbability1(A a) {
  return new WithProbability(1, a);
}


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


static List<String> quoteAll(Collection<String> l) {
  List<String> x = new ArrayList();
  for (String s : l)
    x.add(quote(s));
  return x;
}


static <A> ArrayList<A> toList(A[] a) { return asList(a); }
static ArrayList<Integer> toList(int[] a) { return asList(a); }
static <A> ArrayList<A> toList(Set<A> s) { return asList(s); }
static <A> ArrayList<A> toList(Iterable<A> s) { return asList(s); }


static boolean arraysEqual(Object[] a, Object[] b) {
  if (a.length != b.length) return false;
  for (int i = 0; i < a.length; i++)
    if (neq(a[i], b[i])) return false;
  return true;
}


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

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

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

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


static <A extends JComponent> void componentPopupMenu2(A component, final VF2<A, JPopupMenu> menuMaker) {
  final WeakReference < A > ref = new WeakReference<>(component);
  componentPopupMenu(component, new VF1<JPopupMenu>() { public void get(JPopupMenu menu) { try { 
    callF(menuMaker, ref.get(), menu);
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "callF(menuMaker, ref!, menu);"; }});
}





// onDrop: voidfunc(File), but may also return false
static <A extends JComponent> A jHandleFileDrop(A c, final Object onDrop) {
  new DropTarget(c, new DropTargetAdapter() {
    public void drop(DropTargetDropEvent e) {
      try {
        Transferable tr = e.getTransferable();
        DataFlavor[] flavors = tr.getTransferDataFlavors();
        for (DataFlavor flavor : flavors) {
          if (flavor.isFlavorJavaFileListType()) {
            e.acceptDrop(e.getDropAction());
            File file = first((List<File>) tr.getTransferData(flavor));
            if (file != null && !isFalse(callF(onDrop, file)))
              e.dropComplete(true);
            return;
          }
        }
      } catch (Throwable __e) { _handleException(__e); }
      e.rejectDrop();
    }
  });
  return c;
}

static <A extends JComponent> A jHandleFileDrop(Object onDrop, A c) {
  return jHandleFileDrop(c, onDrop);
}


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

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

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

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

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

static void addMenuItem(JMenuBar menuBar, String text, Runnable action) {
  addMenuItem(menuBar, jmenuItem(text, action));
}

static void addMenuItem(JMenuBar menuBar, JMenuItem menuItem) {
  addDirectMenuItem(menuBar, menuItem);
}


static JFrame showFullScreen(JComponent c) {
  return showFullScreen(defaultFrameTitle(), c);
}

static JFrame showFullScreen(final String title, final JComponent c) {
  return (JFrame) swingAndWait(new F0<Object>() { public Object get() { try { 
    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
      .getDefaultScreenDevice();
    if (!gd.isFullScreenSupported())
      throw fail("No full-screen mode supported!");
    boolean dec = JFrame.isDefaultLookAndFeelDecorated();
    if (dec) JFrame.setDefaultLookAndFeelDecorated(false);
    final JFrame window = new JFrame(title);
    window.setUndecorated(true);
    if (dec) JFrame.setDefaultLookAndFeelDecorated(true);
    registerEscape(window, new Runnable() {  public void run() { try {  disposeWindow(window) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "disposeWindow(window)"; }});
    window.add(wrap(c));
    gd.setFullScreenWindow(window);
    
    // Only this hides the task bar in Peppermint Linux w/Substance
    for (int i = 100; i <= 1000; i += 100)
      awtLater(i, new Runnable() {  public void run() { try {  window.toFront() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "window.toFront()"; }});
    
    return window;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()\r\n      ..."; }});
}


static void selectFile(final String msg, VF1<File> action) {
  selectFile(msg, userDir(), action);
}

static void selectFile(final String msg, final File defaultFile, VF1<File> action) {
  inputFilePath(msg, defaultFile, action);
}


static void saveImage(File f, BufferedImage img) {
  if (hasJPEGExtension(f))
    saveJPG(f, img);
  else
    savePNG(f, img);
}


static <A extends Image> A copyImageToClipboard(A img) {
  TransferableImage trans = new TransferableImage(img);
  Toolkit.getDefaultToolkit().getSystemClipboard().setContents( trans, null);
  vmBus_send("newClipboardContents", img);
  print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
  return img;
}



static JComponent selectImageSnippet(VF1<String> onSelect) {
  return selectSnippetID_v1(onSelect);
}



static JComponent selectImageSnippet(String defaultID, VF1<String> onSelect) {
  return selectSnippetID_v1(defaultID, onSelect);
}


static BufferedImage cloneClipBufferedImage(BufferedImage src, Rectangle clip) {
  return cloneBufferedImage(clipBufferedImage(src, clip));
}

static BufferedImage cloneClipBufferedImage(BufferedImage src, Rect r) {
  return cloneBufferedImage(clipBufferedImage(src, r));
}

static BufferedImage cloneClipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
  return cloneBufferedImage(clipBufferedImage(src, x, y, w, h));
}






static BufferedImage getImageFromClipboard() { try {
  Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
  if (t == null) return null;
  
  List<File> l =  (List<File>) (getTransferData(t, DataFlavor.javaFileListFlavor));
  if (nempty(l))
    return loadImage2(first(l));
  
  if (t.isDataFlavorSupported(DataFlavor.imageFlavor))
    return (BufferedImage) t.getTransferData(DataFlavor.imageFlavor);
  return imageFromDataURL(getTextFromClipboard());
} catch (Exception __e) { throw rethrow(__e); } }


static void popup(final Throwable throwable) {
  popupError(throwable);
}

static void popup(final String msg) {
  print(msg);
  SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      JOptionPane.showMessageDialog(null, msg);
    }
  });
}


static <A> A _print(String s, A a) {
  return print(s, a);
}

static <A> A _print(A a) {
  return print(a);
}

static void _print() {
  print();
}


static boolean hasTransparency(BufferedImage img) {
  return img.getColorModel().hasAlpha();
}


static BufferedImage resizeImage(BufferedImage img, int newW, int newH) {
  return resizeImage(img, newW, newH, Image.SCALE_SMOOTH);
}

static BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) {
  if (newW == img.getWidth() && newH == img.getHeight()) return img;
  Image tmp = img.getScaledInstance(newW, newH, scaleType);
  BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
  Graphics2D g2d = dimg.createGraphics();
  g2d.drawImage(tmp, 0, 0, null);
  g2d.dispose();
  return dimg;
}

static BufferedImage resizeImage(BufferedImage img, int newW) {
  int newH = iround(img.getHeight()*(double) newW/img.getWidth());
  return resizeImage(img, newW, newH);
}

static BufferedImage resizeImage(int newW, BufferedImage img) {
  return resizeImage(img, newW);
}


static <A extends Component> A repaint(A c) {
  if (c != null) c.repaint();
  return c;
}


static Dimension getMinimumSize(final Component c) {
  return c == null ? null : swing(new F0<Dimension>() { public Dimension get() { try {  return c.getMinimumSize();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret c.getMinimumSize();"; }});
}


static boolean imagesHaveSameSize(BufferedImage a, BufferedImage b) {
  return a != null && b != null && a.getWidth() == b.getWidth()
    && a.getHeight() == b.getHeight();
}


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


static Container getParent(final Component c) {
  return c == null ? null : swing(new F0<Container>() { public Container get() { try {  return c.getParent();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret c.getParent();"; }});
}


static Rectangle toRectangle(Rect r) {
  return r == null ? null : r.getRectangle();
}


static JScrollPane enclosingScrollPane(Component c) {
  while (c.getParent() != null && !(c.getParent() instanceof JViewport) && c.getParent().getComponentCount() == 1) c = c.getParent(); // for jscroll_center
  if (!(c.getParent() instanceof JViewport)) return null;
  c = c.getParent().getParent();
  return c instanceof JScrollPane ? (JScrollPane) c : null;
}


// independent timer
static void awtLater(int delay, final Object r) {
  swingLater(delay, r);
}

static void awtLater(Object r) {
  swingLater(r);
}

// dependent timer (runs only when component is visible)
static void awtLater(JComponent component, int delay, Object r) {
  installTimer(component, r, delay, delay, false);
}

static void awtLater(JFrame frame, int delay, Object r) {
  awtLater(frame.getRootPane(), delay, r);
}


static ImageSurface showFullScreenImageSurface(BufferedImage img) {
  ImageSurface is = jImageSurface(img);
  showFullScreen(jscroll_centered(disposeFrameOnClick(is)));
  return is;
}


static void fillArrayUnlessZero(byte[] a, byte value) {
  if (value != 0) Arrays.fill(a, value);
}

static void fillArrayUnlessZero(int[] a, int value) {
  if (value != 0) Arrays.fill(a, value);
}

static void fillArrayUnlessZero(float[] a, float value) {
  if (value != 0) Arrays.fill(a, value);
}


static boolean inRange(int x, int n) {
  return x >= 0 && x < n;
}

static boolean inRange(int x, int a, int b) {
  return x >= a && x < b;
}


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


static int limitToUByte(int i) {
  return max(0, min(255, i));
}


static File loadLibrary(String snippetID) {
  return loadBinarySnippet(snippetID);
}


// TODO: use actualUserHome()?
// (there was a problem with onLocallyInferiorJavaX() always triggering inside #1013896)

static File pathToJavaxJar() {
  
  IResourceLoader rl = vm_getResourceLoader();
  if (rl != null)
    return rl.pathToJavaXJar();
  
  
  return pathToJavaxJar_noResourceLoader();
}
  
static File pathToJavaxJar_noResourceLoader() { try {
  int x = latestInstalledJavaX();
  File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar");
  if (!xfile.isFile()) {
    print("Saving " + f2s(xfile));
    String url = x30JarServerURL();
    byte[] data = loadBinaryPage(url);
    if (data.length < 1000000)
      throw fail("Could not load " + url);
    saveBinaryFile(xfile.getPath(), data);
  }
  return xfile;
} catch (Exception __e) { throw rethrow(__e); } }


static int getWidth(Component c) {
  return c == null ? 0 : (int) swingCall(c, "getWidth");
}


static int getHeight(Component c) {
  return c == null ? 0 : (int) swingCall(c, "getHeight");
}


static String shortClassName_dropNumberPrefix(Object o) {
  return dropNumberPrefix(shortClassName(o));
}


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


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


static UnsupportedOperationException unsupportedOperation() {
  throw new UnsupportedOperationException();
}


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

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


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

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

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




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


static <A, B> LinkedHashMap<A, B> cloneLinkedHashMap(Map<A, B> map) {
  return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
}


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

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

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


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



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




static char second(String s) {
  return charAt(s, 1);
}




static long longMul(long a, long b) {
  return a*b;
}


static BufferedImage toBufferedImage(Object o) {
  return toBufferedImageOpt(o);
}


static int[] pixelsOfBufferedImage(BufferedImage image) { try {
  int width = image.getWidth();
  int height = image.getHeight();
  int[] pixels = new int[width*height];
  PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
  if (!pixelGrabber.grabPixels())
    throw fail("Could not grab pixels");
  return pixels;
} catch (Exception __e) { throw rethrow(__e); } }


static double averageBrightness(BufferedImage img) {
  return new BWImage(img).averageBrightness();
}


static BufferedImage integralImageToBufferedImage(IntegralImage img) {
  if (img == null) return null;
  int w = img.w, h = img.h;
  BufferedImage out = newBufferedImage(w, h);
  for (int y = 0; y < h; y++)
    for (int x = 0; x < w; x++)
      out.setRGB(x, y, ii_getPixel(img, x, y));
  return out;
}


static Object[] litobjectarray(Object... l) {
  return litObjectArray(l);
}


static int ifloor(double d) {
  return (int) Math.floor(d);
}



  static float clampZeroToOne(float x) {
    return x < 0 ? 0 : x > 1 ? 1 : x;
  }


  static double clampZeroToOne(double x) {
    return x < 0 ? 0 : x > 1 ? 1 : x;
  }




static void arrayCopy(Object[] a, Object[] b) {
  arraycopy(a, b);
}



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


static Rect rectMinSize(int minW, int minH, Rect r) {
  return r == null || r.w >= minW && r.h >= minH ? r
    : rect(r.x, r.y, max(r.w, minW), max(r.h, minH));
}


static Rect toRect_floor(DoubleRect r) {
  if (r == null) return null;
  int x = ifloor(r.x), y = ifloor(r.y);
  return new Rect(x, y, ifloor(r.x2())-x, ifloor(r.y2())-y);
}


static DoubleRect doubleRectFromRanges(DoubleRange x, DoubleRange y) {
  return new DoubleRect(x.start, y.start, x.length(), y.length());
}


static int rectArea(Rect r) {
  return r == null ? 0 : r.w*r.h;
}



  static double ii_averageBrightnessOfArea(IIntegralImage img, int x1, int y1, int x2, int y2) {
    return doubleRatio(img.rectSum(x1, y1, x2, y2), (x2-x1)*(y2-y1)*3);
  }
  
  static double ii_averageBrightnessOfArea(IIntegralImage img, int x1, int y1, int x2, int y2, int channel) {
    return doubleRatio(img.rectSum(x1, y1, x2, y2, channel), (x2-x1)*(y2-y1));
  }
  
  static double ii_averageBrightnessOfArea(IIntegralImage img, Rect r) {
    return ii_averageBrightnessOfArea(img, r.x, r.y, r.x2(), r.y2());
  }
  
  static double ii_averageBrightnessOfArea(IIntegralImage img, Rect r, int channel) {
    return ii_averageBrightnessOfArea(img, r.x, r.y, r.x2(), r.y2(), channel);
  }


  static double ii_averageBrightnessOfArea(IntegralImage img, int x1, int y1, int x2, int y2) {
    return doubleRatio(img.rectSum(x1, y1, x2, y2), (x2-x1)*(y2-y1)*3);
  }
  
  static double ii_averageBrightnessOfArea(IntegralImage img, int x1, int y1, int x2, int y2, int channel) {
    return doubleRatio(img.rectSum(x1, y1, x2, y2, channel), (x2-x1)*(y2-y1));
  }
  
  static double ii_averageBrightnessOfArea(IntegralImage img, Rect r) {
    return ii_averageBrightnessOfArea(img, r.x, r.y, r.x2(), r.y2());
  }
  
  static double ii_averageBrightnessOfArea(IntegralImage img, Rect r, int channel) {
    return ii_averageBrightnessOfArea(img, r.x, r.y, r.x2(), r.y2(), channel);
  }




static double transformBetweenDoubleRanges(double x, DoubleRange src, DoubleRange dest) {
  return dest.start+dest.length()*doubleRatio(x-src.start, src.length());
}

static DoubleRange transformBetweenDoubleRanges(DoubleRange r, DoubleRange src, DoubleRange dest) {
  return r == null ? null :
    new DoubleRange(transformBetweenDoubleRanges(r.start, src, dest),
      transformBetweenDoubleRanges(r.end, src, dest));
}


static DoubleRange zeroToOne_value = new DoubleRange(0, 1);

static DoubleRange zeroToOne() {
  return zeroToOne_value;
}


static RGB rgb(String s) {
  return new RGB(s);
}

static RGB rgb(double r, double g, double b) {
  return new RGB((float) r, (float) g, (float) b);
}


static String formatDoubleX(double d, int digits) {
  return formatDoubleFull(d, digits);
}


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

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



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


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



static DoubleRange doubleRange(double start, double end) {
  return new DoubleRange(start, end);
}


static float abs(float f) { return Math.abs(f); }
static int abs(int i) { return Math.abs(i); }
static double abs(double d) { return Math.abs(d); }


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

static void set(Class c, String field, Object value) {
  if (c == null) return;
  try {
    Field f = set_findStaticField(c, field);
    makeAccessible(f);
    smartSet(f, null, value);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
  
static Field set_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}

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

static void set(BitSet bs, int idx) {
  { if (bs != null) bs.set(idx); }
}


static void setPixel(BufferedImage img, Pt p, Color color) {
  { if (img != null) img.setRGB(p.x, p.y, colorToIntOpaque(color)); }
}


static Class<?> getClass(String name) {
  return _getClass(name);
}

static Class getClass(Object o) {
  return _getClass(o);
}

static Class getClass(Object realm, String name) {
  return _getClass(realm, name);
}


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

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

static <A, B> B remove(Map<A, B> map, Object a) {
  return map == null ? null : map.remove(a);
}


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


static int stdHash2(Object a) {
  if (a == null) return 0;
  return stdHash(a, toStringArray(allFields(a)));
}


static int cmp(Number a, Number b) {
  return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}

static int cmp(double a, double b) {
  return a < b ? -1 : a == b ? 0 : 1;
}

static int cmp(int a, int b) {
  return a < b ? -1 : a == b ? 0 : 1;
}

static int cmp(long a, long b) {
  return a < b ? -1 : a == b ? 0 : 1;
}

static int cmp(Object a, Object b) {
  if (a == null) return b == null ? 0 : -1;
  if (b == null) return 1;
  return ((Comparable) a).compareTo(b);
}


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

// map: func(key, value) -> list element
static List syncMap(Map map, Object f) {
  return map(cloneLinkedHashMap(map), f); // TODO: use a temporary list instead
}

static <A, B> Map<A, B> syncMap() {
  return synchroHashMap();
}

static <A, B> Map<A, B> syncMap(Map map) {
  return synchronizedMap(map);
}


static String formatDouble3X(double d) {
  return formatDoubleX(d, 3);
}



static String formatDouble3(double d) {
  return formatDouble(d, 3);
}



static <A> WithProbability<A> withProbability(double probability, A a) {
  return new WithProbability(probability, a);
}


static String toString(Object o) {
  return strOrNull(o);
}


static <A> String pnlToString(String prefix, Iterable<A> l) {
  return hijackPrint(new Runnable() {  public void run() { try {  pnl(prefix, l) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pnl(prefix, l)"; }});
}

static <A> String pnlToString(final Iterable<A> l) {
  return hijackPrint(new Runnable() {  public void run() { try {  pnl(l) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pnl(l)"; }});
}

static <A> String pnlToString(final A[] l) {
  return hijackPrint(new Runnable() {  public void run() { try {  pnl(l) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pnl(l)"; }});
}

static <A, B> String pnlToString(final Map<A, B> map) {
  return hijackPrint(new Runnable() {  public void run() { try {  pnl(map) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pnl(map)"; }});
}


static <A, B> String pnlToString(MultiMap<A, B> map) {
  return pnlToString(multiMapToMap(map));
}



static <A, B, C> List<C> mapToList(Map<A, B> map, IF2<A, B, C> f) {
  return map(map, f);
}


static int rgbInt(int r, int g, int b) {
  return (clamp(r, 0, 255) << 16) | (clamp(g, 0, 255) << 8) | clamp(b, 0, 255);
}


static int asInt(Object o) {
  return toInt(o);
}


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


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



static <A extends JComponent> A setDoubleBuffered(A c, boolean b) {
  { swing(new Runnable() {  public void run() { try {  { if (c != null) c.setDoubleBuffered(b); } 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "c?.setDoubleBuffered(b);"; }}); }
  return c;
}


static Color getBackground(final Component c) {
  return c == null ? null : swing(new F0<Color>() { public Color get() { try {  return c.getBackground();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret c.getBackground();"; }});
}


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

static BufferedImage clipBufferedImage(BufferedImage src, Rect r) {
  if (src == null || r == null) return null;
  // fixClipRect
  r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight()));
  if (rectEmpty(r)) return null; // can't make zero-sized BufferedImage
    
  return src.getSubimage(r.x, r.y, r.w, r.h);
}

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



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

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


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



static void stepAll(Steppable s) {
  if (s != null) while  (s.step()) { ping(); }
}



static void stepMax(int max, Steppable s) {
  if (s == null) return;
  while  (max-- > 0 && s.step()) { ping(); }
}

static void stepMax(Steppable s, int max) {
  stepMax(max, s);
}


static String nEntries(long n) { return n2(n, "entry", "entries"); }
static String nEntries(Collection l) { return nEntries(l(l)); }
static String nEntries(Map map) { return nEntries(l(map)); }


static boolean containsInstance(Iterable i, Class c) {
  if (i != null) for (Object o : i)
    if (isInstanceX(c, o))
      return true;
  return false;
}


static String formatDouble_noLeadingZero(double d, int digits) {
  String s = formatDouble(d, digits);
  if (startsWith(s, "-"))
    return startsWith(s, "-0.") ? "-." + dropFirst(3, s) : s;
  else
    return startsWith(s, "0.") ? dropFirst(s) : s;
}



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


static <A> A navigableSet_find(NavigableSet<A> set, A a) {
  if (set == null || a == null) return null;
  A b = set.floor(a);
  return b != null && sortedSet_compare(set, a, b) == 0 ? b : null;
}


// TODO: clean up these type signatures?

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(final Iterable<A> c, final F1<A, C> makeInnerIterator) {
  return nestedIterator(iterator(c), makeInnerIterator);
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(Collection<A> c, final IF1<A, C> makeInnerIterator) {
  return nestedIterator(iterator(c), makeInnerIterator);
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(Iterator<A> it1, IF1<A, C> makeInnerIterator) {
  return nestedIterator(it1, toF1(makeInnerIterator));
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(final Iterator<A> it1, final F1<A, C> makeInnerIterator) {
  if (it1 == null || !it1.hasNext()) return emptyIterableIterator();
  return iff(new F0() {
    A a;
    Iterator<B> innerIterator;
    
    { nextOuter(); }
    
    void nextOuter() {
      a = it1.next();
      innerIterator = makeInnerIterator.get(a);
    }
    
    public Object get() {
      while (true) { ping();
        if (innerIterator != null && innerIterator.hasNext())
          return innerIterator.next();
        if (!it1.hasNext()) return endMarker();
        nextOuter();
      }
    }
  });
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(IF1<A, C> makeInnerIterator, Iterator<A> it1) {
  return nestedIterator(it1, makeInnerIterator);
}

static <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(IF1<A, C> makeInnerIterator, Collection<A> l) {
  return nestedIterator(l, makeInnerIterator);
}


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


static boolean has(String a, String b, String c) {
  
  return false;
}

static boolean has(T3<String, String, String> t) {
  
  return false;
}


// We even allow overriding existing interface implementations
static <A> A lookupInterface(Class<A> intrface, Object o) {
  return lookupDynamicInterface(intrface, o);
}




static <A> A lookupInterface(Object o, Class<A> intrface) {
  return lookupDynamicInterface(o, intrface);
}


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

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

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



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


static String find(String pattern, String text) {
  Matcher matcher = Pattern.compile(pattern).matcher(text);
  if (matcher.find())
    return matcher.group(1);
  return null;
}

static <A> A find(Collection<A> c, Object... data) {
  for (A x : c)
    if (checkFields(x, data))
      return x;
  return null;
}




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



static String replaceDollarVars(String s, Object... params) {
  if (empty(params)) return s;
  Map<String, Object> vars = mapKeys(__42 -> dropDollarPrefix(__42), (Map<String, Object>) litcimap(params));
  return replaceDollarVars_dyn(s, var -> strOrNull(vars.get(var)));
}

static String replaceDollarVars(String s, IF1<String, String> f) {
  return replaceDollarVars_dyn(s, f);
}


static boolean hasFieldNamed(Object o, String field) {
  return hasField(o, field);
}


static float colorDistance(RGB a, RGB b) {
  return rgbDiff(a, b);
}



// 0xRRGGBB - result is between 0 and 1
static float colorDistance(int a, int b) {
  return rgbDiff(a, b);
}


static String formatFunctionCall(String fname, Object... args) {
  return fname + "(" + joinWithComma(allToString(args)) + ")";
}

static String formatFunctionCall(String fname, List args) {
  return formatFunctionCall(fname, toObjectArray(args));
}


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


static void addDirectMenuItem(JMenuBar mb, String text, Object action) {
  if (mb != null) { swing(new Runnable() {  public void run() { try { 
    addDirectMenuItem(mb, directJMenuItem(text, action));
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "addDirectMenuItem(mb, directJMenuItem(text, action));"; }}); }
}

static void addDirectMenuItem(Component c, String text, Object action) {
  addDirectMenuItem(addMenuBar(c), text, action);
}

static void addDirectMenuItem(JMenuBar mb, JMenuItem menuItem) {
  if (mb != null) { swing(new Runnable() {  public void run() { try { 
    mb.add(menuItem);
    revalidate(mb);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "mb.add(menuItem);\r\n    revalidate(mb);"; }}); }
}


static String defaultFrameTitle() {
  return autoFrameTitle();
}

static void defaultFrameTitle(String title) {
  autoFrameTitle_value = title;
}


static void registerEscape(JFrame frame, final Runnable r) {
  registerEscape_rootPane(frame.getRootPane(), r);
}


static void disposeWindow(final Window window) {
  if (window != null) { swing(new Runnable() {  public void run() { try { 
    window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // call listeners
    myFrames_list.remove(window);
    window.dispose();
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //..."; }}); }
}

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

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

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


static void inputFilePath(final String msg, final Object action) {
  inputFilePath(msg, userDir(), action);
}

// action: voidfunc(File)
static void inputFilePath(final String msg, final File defaultFile, final Object action) {
  swingLater(new Runnable() {  public void run() { try { 
    final JTextField tfPath = jtextfield(f2s(or(defaultFile, userDir())));
    String title = joinStrings(" | ", msg, programName());
    JComponent form = showFormTitled(title,
      unnull(msg), centerAndEast(tfPath, jbutton("Browse...", new Runnable() {  public void run() { try { 
        JFileChooser fileChooser = new JFileChooser(getTextTrim(tfPath));
        if (fileChooser.showOpenDialog(tfPath) == JFileChooser.APPROVE_OPTION) {
          tfPath.setText(fileChooser.getSelectedFile().getAbsolutePath());
          tfPath.requestFocus();
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "JFileChooser fileChooser = new JFileChooser(getTextTrim(tfPath));\r\n        if..."; }})), new Runnable() {  public void run() { try { 
        callF(action, new File(getTextTrim(tfPath)))
      ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "callF(action, new File(getTextTrim(tfPath)))"; }});
    renameSubmitButton(form, "OK");
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "final JTextField tfPath = jtextfield(f2s(or(defaultFile, userDir())));\r\n    S..."; }});
}


static boolean hasJPEGExtension(File f) {
  return ewicOneOf(fileName(f), ".jpg", ".jpeg");
}


static void saveJPG(BufferedImage img, File file) { try {
  if (!ImageIO.write(img, "jpeg", mkdirsFor(file))) {
    print("Reconstructing image for saving JPEG");
    img = reconstructBufferedImage(img);
    if (!ImageIO.write(img, "jpeg", file))
      throw fail("Couldn't write JPEG: " + file + " (" + img + ")");
  }
  vmBus_send("wroteFile", file);
} catch (Exception __e) { throw rethrow(__e); } }

static void saveJPG(File file, BufferedImage img) { try {
  saveJPG(img, file);
} catch (Exception __e) { throw rethrow(__e); } }


static void savePNG(BufferedImage img, File file) { try {
  File tempFile = new File(file.getPath() + "_temp");
  CriticalAction ca = beginCriticalAction("Save " + f2s(file));
  try {
    ImageIO.write(img, "png", mkdirsFor(tempFile));
    file.delete();
    tempFile.renameTo(file);
  } finally {
    ca.done();
  }
} catch (Exception __e) { throw rethrow(__e); } }

// gotta love convenience & program-smartness
static void savePNG(File file, BufferedImage img) {
  savePNG(img, file);
}


static void savePNG(File file, RGBImage img) {
  savePNG(file, img.getBufferedImage());
}



static JComponent selectSnippetID_v1(final VF1<String> onSelect) {
  return selectSnippetID_v1("#", onSelect);
}

static JComponent selectSnippetID_v1(String defaultID, final VF1<String> onSelect) {
  final JTextField tfSnippetID = jtextfield(defaultID);
  if (eq(defaultID, "#")) moveCaretToEnd(tfSnippetID);
  
  JComponent panel;
  renameSubmitButton(panel = showTitledForm("Select Snippet",
    "Snippet ID:", tfSnippetID, runnableThread(new Runnable() {  public void run() { try { 
      callF(onSelect, fsI(getTextTrim(tfSnippetID)));
    
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "callF(onSelect, fsI(getTextTrim(tfSnippetID)));"; }})), "Select snippet");
  return panel;
}


static BufferedImage cloneBufferedImage(BufferedImage image) {
  return copyImage(image);
}


static Object getTransferData(Transferable t, DataFlavor flavor) { try {
  return t != null && t.isDataFlavorSupported(flavor) ? t.getTransferData(flavor) : null;
} catch (Exception __e) { throw rethrow(__e); } }


static BufferedImage imageFromDataURL(String url) {
  String pref = "base64,";
  int i = indexOf(url, pref);
  if (i < 0) return null;
  return decodeImage(base64decode(substring(url, i+l(pref))));
}





static String getTextFromClipboard() { try {
  Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
  if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor))
    return (String) transferable.getTransferData(DataFlavor.stringFlavor);
  return null;
} catch (Exception __e) { throw rethrow(__e); } }


  static void popupError(final Throwable throwable) {
    throwable.printStackTrace(); // print stack trace to console for the experts
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        String text = throwable.toString();
        //text = cutPrefix(text, "java.lang.RuntimeException: ");
        JOptionPane.showMessageDialog(null, text);
      }
    });
  }






// first delay = delay
static Timer installTimer(JComponent component, Object r, long delay) {
  return installTimer(component, r, delay, delay);
}

// first delay = delay
static Timer installTimer(RootPaneContainer frame, long delay, Object r) {
  return installTimer(frame.getRootPane(), r, delay, delay);
}

// first delay = delay
static Timer installTimer(JComponent component, long delay, Object r) {
  return installTimer(component, r, delay, delay);
}

static Timer installTimer(JComponent component, long delay, long firstDelay, Object r) {
  return installTimer(component, r, delay, firstDelay);
}

static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
  return installTimer(component, r, delay, firstDelay, true);
}

static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
  if (component == null) return null;
  return (Timer) swingAndWait(new F0<Object>() { public Object get() { try { 
    final Var<Timer> timer = new Var();
    timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
       AutoCloseable __1 = tempActivity(r); try {
      try {
        if (!allPaused())
          if (isFalse(callF(r)))
            cancelTimer(timer.get());
      } catch (Throwable __e) { _handleException(__e); }
    } finally { _close(__1); }} catch (Throwable __e) { messageBox(__e); }}}));
    timer.get().setInitialDelay(toInt(firstDelay));
    timer.get().setRepeats(repeats);
    bindTimerToComponent(timer.get(), component);
    return timer.get();
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "final new Var<Timer> timer;\r\n    timer.set(new Timer(toInt(delay), actionList..."; }});
}

static Timer installTimer(RootPaneContainer frame, long delay, long firstDelay, Object r) {
  return installTimer(frame.getRootPane(), delay, firstDelay, r);
}



static ImageSurface jImageSurface() {
  return swingNu(ImageSurface.class);
}

// for BWImage
static ImageSurface jImageSurface(MakesBufferedImage img) {
  return swingNu(ImageSurface.class, img.getBufferedImage());
}

static ImageSurface jImageSurface(BufferedImage img) {
  return swingNu(ImageSurface.class, img);
}


static JScrollPane jscroll_centered(Component c) {
  return jscroll(jFullCenter(c));
}


static <A extends JComponent> A disposeFrameOnClick(final A c) {
  onClick(c, new Runnable() {  public void run() { try {  disposeFrame(c) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "disposeFrame(c)"; }});
  return c;
}


static int latestInstalledJavaX() {
  File[] files = new File(userHome(), ".javax").listFiles();
  int v = 0;
  if (files != null) for (File f : files) {
    Matcher m = regexpMatcher("x(\\d\\d\\d?)\\.jar", f.getName());
    if (m.matches())
      v = Math.max(v, Integer.parseInt(m.group(1)));
  }
  return v;
}


static String x30JarServerURL() {
  return "http://botcompany.de:8081/x30.jar";
}


static Object swingCall(final Object o, final String method, final Object... args) {
  return swing(new F0<Object>() { public Object get() { try {  return call(o, method, args);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret call(o, method, args);"; }});
}


static String dropNumberPrefix(String s) {
  return dropFirst(s, indexOfNonDigit(s));
}


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


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

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

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

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


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


static BufferedImage toBufferedImageOpt(Object o) {
  if (o instanceof BufferedImage) return (BufferedImage) o;
  if (o instanceof MakesBufferedImage)
    return ((MakesBufferedImage) o).getBufferedImage();
  if (o instanceof File)
    if (isImageFile(((File) o)))
      return loadBufferedImageFile(((File) o));
  String c = getClassName(o);
  
  // Keep this because it also works on imported objects
  if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
    return (BufferedImage) call(o, "getBufferedImage");
    
  if (eq(c, "main$PNGFile"))
    return (BufferedImage) call(o, "getImage");
  return null;
}


// undefined color, seems to be all black in practice
static BufferedImage newBufferedImage(int w, int h) {
  return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}


static BufferedImage newBufferedImage(int w, int h, RGB rgb) {
  return newBufferedImage(w, h, rgb.getColor());
}


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


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



// assumes coordinates are in range
static int ii_getPixel(IntegralImage img, int x, int y) {
  if (img == null) return 0;
  int r = iround(img.rectSum(x, y, x+1, y+1, 0));
  int g = iround(img.rectSum(x, y, x+1, y+1, 1));
  int b = iround(img.rectSum(x, y, x+1, y+1, 2));
  return rgbInt(r, g, b);
}


static Object[] litObjectArray(Object... l) {
  return l;
}


static Rect rect(int x, int y, int w, int h) {
  return new Rect(x, y, w, h);
}

static Rect rect(Pt p, int w, int h) {
  return new Rect(p.x, p.y, w, h);
}

static Rect rect(int w, int h) {
  return new Rect(0, 0, w, h);
}




static String formatDoubleFull(double d, int digits) {
  String format = digits <= 0 ? "0" : "0." + rep(digits, '0');
  return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d);
}



static int colorToIntOpaque(Color c) {
  return c.getRGB() | 0xFF000000;
}


static Map<Class, Set<String>> allFields_cache = weakHashMap();

static Set<String> allFields(Object o) {
  if (o == null) return emptySet();
  Class _c = _getClass(o);
  Set<String> fields = allFields_cache.get(_c);
  if (fields == null)
    allFields_cache.put(_c, fields = asTreeSet(keys(getOpt_getFieldMap(o))));
  return fields;
}


static int stdHash(Object a, String... fields) {
  if (a == null) return 0;
  int hash = getClassName(a).hashCode();
  for (String field : fields)
    hash = boostHashCombine(hash, hashCode(getOpt(a, field)));
  return hash;
}


static String formatDouble(double d, int digits) {
  String format = digits <= 0 ? "0" : "0." + rep(digits, '#');
  return decimalFormatEnglish(format, d);
}



static String hijackPrint(Runnable r) {
  return hijackPrint((Object) r);
}

static String hijackPrint(Object r) {
  final StringBuilder buf = new StringBuilder();
  Object old = interceptPrintInThisThread(new F1<String, Boolean>() {
    public Boolean get(String s) {
      buf.append(s);
      return false;
    }
  });
  try {
    callF(r);
    return str(buf);
  } finally {
    interceptPrintInThisThread(old);
  }
}


static <A extends Iterable> A pnl(A l) { return pnl("", l); }
static <A extends Iterable> A pnl(String prefix, A l) {
  printNumberedLines(prefix, l);
  return l;
}

static <A> A[] pnl(A[] l) { return pnl("", l); }
static <A> A[] pnl(String prefix, A[] l) {
  printNumberedLines(prefix, l);
  return l;
}

static <A extends Map> A pnl(A map) {
  printNumberedLines(map);
  return map;
}

static <A extends Map> A pnl(String prefix, A map) {
  printNumberedLines(prefix, map);
  return map;
}

static String pnl(String s) {
  printNumberedLines(lines(s));
  return s;
}




static <A, B> MultiMap<A, B> pnl(MultiMap<A, B> mm) {
  pnl(mm == null ? null : mm.asMap());
  return mm;
}



static <A, B> Map<A, List<B>> multiMapToMap(MultiMap<A, B> m) {
  return m == null ? null : m.data;
}


static float clamp(float x, float a, float b) {
  return x < a ? a : x > b ? b : x;
}

static double clamp(double x, double a, double b) {
  return x < a ? a : x > b ? b : x;
}

static int clamp(int x, int a, int b) {
  return x < a ? a : x > b ? b : x;
}

static long clamp(long x, long a, long b) {
  return x < a ? a : x > b ? b : x;
}


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


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


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


static void addToContainer(Container a, Component... b) {
  if (a == null) return;
  { swing(new Runnable() {  public void run() { try { 
    for (Component c : unnullForIteration(b))
      if (c != null) 
        a.add(c);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "for (Component c : unnullForIteration(b))\r\n      if (c != null) \r\n        a.a..."; }}); }
}


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

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

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

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

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

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

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

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




static <A> int sortedSet_compare(SortedSet<A> set, A a, A b) {
  return compareWithComparator(set.comparator(), a, b);
}


static F1 toF1(final Object f) {
  return functionToF1(f);
}


static IterableIterator emptyIterableIterator_instance = new IterableIterator() {
  public Object next() { throw fail(); }
  public boolean hasNext() { return false; }
};

static <A> IterableIterator<A> emptyIterableIterator() {
  return emptyIterableIterator_instance; 
}


// f: func -> A | endMarker
static <A> IterableIterator<A> iff(Object f) {
  return iteratorFromFunction_withEndMarker(f);
}

// can't use type parameter because end marker
static IterableIterator iff(F0 f) {
  return iteratorFromFunction_withEndMarker(f);
}

static <A> IterableIterator iff(IF0 f) {
  return iteratorFromFunction_withEndMarker(f);
}


static Object endMarker() {
  return iteratorFromFunction_endMarker;
}


// We even allow overriding existing interface implementations
static <A> A lookupDynamicInterface(Class<A> intrface, Object o) {
  if (o instanceof DynamicObject)
    { A a =  (A) (mapGet((Map) ((DynamicObject) o).fieldValues, intrface)); if (a != null) return a; }
  if (isInstance(intrface, o)) return (A) o;
  return null;
}


static <A> A lookupDynamicInterface(Object o, Class<A> intrface) {
  return lookupDynamicInterface(intrface, o);
}


static boolean checkFields(Object x, Object... data) {
  for (int i = 0; i < l(data); i += 2)
    if (neq(getOpt(x, (String) data[i]), data[i+1]))
      return false;
  return true;
}




// requires ugly casting when used (O -> A)
static Object iteratorFromFunction_endMarker = new Object();

// f: func -> A | endMarker
static <A> IterableIterator<A> iteratorFromFunction_withEndMarker(final Object f) {
  class IFF extends IterableIterator<A> {
    A a;
    boolean have, done;
    
    public boolean hasNext() {
      getNext();
      return !done;
    }
    
    public A next() {
      getNext();
      if (done) throw fail();
      A _a = a;
      a = null;
      have = false;
      return _a;
    }
    
    void getNext() {
      if (done || have) return;
      Object o = callF(f);
      if (o == iteratorFromFunction_endMarker)
        { done = true; return; }
      a = (A) o;
      have = true;
    }
  };
  return new IFF();
}

// optimized version for F0 argument; TODO: do same for IF0
static <A> IterableIterator<A> iteratorFromFunction_withEndMarker(final F0 f) {
  return iteratorFromFunction_withEndMarker_f0(f);
}


static Map mapKeys(Object func, Map map) {
  Map m = similarEmptyMap(map); // TODO: this might break when key type changes through func
  for (Object key : keys(map))
    m.put(callF(func, key), map.get(key));
  return m;
}

static Map mapKeys(Map map, Object func) {
  return mapKeys(func, map);
}

static <A, B, C> Map<B, C> mapKeys(Map<A, C> map, IF1<A, B> func) {
  return mapKeys(map, (Object) func);
}

static <A, B, C> Map<B, C> mapKeys(IF1<A, B> func, Map<A, C> map) {
  return mapKeys(map, func);
}


static String dropDollarPrefix(String s) {
  return dropPrefix("$", s);
}


static TreeMap litcimap(Object... x) {
  return litCIMap(x);
}


// f takes variable without $ sign. if it returns null, variable is kept
static String replaceDollarVars_dyn(String s, IF1<String, String> f) {
  if (f == null) return s;
  return regexpReplaceIC(s, "\\$(\\w+)", matcher -> {
    String var = matcher.group(1);
    String val = f.get(var);
    return val == null ? matcher.group() : str(val);
  });
}


static boolean hasField(Object o, String field) {
  return findField2(o, field) != null;
}


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

// 0xRRGGBB - result is between 0 and 1
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);
}


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



static JMenuItem directJMenuItem(Action a) {
  return new JMenuItem(a) {
    public Dimension getMaximumSize() {
      return new Dimension(super.getPreferredSize().width, super.getMaximumSize().height);
    }
  };
}

static JMenuItem directJMenuItem(String text, Object action) {
  return directJMenuItem(abstractAction(text, action));
}



static JMenuBar addMenuBar(final Component c) {
  return swing(new F0<JMenuBar>() { public JMenuBar get() { try { 
    RootPaneContainer f = getPossiblyInternalFrame(c);
    if (f == null) return null;
    JMenuBar bar =  (JMenuBar) (call(f, "getJMenuBar"));
    if (bar == null) {
      setMenuBar(f, bar = new JMenuBar());
      revalidate((Component) f);
    }
    return bar;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "RootPaneContainer f = getPossiblyInternalFrame(c);\r\n    if (f == null) null;\r..."; }});
}


static String autoFrameTitle_value;

static String autoFrameTitle() {
  return autoFrameTitle_value != null ? autoFrameTitle_value : getProgramTitle();
}

static void autoFrameTitle(Component c) {
  setFrameTitle(getFrame(c), autoFrameTitle());
}


static void registerEscape_rootPane(JComponent rootPane, final Runnable r) {
  String name = "Escape";
  Action action = abstractAction(name, r);
  KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
  rootPane.getActionMap().put(name, action);
  rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name);
}


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


static JTextField jtextfield() {
  return jTextField();
}

static JTextField jtextfield(String text) {
  return jTextField(text);
}

static JTextField jtextfield(Object o) {
  return jTextField(o);
}



static String programName() {
  return getProgramName();
}


static int showForm_defaultGap = 4;
static int showForm_gapBetweenColumns = 10;

static JPanel showFormTitled(final String title, final Object... _parts) {
  JDesktopPane desktop = mainDesktopPane();
  if (desktop != null) return showInternalFrameFormTitled(desktop, title, _parts);
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    final Var<JFrame> frame = new Var();
    JPanel panel = showForm_makePanel(false, _parts);
    frame.set(showForm_makeFrame(title, panel));
    return panel;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "final new Var<JFrame> frame;\r\n    JPanel panel = showForm_makePanel(false, _p..."; }});
}

static JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) {
  List<JComponent> out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts));
  return vstackWithSpacing(out, showForm_defaultGap);
}


static JPanel centerAndEast(final Component c, final Component e) {
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(BorderLayout.CENTER, wrap(c));
    panel.add(BorderLayout.EAST, wrap(e));
    return panel;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.CENT..."; }});
}


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

// button without action
static JButton jbutton(String text) {
  return newButton(text, null);
}

/*static JButton jbutton(BufferedImage img, O action) {
  ret setButtonImage(img, jbutton("", action));
}*/

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


static String getTextTrim(JTextComponent c) {
  return trim(getText(c));
}

// tested for editable combo box - returns the contents of text field
static String getTextTrim(JComboBox cb) {
  return trim(getText(cb));
}

static String getTextTrim(JComponent c) {
  if (c instanceof JLabel) return trim(((JLabel) c).getText());
  if (c instanceof JComboBox) return getTextTrim((JComboBox) c);
  return getTextTrim((JTextComponent) c);
}


static <A extends JComponent> A renameSubmitButton(A form, String newName) {
  renameButton(form, showFormSubmitButtonName(), newName);
  return form;
}

static <A extends JComponent> A renameSubmitButton(String newName, A form) {
  return renameSubmitButton(form, newName);
}


static boolean ewicOneOf(String s, String... l) {
  if (s != null) for (String x : l) if (ewic(s, x)) return true; return false;
}


static String fileName(File f) {
  return f == null ? null : f.getName();
}


static BufferedImage reconstructBufferedImage(BufferedImage img) {
  if (img == null) return null;
  RGBImage rgb = new RGBImage(img);
  rgb.uncacheBufferedImage();
  return rgb.getBufferedImage();
}


static <A extends JTextComponent> A moveCaretToEnd(A ta) {
  setCaretPosition(ta, textAreaTextLength(ta));
  return ta;
}


static JComponent showTitledForm(String title, Object... _parts) {
  return showFormTitled(title, _parts);
}



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


static BufferedImage copyImage(BufferedImage bi) {
  if (bi == null) return null;
  ColorModel cm = bi.getColorModel();
  boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
  WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster());
  return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}


static BufferedImage decodeImage(byte[] data) { try {
  return ImageIO.read(new ByteArrayInputStream(data));
} catch (Exception __e) { throw rethrow(__e); } }


  static byte[] base64decode(String s) {
    byte[] alphaToInt = base64decode_base64toint;
    int sLen = s.length();
    int numGroups = sLen/4;
    if (4*numGroups != sLen)
      throw new IllegalArgumentException(
        "String length must be a multiple of four.");
    int missingBytesInLastGroup = 0;
    int numFullGroups = numGroups;
    if (sLen != 0) {
      if (s.charAt(sLen-1) == '=') {
        missingBytesInLastGroup++;
        numFullGroups--;
      }
      if (s.charAt(sLen-2) == '=')
        missingBytesInLastGroup++;
    }
    byte[] result = new byte[3*numGroups - missingBytesInLastGroup];

    // Translate all full groups from base64 to byte array elements
    int inCursor = 0, outCursor = 0;
    for (int i=0; i<numFullGroups; i++) {
      int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch3 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
      result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
      result[outCursor++] = (byte) ((ch2 << 6) | ch3);
    }

    // Translate partial group, if present
    if (missingBytesInLastGroup != 0) {
      int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
      result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));

      if (missingBytesInLastGroup == 1) {
        int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
        result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
      }
    }
    // assert inCursor == s.length()-missingBytesInLastGroup;
    // assert outCursor == result.length;
    return result;
  }

  static int base64decode_base64toint(char c, byte[] alphaToInt) {
    int result = alphaToInt[c];
    if (result < 0)
      throw new IllegalArgumentException("Illegal character " + c);
    return result;
  }

  static final byte base64decode_base64toint[] = {
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
    55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
    5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
    24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
    35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
  };




static AutoCloseable tempActivity(Object r) {
  return null;
}


static boolean allPaused() {
  return ping_pauseAll;
}



static void cancelTimer(javax.swing.Timer timer) {
  if (timer != null) timer.stop();
}


static void cancelTimer(java.util.Timer timer) {
  if (timer != null) timer.cancel();
}

static void cancelTimer(Object o) {
  if (o instanceof java.util.Timer) cancelTimer((java.util.Timer) o);
  
  else if (o instanceof javax.swing.Timer) cancelTimer((javax.swing.Timer) o);
  
  else if (o instanceof AutoCloseable) { try { ((AutoCloseable) o).close(); } catch (Throwable __e) { _handleException(__e); }}
}




static void bindTimerToComponent(final Timer timer, JFrame f) {
  bindTimerToComponent(timer, f.getRootPane());
}

static void bindTimerToComponent(final Timer timer, JComponent c) {
  if (c.isShowing())
    timer.start();
  
  c.addAncestorListener(new AncestorListener() {
    public void ancestorAdded(AncestorEvent event) {
      timer.start();
    }

    public void ancestorRemoved(AncestorEvent event) {
      timer.stop();
    }

    public void ancestorMoved(AncestorEvent event) {
    }
  });
}


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


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


static <A extends JComponent> A onClick(final A c, final Object runnable) {
  if (c != null) { swing(new Runnable() {  public void run() { try { 
    c.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        callF(runnable, e);
      }
    });
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "c.addMouseListener(new MouseAdapter {\r\n      public void mouseClicked(MouseEv..."; }}); }
  return c;
}

// re-interpreted for buttons
static void onClick(JButton btn, final Object runnable) {
  onEnter(btn, runnable);
}


static void disposeFrame(final Component c) {
  disposeWindow(c);
}


static int indexOfNonDigit(String s) {
  int n = l(s);
  for (int i = 0; i < n; i++)
    if (!isDigit(s.charAt(i)))
      return i;
  return -1;
}


static boolean isImageFile(File f) {
  return isImageFileName(fileName(f));
}


static String rep(int n, char c) {
  return repeat(c, n);
}

static String rep(char c, int n) {
  return repeat(c, n);
}

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

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



static Set emptySet() {
  return new HashSet();
}


static <A> TreeSet<A> asTreeSet(Collection<A> set) {
  return set == null ? null : set instanceof TreeSet ? (TreeSet) set : new TreeSet(set);
}


static String decimalFormatEnglish(String format, double d) {
  return decimalFormatEnglish(format).format(d);
}

static java.text.DecimalFormat decimalFormatEnglish(String format) {
  return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH));
}


// f can return false to suppress regular printing
// call print_raw within f to actually print something
// f preferrably is F1<S, Bool>
static Object interceptPrintInThisThread(Object f) {
  Object old = print_byThread().get();
  print_byThread().set(f);
  return old;
}


/*static <A> L<A> printNumberedLines(L<A> l) {
  printNumberedLines((Collection<A>) l);
  ret l;
}

static <A> L<A> printNumberedLines(S prefix, L<A> l) {
  printNumberedLines(prefix, (Collection<A>) l);
  ret l;
}*/

static void printNumberedLines(Map map) {
  printNumberedLines(mapToLines(map));
}

static void printNumberedLines(String prefix, Map map) {
  printNumberedLines(prefix, mapToLines(map));
}

static <A extends Iterable> A printNumberedLines(A l) {
  int i = 0;
  if (l != null) for (Object a : l) print((++i) + ". " + str(a));
  return l;
}

static <A extends Iterable> A printNumberedLines(String prefix, A l) {
  int i = 0;
  if (l != null) for (Object a : l) print(prefix + (++i) + ". " + str(a));
  return l;
}

static void printNumberedLines(Object[] l) { printNumberedLines("", l); }
static void printNumberedLines(String prefix, Object[] l) {
  printNumberedLines(prefix, asList(l));
}

static void printNumberedLines(Object o) {
  printNumberedLines(lines(str(o)));
}


static double parseDouble(String s) {
  return Double.parseDouble(s);
}


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

static <A> Collection<A> unnullForIteration(Collection<A> l) {
  return l == null ? immutableEmptyList() : l;
}

static <A> List<A> unnullForIteration(List<A> l) { return l == null ? immutableEmptyList() : l; }
static int[] unnullForIteration(int[] l) { return l == null ? emptyIntArray() : l; }
static char[] unnullForIteration(char[] l) { return l == null ? emptyCharArray() : l; }
static double[] unnullForIteration(double[] l) { return l == null ? emptyDoubleArray() : l; }

static <A, B> Map<A, B> unnullForIteration(Map<A, B> l) {
  return l == null ? immutableEmptyMap() : l;
}

static <A> Iterable<A> unnullForIteration(Iterable<A> i) {
  return i == null ? immutableEmptyList() : i;
}

static <A> A[] unnullForIteration(A[] a) {
  return a == null ? (A[]) emptyObjectArray() : a;
}

static BitSet unnullForIteration(BitSet b) {
  return b == null ? new BitSet() : b;
}


static Pt unnullForIteration(Pt p) {
  return p == null ? new Pt() : p;
}


//ifclass Symbol



static <A, B> Pair<A, B> unnullForIteration(Pair<A, B> p) {
  return p != null ? p : new Pair(null, null);
}


static long unnullForIteration(Long l) { return l == null ? 0L : l; }


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;
}

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;
}


static <A> int compareWithComparator(Comparator<A> comparator, A a, A b) {
  return comparator == null ? cmp(a, b) : comparator.compare(a, b);
}


static F1 functionToF1(final Object f) {
  if (isString(f)) return mainFunctionToF1((String) f);
  if (f instanceof F1) return (F1) f;
  return new F1<Object, Object>() { public Object get(Object a) { try {  return callF(f, a);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret callF(f, a);"; }};
}




static <A> IterableIterator<A> iteratorFromFunction_withEndMarker_f0(final F0<A> f) {
  class IFF2 extends IterableIterator<A> {
    A a;
    boolean have, done;
    
    public boolean hasNext() {
      getNext();
      return !done;
    }
    
    public A next() {
      getNext();
      if (done) throw fail();
      A _a = a;
      a = null;
      have = false;
      return _a;
    }
    
    void getNext() {
      if (done || have) return;
      Object o = f.get();
      if (o == iteratorFromFunction_endMarker)
        { done = true; return; }
      a = (A) o;
      have = true;
    }
  };
  return new IFF2();
}


static Map similarEmptyMap(Map m) {
  if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator());
  if (m instanceof LinkedHashMap) return new LinkedHashMap();
  
  // default to a hash map
  return new HashMap();
}

static Map similarEmptyMap(Iterable m) {
  if (m instanceof TreeSet) return new TreeMap(((TreeSet) m).comparator());
  if (m instanceof LinkedHashSet) return new LinkedHashMap();
  
  return new HashMap();
}


static TreeMap litCIMap(Object... x) {
  TreeMap map = caseInsensitiveMap();
  litmap_impl(map, x);
  return map;
}


// f : Matcher -> S
static String regexpReplaceIC(String s, String pat, Object f) {
  return regexReplaceIC(s, pat, f);
}

static String regexpReplaceIC(String s, String pat, String replacement) {
  return regexReplaceIC(s, pat, replacement);
}

static String regexpReplaceIC(String s, String pat, IF1<Matcher, String> f) {
  return regexReplaceIC(s, pat, f);
}


static Field findField2(Object o, String field) {
  Class c = o.getClass();
  HashMap<String, Field> map;
  synchronized(getOpt_cache) {
    map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
  }
  
  if (map == getOpt_special) {
    if (o instanceof Class)
      return findField2_findStaticField((Class) o, field);
  }
    
  return map.get(field);
}

static Field findField2_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}


static void setMenuBar(final JMenuBar mb, final RootPaneContainer f) {
  { swing(new Runnable() {  public void run() { try { 
    call(f, "setJMenuBar", mb);
    revalidate((Component) f);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "call(f, \"setJMenuBar\", mb);\r\n    revalidate((Component) f);"; }}); }
}

static void setMenuBar(RootPaneContainer f, JMenuBar mb) {
  setMenuBar(mb, f);
}


static String getProgramTitle() {
  return getProgramName();
}


static boolean isInstanceOf(Object o, Class type) {
  return type.isInstance(o);
}


static JTextField jTextField() {
  return jTextField("");
}

static JTextField jTextField(final String text) {
  return swing(new F0<JTextField>() { public JTextField get() { try { 
    JTextField tf = new JTextField(unnull(text));
    standardTextFieldPopupMenu(tf);
    jenableUndoRedo(tf);
    tf.selectAll();
    return tf;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n    standardTextFieldPopupMenu..."; }});
}

static JTextField jTextField(Object o) {
  return jTextField(strOrEmpty(o));
}



static JDesktopPane mainDesktopPane_value;

static JDesktopPane mainDesktopPane() {
  return mainDesktopPane_value;
}


static JPanel showInternalFrameFormTitled(final JDesktopPane desktop, final String title, final Object... _parts) {
  JPanel panel = showForm_makePanel(true, _parts);
  showForm_makeInternalFrame(desktop, title, panel);
  return panel;
}


static JFrame showForm_makeFrame(String title, JPanel panel) {
  return handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400));
}


static List<JComponent> showForm_arrange1(List<List<JComponent>> l) {
  int minW = showForm_leftWidth(l);

  List<JComponent> out = new ArrayList();
  for (List<JComponent> row : l)
    out.add(westAndCenter(withRightMargin(showForm_gapBetweenColumns, jMinWidthAtLeast(minW, first(row))), second(row)));
  return out;
}


static List<List<JComponent>> showForm_makeComponents(final Boolean internalFrame, Object... _parts) {
  List<List<JComponent>> l = new ArrayList();
  List parts = asList(_parts);
  JButton submitButton = null;
  for (int i = 0; i < l(parts); i++) {
    final Object o = parts.get(i), next = get(parts, i+1);
    if (o instanceof String && next instanceof Component)
      setComponentID((Component) next, (String) o);
    
    if (o instanceof Component || o instanceof String || next instanceof Component) { // smartAdd accepts strings
      l.add(mapLL(__43 -> wrapForSmartAdd_jComponent(__43), 
          o == null ? new JPanel()
        : o instanceof String ? humanizeFormLabel((String) o)
        : o, next));
      if (next instanceof JButton && submitButton == null)
        submitButton = (JButton) next;
      i++;
    } else if (isRunnable(o))
      l.add(mapLL(__44 -> wrapForSmartAdd_jComponent(__44), null, submitButton = jbutton(showFormSubmitButtonName(), new Runnable() {  public void run() { try { 
        Object result = call(o);
        print("Result of form runnable: " + result + ". Button:  " + heldInstance(JButton.class));
        if (neq(Boolean.FALSE, result)) {
          if (isTrue(internalFrame))
            disposeInternalFrame(heldInstance(JButton.class));
          else if (isFalse(internalFrame))
            disposeFrame(heldInstance(JButton.class));
        }
      
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "Object result = call(o);\r\n        print(\"Result of form runnable: \" + result ..."; }})));
    else print("showForm: Unknown element type: " + getClassName(o));
  }
  if (submitButton != null) {
    final JButton _submitButton = submitButton;
    onEnterInAllTextFields(concatLists(l), new Runnable() {  public void run() { try {  clickButton(_submitButton) ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "clickButton(_submitButton)"; }});
  }
  
  // massage labels
  for (List<JComponent> row : l) {
    JComponent left = first(row);
    if (left instanceof JLabel) makeBold((JLabel) left).setVerticalAlignment(JLabel.TOP);
  }
  
  return l;
}


static int vstackWithSpacing_default = 10;

static JPanel vstackWithSpacing(final List parts) {
  return vstackWithSpacing(parts, vstackWithSpacing_default);
}

static JPanel vstackWithSpacing(final List parts, final int spacing) {
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.insets = new Insets(spacing/2, 0, spacing/2, 0); // well...
    smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts)));
    //gbc = (GridBagConstraints) gbc.clone();
    //gbc.fill = GridBagConstraints.BOTH;
    gbc.weighty = 1;
    gbc.insets = new Insets(0, 0, 0, 0);
    panel.add(jrigid(), gbc);
    return panel;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n    new GridBagConstraints gbc..."; }});
}

static JPanel vstackWithSpacing(Component... parts) {
  return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
}

static JPanel vstackWithSpacing(int spacing, Component... parts) {
  return vstackWithSpacing(asList(parts), spacing);
}


static boolean newButton_autoToolTip = true;

// action can be Runnable or a function name
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());
      //onChangeAndNow(btn, r { btn.setToolTipText(btn.getText()) });
    }
    // submitButtonOnEnter(btn); // test this first
    if (action != null)
      btn.addActionListener(actionListener(action, btn));
    return btn;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n    final JButton btn = new JButt..."; }});
}



static String getText(final AbstractButton c) {
  return c == null ? "" : (String) swingAndWait(new F0<Object>() { public Object get() { try {  return c.getText();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret c.getText();"; }});
}

static String getText(final JTextComponent c) {
  return c == null ? "" : (String) swingAndWait(new F0<Object>() { public Object get() { try {  return c.getText();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret c.getText();"; }});
}

static String getText(final JLabel l) {
  return l == null ? "" : (String) swingAndWait(new F0<Object>() { public Object get() { try {  return l.getText();  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "ret l.getText();"; }});
}

// returns the contents of text field for editable combo box
static String getText(final JComboBox cb) {
  if (cb == null) return null;
  if (isEditableComboBox(cb))
    return unnull((String) cb.getEditor().getItem());
  else
    return str(cb.getSelectedItem());
}





static JButton renameButton(JComponent c, String name) {
  JButton b = first(childrenOfType(c, JButton.class));
  if (b != null)
    b.setText(name);
  return b;
}

static JButton renameButton(JComponent c, String oldName, String newName) {
  JButton b = findButton(c, oldName);
  if (b != null) b.setText(newName);
  return b;
}


static String showFormSubmitButtonName() {
  return "Submit";
}


static void setCaretPosition(final JTextComponent c, final int pos) {
  if (c != null) { swing(new Runnable() {  public void run() { try { 
    try {
      int _pos = max(0, min(l(c.getText()), pos));
      c.setCaretPosition(_pos);
    } catch (Throwable __e) { _handleException(__e); }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "pcall {\r\n      int _pos = max(0, min(l(c.getText()), pos));\r\n      c.setCaret..."; }}); }
}


static int textAreaTextLength(JTextComponent ta) {
  return l(getText(ta));
}


static boolean isDigit(char c) {
  return Character.isDigit(c);
}


static boolean isImageFileName(String s) {
  return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif");
}


static String repeat(char c, int n) {
  n = Math.max(n, 0);
  char[] chars = new char[n];
  for (int i = 0; i < n; i++)
    chars[i] = c;
  return new String(chars);
}

static <A> List<A> repeat(A a, int n) {
  n = Math.max(n, 0);
  List<A> l = new ArrayList(n);
  for (int i = 0; i < n; i++)
    l.add(a);
  return l;
}

static <A> List<A> repeat(int n, A a) {
  return repeat(a, n);
}


static <A> List<A> immutableEmptyList() {
  return Collections.emptyList();
}


static <A, B> Map<A, B> immutableEmptyMap() {
  return Collections.emptyMap();
}


static boolean isString(Object o) {
  return o instanceof String;
}


static F1 mainFunctionToF1(final String fname) {
  return new F1<Object, Object>() { public Object get(Object a) { try {  return callMC(fname, a);  } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "callMC(fname, a)"; }};
}




static <A> TreeMap<String, A> caseInsensitiveMap() {
  return new TreeMap(caseInsensitiveComparator());
}


static HashMap litmap(Object... x) {
  HashMap map = new HashMap();
  litmap_impl(map, x);
  return map;
}

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]);
}


// f : Matcher -> S
static String regexReplaceIC(String s, String pat, Object f) {
  return regexReplace(regexpMatcherIC(pat, s), f);
}

static String regexReplaceIC(String s, String pat, String replacement) {
  return regexpReplaceIC_direct(s, pat, replacement);
}


static JTextField standardTextFieldPopupMenu(final JTextField tf) {
  final WeakReference<JTextField> ref = weakRef(tf);
  componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() {  public void run() { try { 
    copyTextToClipboard(ref.get().getText())
  ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "copyTextToClipboard(ref.get().getText())"; }});
  componentPopupMenuItem(tf, "Paste", new Runnable() {  public void run() { try {  ref.get().paste() ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "ref.get().paste()"; }});
  return tf;
}




static <A extends JTextComponent> A jenableUndoRedo(final A textcomp) {
  { swing(new Runnable() {  public void run() { try { 
    final UndoManager undo = new UndoManager();
    vm_generalWeakSet("Undo Managers").add(undo);
    textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
      public void undoableEditHappened(UndoableEditEvent evt) {
        undo.addEdit(evt.getEdit());
      }
    });
    
    textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() {  public void run() { try { 
      if (undo.canUndo()) undo.undo()
    ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (undo.canUndo()) undo.undo()"; }}));
    textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() {  public void run() { try { 
      if (undo.canRedo()) undo.redo()
    ;
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (undo.canRedo()) undo.redo()"; }}));
    textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
    textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "final new UndoManager undo;\r\n    vm_generalWeakSet(\"Undo Managers\").add(undo)..."; }}); }
  return textcomp;
}


static String strOrEmpty(Object o) {
  return o == null ? "" : str(o);
}


static JInternalFrame showForm_makeInternalFrame(JDesktopPane desktop, String title, JPanel panel) {
  JInternalFrame f = addInternalFrame(desktop, title, withMargin(panel));
  minInternalFrameWidth(f, 400);
  packInternalFrameVertically(f);
  centerInternalFrame(f);
  // TODO: handleEscapeKey(f);
  return f;
}


static JFrame handleEscapeKey(final JFrame frame) {
  KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
  frame.getRootPane().registerKeyboardAction(new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
      frame.dispose();
    }
  }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
  return frame;
}



static JFrame minFrameWidth(JFrame frame, int w) {
  if (frame != null && frame.getWidth() < w)
    frame.setSize(w, frame.getHeight());
  return frame;
}

static JFrame minFrameWidth(int w, JFrame frame) {
  return minFrameWidth(frame, w);
}



static int withMargin_defaultWidth = 6;

static JPanel withMargin(Component c) {
  return withMargin(withMargin_defaultWidth, c);
}

static JPanel withMargin(int w, Component c) {
  return withMargin(w, w, c);
}

static JPanel withMargin(int w, int h, Component c) {
  return withMargin(w, h, w, h, c);
}

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..."; }});
}


static int showForm_leftWidth_safetyMargin = 10;

static int showForm_leftWidth(List<List<JComponent>> l) {
  forEachLevel2(l, x -> vmBus_send("updateLayoutNow", x));
  int minW = 0;
  for (List<JComponent> row : l)
    minW = max(minW, getMinimumSize(first(row)).width);
  return minW + or((Integer) vmBus_query("formSafetyMargin"), showForm_leftWidth_safetyMargin);
}


static JPanel westAndCenter(final Component w, final Component c) {
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(BorderLayout.WEST, wrap(w));
    panel.add(BorderLayout.CENTER, wrap(c));
    return panel;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.WEST..."; }});
}


static int withRightMargin_defaultWidth = 6;

static JPanel withRightMargin(Component c) {
  return withRightMargin(withRightMargin_defaultWidth, c);
}

static JPanel withRightMargin(final int w, final Component c) {
  return swing(new F0<JPanel>() { public JPanel get() { try { 
    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w));
    p.add(c);
    return p;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat..."; }});
}


static <A extends Component> A jMinWidthAtLeast(int w, final A c) {
  if (c == null) return null;
  return swing(new F0<A>() { public A get() { try { 
    Dimension size = c.getMinimumSize();
    Dimension d = new Dimension(max(w, size.width), size.height);
    c.setMinimumSize(d);
    return jPreferWidth(d.width, c);
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "Dimension size = c.getMinimumSize();\r\n    Dimension d = new Dimension(max(w, ..."; }});
}


static void setComponentID(Component c, String id) {
  if (c != null) componentID_map.put(c, id);
}


static List mapLL(Object f, Object... data) {
  return map(f, ll(data));
}

static <A, B> List<B> mapLL(IF1<A, B> f, A... data) {
  return map(f, ll(data));
}


static JComponent wrapForSmartAdd_jComponent(Object o) {
  return componentToJComponent(wrapForSmartAdd(o));
}


static Map<String, String> humanizeFormLabel_replacements = litmap("id" , "ID", "md5" , "MD5");

static String humanizeFormLabel(String s) {
  if (containsSpace(s)) return s;
  return firstToUpper(
    joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID")
  );
}


static boolean isRunnable(Object o) {
  return o instanceof Runnable || hasMethod(o, "get");
}


static void disposeInternalFrame(Component c) {
  final JInternalFrame f = getInternalFrame(c);
  if (f != null) { swing(new Runnable() {  public void run() { try { 
    vmBus_send("disposingInternalFrame", f);
    f.dispose();
    setOpt(f, "lastFocusOwner" , null); // Help GC
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "vmBus_send disposingInternalFrame(f);\r\n    f.dispose();\r\n    setOpt(f, lastFo..."; }}); }
}


static void onEnterInAllTextFields(JComponent c, Object action) {
  if (action == null) return;
  for (Component tf : allChildren(c))
    onEnterIfTextField(tf, action);
}

static void onEnterInAllTextFields(List c, Object action) {
  for (Object o : unnull(c))
    if (o instanceof JComponent)
      onEnterInAllTextFields((JComponent) o, action);
}


static <A> List<A> concatLists(Iterable<A>... lists) {
  List<A> l = new ArrayList();
  if (lists != null) for (Iterable<A> list : lists)
    addAll(l, list);
  return l;
}

static <A> List<A> concatLists(Collection<? extends Iterable<A>> lists) {
  List<A> l = new ArrayList();
  if (lists != null) for (Iterable<A> list : lists)
    addAll(l, list);
  return l;
}



static void clickButton(final JButton b) {
  if (b != null) { swing(new Runnable() {  public void run() { try { 
    if (b.isEnabled())
      b.doClick();
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (b.isEnabled())\r\n      b.doClick();"; }}); }
}


static <A extends JComponent> A makeBold(final A c) {
  if (c != null) { swing(new Runnable() {  public void run() { try {  c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD)); 
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD));"; }}); }
  return c;
}


static JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
  for (Object o : parts)
    panel.add(wrapForSmartAdd(o), layout);
  return panel;
}

static JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
  return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
}



static <A> List<A> nonNulls(Iterable<A> l) {
  return withoutNulls(l);
}

static <A> List<A> nonNulls(A[] l) {
  return withoutNulls(l);
}

static <A, B> Map<A, B> nonNulls(Map<A, B> map) {
  return withoutNulls(map);
}


static Component jrigid() {
  return javax.swing.Box.createRigidArea(new Dimension(0, 0));
}


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();"; }});
}


static <A> List<A> childrenOfType(Component c, Class<A> theClass) {
  List<A> l = new ArrayList();
  scanForComponents(c, theClass, l);
  return l;
}

static <A> List<A> childrenOfType(Class<A> theClass, Component c) {
  return childrenOfType(c, theClass);
}


static JButton findButton(Component c, String name) {
  for (JButton b : childrenOfType(c, JButton.class))
    if (eq(b.getText(), name)) return b;
  for (JButton b : childrenOfType(getFrame(c), JButton.class))
    if (eq(b.getText(), name)) return b;
  return null;
}

static JButton findButton(Component c) {
  return childOfType(c, JButton.class);
}




static Map<Component, String> componentID_map = weakHashMap();

static String componentID(Component c) {
  return c == null ? null : componentID_map.get(c);
}


static Comparator<String> caseInsensitiveComparator() {
  
  
  return betterCIComparator();
  
}


// f : Matcher -> S
static String regexReplace(String s, String pat, Object f) {
  Matcher m = Pattern.compile(pat).matcher(s);
  return regexReplace(m, f);
}

static String regexReplace(String s, String pat, String replacement) {
  return regexpReplace_direct(s, pat, replacement);
}

static String regexReplace(Matcher m, Object f) {
  StringBuffer buf = new StringBuffer();
  while (m.find())
    m.appendReplacement(buf, m.quoteReplacement(str(callF(f, m))));
  m.appendTail(buf);
  return str(buf);
}

static String regexReplace(String s, String pat, IF1<Matcher, String> f) {
  return regexReplace(s, pat, (Object) f);
}


static Matcher regexpMatcherIC(String pat, String s) {
  return compileRegexpIC(pat).matcher(unnull(s));
}


static String regexpReplaceIC_direct(String s, String pat, String replacement) {
  Matcher m = regexpIC(pat, s);
  StringBuffer buf = new StringBuffer();
  while (m.find())
    m.appendReplacement(buf, replacement);
  m.appendTail(buf);
  return str(buf);
}


static <A extends JComponent> A componentPopupMenuItem(A c, final String name, final Object action) {
  componentPopupMenu(c, new VF1<JPopupMenu>() { public void get(JPopupMenu menu) { try { 
    addMenuItem(menu, name, action);
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "addMenuItem(menu, name, action);"; }});
  return c;
}

static void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) {
  componentPopupMenu(c, new VF1<JPopupMenu>() { public void get(JPopupMenu menu) { try { 
    addMenuItem(menu, menuItem);
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "addMenuItem(menu, menuItem);"; }});
}


static Set vm_generalWeakSet(Object name) {
  synchronized(get(javax(), "generalMap")) {
    Set set =  (Set) (vm_generalMap_get(name));
    if (set == null)
      vm_generalMap_put(name, set = newWeakHashSet());
    return set;
  }
}



static ThreadLocal<Boolean> addInternalFrame_dontSelect = new ThreadLocal();
static ThreadLocal<Integer> addInternalFrame_layer = new ThreadLocal();
static ThreadLocal<Boolean> addInternalFrame_toBack = new ThreadLocal();

static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h) {
  return addInternalFrame(desktop, title, x, y, w, h, null);
}

static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h, final Component contents) {
  return addInternalFrame(desktop, title, rect(x, y, w, h), contents);
}

static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Component contents) {
  return addInternalFrame(desktop, title, null, contents);
}

static JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Rect r, final Component contents) {
  final boolean dontSelect = isTrue(optParam(addInternalFrame_dontSelect));
  final boolean toBack = isTrue(optParam(addInternalFrame_toBack));
  final Integer layer = optParam(addInternalFrame_layer);
  return swing(new F0<JInternalFrame>() { public JInternalFrame get() { try { 
    JInternalFrame frame;
    if (contents instanceof JInternalFrame)
      frame = (JInternalFrame) contents;
    else {
      frame = jInternalFrame(title);
      setInternalFrameContents(frame, contents);
    }
    frame.setVisible(true);
    desktop.add(frame, layer);
    if (r != null)
      setBounds(frame, r);
    else
      internalFrameDefaultPosition(frame);
    if (dontSelect)
      if (toBack)
        frame.toBack();
      else
        frame.toFront();
    else
      frame.setSelected(true);
    return fixInternalFrame(frame);
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JInternalFrame frame;\r\n    if (contents instanceof JInternalFrame)\r\n      fra..."; }});
}

static JInternalFrame addInternalFrame(JDesktopPane desktop, String title) {
  return addInternalFrame(desktop, title, jpanel());
}


static JInternalFrame minInternalFrameWidth(final JInternalFrame frame, final int w) {
  { swing(new Runnable() {  public void run() { try { 
    if (frame != null && frame.getWidth() < w)
      frame.setSize(w, frame.getHeight());
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "if (frame != null && frame.getWidth() < w)\r\n      frame.setSize(w, frame.getH..."; }}); }
  return frame;
}

static JInternalFrame minInternalFrameWidth(int w, JInternalFrame frame) {
  return minInternalFrameWidth(frame, w);
}



static <A extends Component> A packInternalFrameVertically(A c) {
  return packInternalFrameVertically(-1, c);
}

static <A extends Component> A packInternalFrameVertically(int width, A c) {
  final JInternalFrame win = getInternalFrame(c);
  if (win == null) return c;
  final int w = width < 0 ? win.getWidth() : width;
  { swing(new Runnable() {  public void run() { try { 
    win.pack();
    win.setSize(w, win.getHeight());
    fixInternalFrame(win);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "win.pack();\r\n    win.setSize(w, win.getHeight());\r\n    fixInternalFrame(win);"; }}); }
  return c;
}


static JInternalFrame centerInternalFrame(final JInternalFrame f) {
  { swing(new Runnable() {  public void run() { try { 
    Container c = f.getParent();
    if (c != null) {
      //print("Container type: " + className(c) + ", bounds: " + c.getBounds());
      f.setLocation((c.getWidth()-f.getWidth())/2, (c.getHeight()-f.getHeight())/2);
    }
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "Container c = f.getParent();\r\n    if (c != null) {\r\n      //print(\"Container ..."; }}); }
  return f;
}

static JInternalFrame centerInternalFrame(final int w, final int h, final JInternalFrame f) {
  { swing(new Runnable() {  public void run() { try { 
    f.setSize(w, h);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "f.setSize(w, h);"; }}); }
  return centerInternalFrame(f);
}


static <A, B extends Collection<A>> void forEachLevel2(Iterable<B> l, IVF1<A> f) {
  if (l != null) for (B b : l)
    forEach(b, f);
}

static <A, B extends Collection<A>> void forEachLevel2(IVF1<A> f, Iterable<B> l) {
  forEachLevel2(f, l);
}


static Object vmBus_query(String msg, Object... args) {
  Object arg = vmBus_wrapArgs(args);
  { Object __1= pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg); if (__1 != null) return __1; }
  return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
}

static Object vmBus_query(String msg) {
  return vmBus_query(msg, (Object) null);
}


static <A extends Component> A jPreferWidth(int w, A c) {
  Dimension size = c.getPreferredSize();
  c.setPreferredSize(new Dimension(/*max(w, size.width) ??? */w, size.height));
  return c;
}


static Component wrapForSmartAdd(Object o) {
  if (o == null) return jpanel();
  if (o instanceof String) return jlabel((String) o);
  return wrap(o);
}


static boolean containsSpace(String s) {
  return containsSpaces(s);
}


static String firstToUpper(String s) {
  if (empty(s)) return s;
  return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}


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)"; }});
}


static List<String> splitCamelCase(String s) {
  return ai_splitCamelCase(s);
}


static boolean hasMethod(Object o, String method, Object... args) {
  return findMethod_cached(o, method, args) != null;
}


static List<Component> allChildren(Component c) {
  return childrenOfType(c, Component.class);
}


static void onEnterIfTextField(Component c, Object action) {
  if (action == null) return;
  if (c instanceof JTextField)
    onEnter((JTextField) c, action);
  else if (c instanceof JComboBox)
    onEnter((JComboBox) c, action);
}


static 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);
}


static <A> List<A> withoutNulls(Iterable<A> l) {
  if (l instanceof List)
    if (!containsNulls(((List) l))) return ((List) l);
  List<A> l2 = new ArrayList();
  for (A a : l)
    if (a != null)
      l2.add(a);
  return l2;
}

static <A, B> Map<A, B> withoutNulls(Map<A, B> map) {
  Map<A, B> map2 = similarEmptyMap(map);
  for (A a : keys(map))
    if (a != null) {
      B b = map.get(a);
      if (b != null)
        map2.put(a, b);
    }
  return map2;
}

static <A> List<A> withoutNulls(A[] l) {
  List<A> l2 = new ArrayList();
  if (l != null) for (A a : l)
    if (a != null)
      l2.add(a);
  return l2;
}


static <A> void scanForComponents(final Component c, final Class<A> theClass, final List<A> l) {
  if (theClass.isInstance(c))
    l.add((A) c);
  if (c instanceof Container) { swing(new Runnable() {  public void run() { try { 
    for (Component comp : ((Container) c).getComponents())
      scanForComponents(comp, theClass, l);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "for (Component comp : ((Container) c).getComponents())\r\n      scanForComponen..."; }}); }
}


static <A> A childOfType(Component c, Class<A> theClass) {
  return first(childrenOfType(c, theClass));
}

static <A> A childOfType(Class<A> theClass, Component c) {
  return childOfType(c, theClass);
}




static betterCIComparator_C betterCIComparator_instance;

static betterCIComparator_C betterCIComparator() {
  if (betterCIComparator_instance == null)
    betterCIComparator_instance = new betterCIComparator_C();
  return betterCIComparator_instance;
}

final static class betterCIComparator_C implements Comparator<String> {
  public int compare(String s1, String s2) {
    if (s1 == null) return s2 == null ? 0 : -1;
    if (s2 == null) return 1;
  
    int n1 = s1.length();
    int n2 = s2.length();
    int min = Math.min(n1, n2);
    for (int i = 0; i < min; i++) {
        char c1 = s1.charAt(i);
        char c2 = s2.charAt(i);
        if (c1 != c2) {
            c1 = Character.toUpperCase(c1);
            c2 = Character.toUpperCase(c2);
            if (c1 != c2) {
                c1 = Character.toLowerCase(c1);
                c2 = Character.toLowerCase(c2);
                if (c1 != c2) {
                    // No overflow because of numeric promotion
                    return c1 - c2;
                }
            }
        }
    }
    return n1 - n2;
  }
}


static String regexpReplace_direct(String s, String pat, String replacement) {
  Matcher m = regexp(pat, s);
  return regexpReplace_direct(m, replacement);
}
  
static String regexpReplace_direct(Matcher m, String replacement) {
  StringBuffer buf = new StringBuffer();
  while (m.find())
    m.appendReplacement(buf, replacement);
  m.appendTail(buf);
  return str(buf);
}


static Map<String, java.util.regex.Pattern> compileRegexpIC_cache = syncMRUCache(10);

static java.util.regex.Pattern compileRegexpIC(String pat) {
  java.util.regex.Pattern p = compileRegexpIC_cache.get(pat);
  if (p == null) {
    
    try {
      compileRegexpIC_cache.put(pat, p = java.util.regex.Pattern.compile(pat, Pattern.CASE_INSENSITIVE));
    } catch (PatternSyntaxException e) {
      throw rethrow(wrapPatternSyntaxException(e));
    }
  }
  return p;
}


static Matcher regexpIC(Pattern pat, String s) {
  return pat.matcher(unnull(s));
}

static Matcher regexpIC(String pat, String s) {
  return compileRegexpIC(pat).matcher(unnull(s));
}

static Pattern regexpIC(String pat) {
  return compileRegexpIC(pat);
}


static <A> Set<A> newWeakHashSet() {
  return synchroWeakHashSet();
}


static boolean jInternalFrame_iconifiable = true;

static JInternalFrame jInternalFrame() {
  return jInternalFrame("");
}

static JInternalFrame jInternalFrame(final String title) {
  return swing(new F0<JInternalFrame>() { public JInternalFrame get() { try { 
    JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame_iconifiable);
    f.setVisible(true);
    return f;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame..."; }});
}


static void setInternalFrameContents(final Component c, final Object contents) {
  { swing(new Runnable() {  public void run() { try { 
    JInternalFrame frame = getInternalFrame(c);
    if (frame == null) return;
    frame.getContentPane().removeAll();
    frame.getContentPane().setLayout(new BorderLayout());
    if (contents != null) frame.getContentPane().add(wrap(contents));
    revalidate(frame);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "JInternalFrame frame = getInternalFrame(c);\r\n    if (frame == null) return;\r\n..."; }}); }
}


static <A extends Component> A setBounds(final int x, final int y, final int w, final int h, final A a) {
  if (a != null) { swing(new Runnable() {  public void run() { try { 
    a.setBounds(x, y, w, h);
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "a.setBounds(x, y, w, h);"; }}); }
  return a;
}

static <A extends Component> A setBounds(A a, Rect r) {
  if (a != null && r != null) { swing(new Runnable() {  public void run() { try { 
    a.setBounds(toRectangle(r));
  
} catch (Exception __e) { throw rethrow(__e); } }  public String toString() { return "a.setBounds(toRectangle(r));"; }}); }
  return a;
}

static <A extends Component> A setBounds(Rect r, A a) {
  return setBounds(a, r);
}

static <A extends Component> A setBounds(A a, int x, int y, int w, int h) {
  return setBounds(x, y, w, h, a);
}


static void internalFrameDefaultPosition(JInternalFrame f) {
  f.setSize(500, 300);
  centerInternalFrame(f);
}


static int fixInternalFrame_borderTopLeft = 0;
static int fixInternalFrame_borderBottomRight = 40; // for title bar

static JInternalFrame fixInternalFrame(final JInternalFrame f) {
  return swing(new F0<JInternalFrame>() { public JInternalFrame get() { try { 
    Container c = f.getParent();
    if (c == null) return f;
    Rect r = toRect(f.getBounds());
    int a = fixInternalFrame_borderTopLeft, b = fixInternalFrame_borderBottomRight;
    Rect outer = new Rect(a, a, c.getWidth()-b, c.getHeight()-b);
    if (!rectContains(outer, r))
      f.setLocation(
        max(a, min(r.x, outer.x2())),
        max(a, min(r.y, outer.y2())));
    if (r.w > c.getWidth() || r.h > c.getHeight())
      f.setSize(c.getWidth()-a, c.getHeight()-a);
    return f;
   } catch (Exception __e) { throw rethrow(__e); } }
  public String toString() { return "Container c = f.getParent();\r\n    if (c == null) ret f;\r\n    Rect r = toRect(..."; }});
}



static JPanel jpanel(LayoutManager layout) {
  return swingNu(JPanel.class, layout);
}

static JPanel jpanel() {
  return swingNu(JPanel.class);
}


static <A> void forEach(Iterable<A> l, IVF1<A> f) {
  if (f != null && l != null) for (A a : l)
    callF(f, a);
}

static <A> void forEach(IVF1<A> f, Iterable<A> l) {
  forEach(l, f);
}

static <A> void forEach(A[] l, IVF1<A> f) {
  if (f != null && l != null) for (A a : l)
    callF(f, a);
}


static Object pcallFAll_returnFirstNotNull(Collection l, Object... args) {
  if (l != null) for (Object f : cloneList(l))
    { Object __1= pcallF(f, args); if (__1 != null) return __1; }
  return null;
}

static Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) {
  while (it.hasNext())
    { Object __2= pcallF(it.next(), args); if (__2 != null) return __2; }
  return null;
}


static boolean containsSpaces(String s) {
  return indexOf(s, ' ') >= 0;
}


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;
}


static List<String> ai_splitCamelCase(String s) {
  int j = 0;
  List<String> l = new ArrayList();
  
  // new addition
  if (isAllUpperCase(s)) { l.add(s); return l; }
  
  for (int i = 0; i < l(s); i++)
    if (i > j && isUpperCaseLetter(s.charAt(i))) {
      l.add(substring(s, j, i));
      j = i;
    }
  if (j < l(s))
    l.add(substring(s, j));
  return l;
}


static Object[] asObjectArray(Collection l) {
  return toObjectArray(l);
}


static boolean containsNulls(Collection c) {
  return contains(c, null);
}




static Matcher regexp(String pat, String s) {
  return regexp(compileRegexp(pat), unnull(s));
}

static Matcher regexp(java.util.regex.Pattern pat, String s) {
  return pat.matcher(unnull(s));
}

static java.util.regex.Pattern regexp(String pat) {
  return compileRegexp(pat);
}


static RuntimeException wrapPatternSyntaxException(PatternSyntaxException e) {
  if (e == null) return null;
  String pat = e.getPattern();
  int i = e.getIndex();
  return new RuntimeException("Regular expression error between " + multiLineQuoteWithSpaces(substring(pat, 0, i)) + " and " + multiLineQuoteWithSpaces(substring(pat, i)) + " - " + e.getMessage());
}


static <A> Set<A> synchroWeakHashSet() {
  return Collections.newSetFromMap((Map) newWeakHashMap());
}




static Rect toRect(Rectangle r) {
  return r == null ? null : new Rect(r);
}

static Rect toRect(RectangularShape r) {
  return r == null ? null : toRect(r.getBounds());
}


static Rect toRect(DoubleRect r) {
  if (r == null) return null;
  int x = iround(r.x), y = iround(r.y);
  return new Rect(x, y, iround(r.x2())-x, iround(r.y2())-y);
}


static Rect toRect(Rect r) { return r; }


static boolean rectContains(int x1, int y1, int w, int h, Pt p) {
  return p.x >= x1 && p.y >= y1 && p.x < x1+w && p.y < y1+h;
}

static boolean rectContains(Rect a, Rect b) {
  return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2();
}

static boolean rectContains(Rect a, int x, int y) {
  return a != null && a.contains(x, y);
}


static boolean isAllUpperCase(String s) {
  return hasLettersAllUpperCase(s);
}


static boolean isUpperCaseLetter(char c) {
  return Character.isUpperCase(c);
}




static String multiLineQuoteWithSpaces(String s) {
  return multiLineQuote(" " + s + " ");
}


static boolean hasLettersAllUpperCase(String s) {
  return hasLetters(s) && !containsLowerCase(s);
}




static String multiLineQuote(String s) {
  for (int i = 0; ; i++) {
    String closer = "]" + rep('=', i) + "]";
    if (!contains(s, closer))
      return "[" + rep('=', i) + "[" + s + closer;
  }
}


static boolean hasLetters(String s) {
  for (int i = 0; i < s.length(); i++)
    if (Character.isLetter(s.charAt(i)))
      return true;
  return false;
}


static boolean containsLowerCase(String s) {
  for (int i = 0; i < l(s); i++)
    if (isLowerCase(s.charAt(i)))
      return true;
  return false;
}




static boolean isLowerCase(char c) {
  return Character.isLowerCase(c);
}








static class TransferableImage implements Transferable {
  Image i;

  TransferableImage(Image i) {
  this.i = i;}

  public Object getTransferData( DataFlavor flavor )
  throws UnsupportedFlavorException, IOException {
      if ( flavor.equals( DataFlavor.imageFlavor ) && i != null ) {
          return i;
      }
      else {
          throw new UnsupportedFlavorException( flavor );
      }
  }

  public DataFlavor[] getTransferDataFlavors() {
      DataFlavor[] flavors = new DataFlavor[ 1 ];
      flavors[ 0 ] = DataFlavor.imageFlavor;
      return flavors;
  }

  public boolean isDataFlavorSupported( DataFlavor flavor ) {
      DataFlavor[] flavors = getTransferDataFlavors();
      for ( int i = 0; i < flavors.length; i++ ) {
          if ( flavor.equals( flavors[ i ] ) ) {
              return true;
          }
      }

      return false;
  }
}
static class MultiMap<A,B> {
  Map<A, List<B>> data = new HashMap<A, List<B>>();
  
  MultiMap() {}
  MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); }
  MultiMap(MultiMap<A, B> map) { putAll(map); }
  MultiMap(Map<A, List<B>> data) {
  this.data = data;}

  void put(A key, B value) { synchronized(data) {
    List<B> list = data.get(key);
    if (list == null)
      data.put(key, list = _makeEmptyList());
    list.add(value);
  }}

  void add(A key, B value) { put(key, value); }

  void addAll(A key, Collection<B> values) { putAll(key, values); }
  
  void addAllIfNotThere(A key, Collection<B> values) { synchronized(data) {
    for (B value : values)
      setPut(key, value);
  }}
  
  void setPut(A key, B value) { synchronized(data) {
    if (!containsPair(key, value))
      put(key, value);
  }}
  
  boolean containsPair(A key, B value) { synchronized(data) {
    return get(key).contains(value);
  }}
  
  void putAll(Collection<A> keys, B value) { synchronized(data) {
    for (A key : unnullForIteration(keys))
      put(key, value);
  }}

  void putAll(A key, Collection<B> values) { synchronized(data) {
    if (nempty(values)) getActual(key).addAll(values);
  }}

  void putAll(Iterable<Pair<A, B>> pairs) { synchronized(data) {
    for (Pair<A, B> p : unnullForIteration(pairs))
      put(p.a, p.b);
  }}
  
  void removeAll(A key, Collection<B> values) { synchronized(data) {
    for (B value : values)
      remove(key, value);
  }}
  
  List<B> get(A key) { synchronized(data) {
    List<B> list = data.get(key);
    return list == null ? Collections.<B> emptyList() : list;
  }}

  List<B> getOpt(A key) { synchronized(data) {
    return data.get(key);
  }}

  // returns actual mutable live list
  // creates the list if not there
  List<B> getActual(A key) { synchronized(data) {
    List<B> list = data.get(key);
    if (list == null)
      data.put(key, list = _makeEmptyList());
    return list;
  }}
 
  void clean(A key) { synchronized(data) {
    List<B> list = data.get(key);
    if (list != null && list.isEmpty())
      data.remove(key);
  }}

  Set<A> keySet() { synchronized(data) {
    return data.keySet();
  }}

  Set<A> keys() { synchronized(data) {
    return data.keySet();
  }}

  void remove(A key) { synchronized(data) {
    data.remove(key);
  }}

  void remove(A key, B value) { synchronized(data) {
    List<B> list = data.get(key);
    if (list != null) {
      list.remove(value);
      if (list.isEmpty())
        data.remove(key);
    }
  }}

  void clear() { synchronized(data) {
    data.clear();
  }}

  boolean containsKey(A key) { synchronized(data) {
    return data.containsKey(key);
  }}

  B getFirst(A key) { synchronized(data) {
    List<B> list = get(key);
    return list.isEmpty() ? null : list.get(0);
  }}
  
  void addAll(MultiMap<A, B> map) { putAll(map); }
  
  void putAll(MultiMap<A, B> map) { synchronized(data) {
    for (A key : map.keySet())
      putAll(key, map.get(key));
  }}
  
  void putAll(Map<A, B> map) { synchronized(data) {
    if (map != null) for (Map.Entry<A, B> e : map.entrySet())
      put(e.getKey(), e.getValue());
  }}
  
  int keysSize() { synchronized(data) { return l(data); }}
  
  // full size - note: expensive operation
  int size() { synchronized(data) {
    int n = 0;
    for (List l : data.values())
      n += l(l);
    return n;
  }}
  
  // expensive operation
  List<A> reverseGet(B b) { synchronized(data) {
    List<A> l = new ArrayList();
    for (A key : data.keySet())
      if (data.get(key).contains(b))
        l.add(key);
    return l;
  }}
  
  Map<A, List<B>> asMap() { synchronized(data) {
    return cloneMap(data);
  }}
  
  boolean isEmpty() { synchronized(data) { return data.isEmpty(); }}
  
  // override in subclasses
  List<B> _makeEmptyList() {
    return new ArrayList();
  }
  
  // returns live lists
  Collection<List<B>> allLists() {
    synchronized(data) {
      return new ArrayList(data.values());
    }
  }
  Collection<List<B>> values() { return allLists(); }
  
  List<B> allValues() {
    return concatLists(data.values());
  }
  
  Object mutex() { return data; }
  
  public String toString() { return "mm" + str(data); }
}
static class DoubleRect {
  double x, y, w, h;
  
  DoubleRect() {}
  DoubleRect(Rectangle r) {
    x = r.x;
    y = r.y;
    w = r.width;
    h = r.height;
  }
  DoubleRect(double x, double y, double w, double h) {
  this.h = h;
  this.w = w;
  this.y = y;
  this.x = x;}
  
  public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
  
  public String toString() {
    return x + "," + y + " / " + w + "," + h;
  }
  
  double x2() { return x + w; }
  double y2() { return y + h; }
  
  boolean contains(Pt p) {
    return contains(p.x, p.y);
  }
  
  boolean contains(double _x, double _y) {
    return _x >= x && _y >= y && _x < x+w && _y < y+h;
  }
  
  boolean empty() { return w <= 0 || h <= 0; }
}
static class T3<A, B, C> {
  A a;
  B b;
  C c;
  
  T3() {}
  T3(A a, B b, C c) {
  this.c = c;
  this.b = b;
  this.a = a;}
  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) + ")";
  }
}


static <A, B> Map<A, B> putAll(Map<A, B> a, Map<? extends A,? extends B> b) {
  if (a != null && b != null) a.putAll(b);
  return a;
}


static <A, B> MultiMap<A, B> putAll(MultiMap<A, B> a, Map<? extends A,? extends B> b) {
  if (a != null) a.putAll((Map) b);
  return a;
}


static <A, B> Map<A, B> putAll(Map<A, B> a, Object... b) {
  if (a != null)
    litmap_impl(a, b);
  return a;
}



static <A, B> Set<A> keySet(Map<A, B> map) {
  return map == null ? new HashSet() : map.keySet();
}

static Set keySet(Object map) {
  return keys((Map) map);
}




  static <A, B> Set<A> keySet(MultiMap<A, B> mm) {
    return mm.keySet();
  }





static <A> A reverseGet(List<A> l, int idx) {
  if (l == null || idx < 0) return null;
  int n = l(l);
  return idx < n ? l.get(n-1-idx) : null;
}


static <A, B> Map<A, B> cloneMap(Map<A, B> map) {
  if (map == null) return new HashMap();
  // assume mutex is equal to map
  synchronized(map) {
    return map instanceof TreeMap ? new TreeMap((TreeMap) map) // copies comparator
      : map instanceof LinkedHashMap ? new LinkedHashMap(map)
      : new HashMap(map);
  }
}

static <A, B> List<B> cloneMap(Iterable<A> l, IF1<A, B> f) {
  List x = emptyList(l);
  if (l != null) for (A o : cloneList(l))
    x.add(f.get(o));
  return x;
}


static <A, B> Collection<B> values(Map<A, B> map) {
  return map == null ? emptyList() : map.values();
}

// convenience shortcut for values_gen
static Collection values(Object map) {
  return values((Map) map);
}


static <A, B> Collection<B> values(MultiMap<A, B> mm) {
  return mm == null ? emptyList() : concatLists(values(mm.data));
}





static String quoteBorderless(Object o) {
  if (o == null) return "null";
  return quoteBorderless(str(o));
}

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();
}
  
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);
  }
}



}